Ruby Standard Library Documentation

Introduction

Welcome to the Ruby Standard Library Documentation collection, brought to you by the ruby-doc project. Whether you are browsing online or offline, we hope that your use of Ruby's standard library will become more productive as a result of this effort.

ruby-doc is a project dedicated to creating and collecting documentation on Ruby. You can find collections of articles and other resources at the website.

stdlib-doc is a RubyForge project that converts Ruby source code into this documentation you are looking at. It also tracks the status of the documentation effort; you can see some of that effort in the Status Report page.

What You'll Find Here

Each package in the Ruby standard library (found in lib/ directory of the Ruby source code, or lib/ruby/1.x/ of a Ruby installation) has been run through RDoc and the results have been collected here.

ruby-doc volunteers and library authors add comments to the Ruby source code CVS, and it is those comments that RDoc captures for display in this collection. As there are many libraries and few volunteers, this is a long task. To get some idea of what we've done and what we haven't, we use the stdlib-doc project mentioned above, whereby each file has a documentation score. What you need to know is that

  • bold libraries in the table of contents are well documented, and
  • italic libraries are not.

Because the source code comments go straight into Ruby's CVS, the only way to get up-to-date documentation is to use the latest Ruby code as a source. There are two important side effects here:

  • the documentation may be ahead of Ruby 1.8.0, which many users will have, and
  • the documentation is certainly out of step with Ruby 1.6.x.

The ruby_1_8 branch of the Ruby source code is used to produce the documentation. So you will see the latest that Ruby 1.8.x has to offer, not the experimental 1.9.

Downloading and Installing

You are welcome to browse this documentation online for as long as you like, but should you wish to download a copy for yourself, you may.

When you download a tarball or zip file and unpack it, you'll see a directory ruby-doc-stdlib-0.7.1/, for instance. You can point your browser to index.html and browse away, or you can install the documentation to a central location. The advantage of installing it is that when you upgrade your offline copy, you can reinstall and you will still find the documentation in that same central place, like /usr/local/doc/ruby/stdlib/index.html. It's up to you.

If you do wish to install it, just follow these steps:

  • change directory to ruby-doc-stdlib-x.y.z
  • run ruby install.rb

It will remove any existing documentation in the target directory (RDoc cruft can accumulate over time) and copy over the latest and greatest.

In the future there may be a command that searches for updates and installs them. If anyone wants to contribute such a command, feel free.

Credits

The documentation itself has been created by Gavin Sinclair, William Webber, Lyle Johnson, James Edward Gray II, and library authors. Individual library files usually have code and documentation credits.

ruby-doc.org was created and is maintained by James Britt.

Gavin Sinclair wrote the software (ruby stdlib-doc.rb gendoc --all) to generate this webpage (thanks, Amrita!).

Thanks to Dave Thomas for RDoc, without which this project would be impossible, and for Programming Ruby, which provided inspiration for documentation, as well as some actual text.


Packages Overview

Ruby Standard Library Doc. Packages Overview

Please select a package from the following list.

abbrev
Calculates the set of unique abbreviations for a given set of strings.
base64
Methods for base64-encoding and -decoding strings.
benchmark
Contains routines for benchmarking code.
bigdecimal
Arbitrary-precision arithmetic.
cgi
CGI library, including methods for query parsing, HTML generation and session handling.
complex
Implements a complex number type, Complex.
csv
Read and write CSV (comma separated values) data.
curses
Interface to the "curses" character-based interface library.
date
Implements the Date class.
dbm
Read and write 'db' files.
delegate
Simplifies delegation to methods of other classes.
digest
MD5 and SHA1 digest implementations.
dl
"Interface to the Dynamic Loader, for creating extensions."
drb
Distributed Ruby. Talk to objects across a network.
English
"English-language long names for Ruby's special variables."
enumerator
Flexible enumeration capabilities.
erb
"Templating system whereby you embed Ruby code in text/HTML/..."
etc
Access to UNIX users and groups information.
fcntl
Provides constant definitions for IO#fcntl.
fileutils
Utility module for copying, moving, renaming files, etc.
finalize
find
Recursively descend directories.
forwardable
Method-level delegation.
ftools
Similar to, but older than, fileutils.
gdbm
Read and write GNU 'db' files.
generator
Converts an internal iterator to an external iterator.
getoptlong
A common library for parsing command-line options. See optparse for a stronger Ruby solution.
gserver
Generic server.
iconv
importenv
Imports environment variables as global variables.
io/wait
ipaddr
Manipulate IP addresses.
jcode
Handle Japanese strings.
logger
Simple logging mechanism.
mailread
mathn
Make all numeric classes work well together.
matrix
Defines the Matrix and Vector classes.
mkmf
Generate Makefiles for Ruby extensions.
monitor
Add monitor function to an arbitrary object.
mutex_m
net/ftp
FTP library for accessing remote files.
net/http
HTTP library for accessing web pages.
net/imap
IMAP library for accessing email on a server.
net/pop
POP library for accessing email on a server.
net/smtp
SMTP library for sending email.
net/telnet
Telnet library for executing commands remotely.
nkf
observer
Implements the observer pattern; objects can be notified of changes to other objects.
open-uri
Allows file-like access to URIs like "ftp://server/filename".
open3
Run external commands and have access to stdin, stdout, and stderr.
openssl
Secure socket layer, including HTTP, FTP, and Telnet implementations.
optparse
A more advanced command-line options parsing library than getoptlong.
ostruct
Open structs. You can add attributes dynamically.
parsedate
A module for extracting date information from a String.
pathname
Object-oriented pathname.
ping
Simple 'ping' implementation.
pp
Implements Kernel.pp so you can pretty-print any object.
prettyprint
Implements a pretty-printing algorithm. See 'pp'.
profile
Runtime profiler.
profiler
Runtime profiling library.
pstore
Simple object-oriented database using Marshal.
pty
Executes commands as if their standard I/O is connected to ttys.
racc
"LALR(1) parser generator for Ruby."
racc/parser
rational
Implements a rational number type, Rational.
rdoc
"Ruby's API documentation generator."
readbytes
Implements IO#readbytes.
readline
Command-line editing and history.
resolv
Find IP address from hostname, or vice versa, and more.
resolv-replace
rexml
Pure-Ruby XML parser and emitter.
rinda
A Ruby implementation of the Linda distibuted computing paradigm.
rss
RSS (Rich Site Syndicator) parser and emitter.
runit
Older unit testing framework. Taken over by test/unit.
scanf
"Analogous to C's scanf. Reads formatted data."
sdbm
Yet another 'db' file interface.
set
Implements the Set data type.
singleton
Implements the singleton design pattern, whereby a certain class has only one instance.
soap
Implements the SOAP protocol.
socket
Implements several socket classes for UDP, TCP, UNIX, SOCKS, as well as a TCPServer class.
stringio
Implements StringIO, which allows IO-like operations on a String-like object.
strscan
A fast string scanner.
syck
Fast YAML implementation.
sync
Phase lock with counter.
syslog
Wrapper for UNIX Syslog system calls.
tcltklib
tempfile
Create and use a temporary file.
test/unit
"Ruby's standard unit testing framework."
thread
Support for threads, including Mutex, ConditionVariable, and Queue.
thwait
Thread synchronization class.
time
Extends built-in Time class to support various standard time formats.
timeout
Ensures some code completes within a certain time, or throws exception.
tk
tmpdir
Retrieve temporary directory path.
tracer
Trace program execution.
tsort
Topological sorting for strongly connected components.
un
Utility module for file operations in command-line scripts.
uri
Universal Resource Identifier implementation.
weakref
Implements weak references.
webrick
A servlet container and self-contained web server.
Win32API
Interface to Windows registry.
win32ole
Interface to Win32 OLE automation.
wsdl
Web Services Description Language.
xmlrpc
XML RPC (remote procedure call) client and server implementations.
xsd
XML Schema Definition.
yaml
Data serialization format designed for ease of human use.
zlib
Interface to UNIX zlib (gzip streams).


History

Ruby Standard Library Doc. History

v0.10.1

(2005-10-29)

  • documentation added: enumerator, etc, fcntl, rational, pstore (thanks to James Gray, Kev Jackson, and Mathew Pobox)
  • changes to site CSS to improve readability
  • added 'profile' and 'profiler' to package list (no documentation though)

v0.10.0

(2005-10-12)

  • first update in about 10 months
  • therefore, status report probably inaccurate; will hopefully fix soon
  • Delegate and Forwardable documentation updated (that's what spurred this release)
  • some other documentation probably updated too
  • most packages now have a one-line description (see "Packages" link)

v0.9.13

(2004-12-09)

  • workaround recent RDoc problem that's hiding h2 headings

v0.9.12

(2004-11-30)

  • included, but not documented, rss.rb

v0.9.11

(2004-11-27)

  • included abbrev.rb (it was already documented)

v0.9.10

(2004-11-27)

  • added erb documentation (thanks James Edward Gray II)

v0.9.9

(2004-11-24)

  • regenerated, since it's been a while; there may or may not be any changes

v0.9.8

(2004-05-17)

  • recovered test/unit documentation
  • apply higher scores applied to date, drb, and optparse

v0.9.7

(2004-05-09)

  • improved nearly all net/* libraries (rearranged, clarified, and corrected documentation)

v0.9.6

(2004-05-05)

  • documented gserver
  • linked to xmlrpc documentation
  • Doug Kearns corrected many typos

v0.9.5

(2004-04-11)

  • removed RDoc links from introduction

v0.9.4

(2004-03-24)

  • added uri documentation (thanks Dmitry Sabanin)

v0.9.3

(2004-02-22)

  • English.rb now rendered properly
  • improved strscan
  • documented zlib
  • documented ostruct
  • removed browser comparison
  • no longer provide ZIP file

v0.9.2

(2004-02-17)

  • added rinda documentation (thanks Hugh Sasse)
  • improved generator.rb
  • documented strscan

v0.9.0

(2004-02-13)

  • MAJOR CHANGE: now includes the compiled parts of the standard library found in 'ext'. They are not documented, nor are they accounted for in the status database, but at least they are there.
  • updated package list and status database (wsdl, xsd, soap, ...)
  • documented base64.rb (thanks Dave Thomas), ftools.rb (thanks Zachary Landau)
  • improved fileutils.rb, test/unit.rb
  • now sourced from ruby_1_8 branch, not CVS HEAD

v0.9.1

(2004-02-13)

  • minor corrections

v0.8.7

(2004-01-11)

  • Fixed CSS bug (only visible in Mozilla)

v0.8.6

(2004-01-06)

  • enhanced logger.rb

v0.8.5

(2003-12-31)

  • documented pathname.rb

v0.8.4

(2003-12-28)

  • documented optparse.rb

v0.8.3

(2003-12-15)

  • last release before history added


Status Report

Ruby Standard Library Doc. Status Report

Introduction

The following is a status report on nearly all of the important files in the Ruby standard library. Some are missing and will be added in time.

The priority indicates how important it is to properly document the given file. The status shows whether it has been attempted or not. The score is a mark out of 10 on how complete the documentation is.

If you'd like to help, pick a high-priority open file whose usage you are familiar with and start documenting! Grab the latest version from CVS, add some RDoc comments to it, and submit it to Gavin Sinclair. Several files already have comprehensive RD comments, so the conversion to RDoc is not difficult, just time-consuming. These are the ideal files for a first-timer.

The Report

ext/enumerator/enumerator.c | Pri: high | Stat: done | Score: 7
Some methods unclear. Overall example usage would be good.
ext/etc/etc.c | Pri: high | Stat: done | Score: 8
Add example usage to the module documentation and it's perfect.
ext/fcntl/fcntl.c | Pri: medium | Stat: done | Score: 10
ext/iconv/iconv.c | Pri: medium | Stat: done | Score: 7
Mostly done; one or two things to iron out.
ext/strscan/strscan.c | Pri: medium | Stat: done | Score: 9
One FIXME, and #initialize might be incorrectly documented.
ext/zlib/zlib.c | Pri: high | Stat: done | Score: 6
Just entered docs from author's RD documentation, improved English and formatting, and added class/module docs. Some undocumented methods and some unclear ones. More examples and general effort needed.
lib/English.rb | Pri: medium | Stat: done | Score: 10
lib/abbrev.rb | Pri: medium | Stat: done | Score: 10
lib/base64.rb | Pri: medium | Stat: done | Score: 9
A couple of methods are unclear in their purpose, which some better documentation could address.
lib/benchmark.rb | Pri: high | Stat: done | Score: 9.5
Benchmark.benchmark is a bit unclear.
lib/cgi.rb | Pri: high | Stat: done | Score: 10
lib/cgi/session.rb | Pri: high | Stat: done | Score: 9
lib/cgi/session/pstore.rb | Pri: high | Stat: done | Score: 9
lib/complex.rb | Pri: high | Stat: done | Score: 9
lib/csv.rb | Pri: high | Stat: done | Score: 7
Looks pretty complete, but poorly formatted.
lib/date.rb | Pri: high | Stat: done | Score: 7
Awaiting RDoc :def: feature to document dynamic methods.
lib/date/format.rb | Pri: high | Stat: open | Score: -
I'm not sure what it does, but it's probably pretty important.
lib/delegate.rb | Pri: high | Stat: done | Score: 9
lib/drb/acl.rb | Pri: medium | Stat: open | Score: -
lib/drb/drb.rb | Pri: high | Stat: done | Score: 10
Extremely well documented; but the rest of the drb package remains to be done.
lib/drb/eq.rb | Pri: medium | Stat: open | Score: -
lib/drb/extserv.rb | Pri: medium | Stat: open | Score: -
lib/drb/extservm.rb | Pri: medium | Stat: open | Score: -
lib/drb/gw.rb | Pri: medium | Stat: open | Score: -
lib/drb/invokemethod.rb | Pri: medium | Stat: open | Score: -
lib/drb/observer.rb | Pri: medium | Stat: open | Score: -
lib/drb/ssl.rb | Pri: medium | Stat: open | Score: -
lib/drb/timeridconv.rb | Pri: medium | Stat: open | Score: -
lib/e2mmap.rb | Pri: low | Stat: open | Score: 3
Most of the documentation is there, but it's a weird library, probably only used by other libraries, and therefore a low priority. Not in good RDoc format.
lib/erb.rb | Pri: low | Stat: done | Score: 9
A few unimportant methods that should perhaps be documented.
lib/eregex.rb | Pri: low | Stat: open | Score: -
Not a serious file.
lib/fileutils.rb | Pri: high | Stat: done | Score: 10
lib/finalize.rb | Pri: medium | Stat: open | Score: 3
Skimpy RDoc comments exist. Need examples, etc.
lib/find.rb | Pri: high | Stat: done | Score: 10
lib/forwardable.rb | Pri: high | Stat: done | Score: 9
lib/ftools.rb | Pri: high | Stat: done | Score: 9
One or two methods are hard to explain. Bad variable choices don't help. But it's done.
lib/generator.rb | Pri: | Stat: done | Score: 9
Looks fairly well documented. Needs review.
lib/getoptlong.rb | Pri: high | Stat: open | Score: 3
Skimpy RDoc comments exist. Need examples, etc. Also explain that despite the wide use of getoptlong, optparse is more advanced.
lib/gserver.rb | Pri: medium | Stat: done | Score: 8
Class-level doco is sufficient to grok this, but method doco would be nice as well.
lib/ipaddr.rb | Pri: medium | Stat: done | Score: 7
Formatting needs work.
lib/jcode.rb | Pri: medium | Stat: open | Score: -
File-level comment explaining what it is and does would be nice.
lib/logger.rb | Pri: high | Stat: done | Score: 10
All done. Could be better in some way, I suppose, but it's an easy library to understand.
lib/mailread.rb | Pri: low | Stat: open | Score: -
Never heard of it. Looks good for its task, though (reading a whole mbox file is my guess).
lib/mathn.rb | Pri: medium | Stat: open | Score: -
Not a commonly used/mentioned library, but looks OK. It loads 'complex', 'rational', and 'matrix', and defines some methods for inter-operation.
lib/matrix.rb | Pri: high | Stat: done | Score: 9
A couple of todos at EOF.
lib/mkmf.rb | Pri: high | Stat: open | Score: -
Not much of a library, but some usage notes at the file level would be good.
lib/monitor.rb | Pri: medium | Stat: done | Score: 4
Serious issues remain. Is it superseded by something? (Wishful thinking.)
lib/mutex_m.rb | Pri: medium | Stat: open | Score: 1
Some file-level documentation exists.
lib/net/ftp.rb | Pri: high | Stat: done | Score: 9
A few things to tidy up.
lib/net/http.rb | Pri: high | Stat: done | Score: 9
Some formatting errors.
lib/net/imap.rb | Pri: high | Stat: done | Score: 10
lib/net/pop.rb | Pri: high | Stat: done | Score: 10
lib/net/smtp.rb | Pri: high | Stat: done | Score: 10
lib/net/telnet.rb | Pri: high | Stat: done | Score: 10
lib/observer.rb | Pri: high | Stat: done | Score: 9
Put examples etc. at class level, not file level.
lib/open-uri.rb | Pri: high | Stat: open | Score: 6
Good examples, but some cleanup to be done.
lib/open3.rb | Pri: high | Stat: open | Score: -
Not much work to do here.
lib/optparse.rb | Pri: high | Stat: done | Score: 7
Good documentation of OptionParser *class*, not of methods. The latter is not really needed, as the usage example tells you all you need to know. Still, should finish it off at some stage.
lib/ostruct.rb | Pri: high | Stat: done | Score: 10
lib/parsedate.rb | Pri: high | Stat: open | Score: -
Easy.
lib/pathname.rb | Pri: medium | Stat: done | Score: 10
All done. Many methods merely say "See FileTest.xyz", but that doesn't matter.
lib/ping.rb | Pri: medium | Stat: open | Score: 9
Just some rearranging here and you're done.
lib/pp.rb | Pri: medium | Stat: open | Score: -
Thoroughly commented in RD.
lib/prettyprint.rb | Pri: low | Stat: open | Score: -
I doubt it's of use to many users; it's used by 'pp'.
lib/pstore.rb | Pri: high | Stat: open | Score: 9
lib/racc/parser.rb | Pri: low | Stat: open | Score: -
I don't really know what this is, and it looks tough.
lib/rational.rb | Pri: high | Stat: done | Score: 9
lib/rdoc/* | Pri: medium | Stat: open | Score: -
Not really relevant to your average stdlib user (certainly not the internals), but we should document the programmatic interface.
lib/readbytes.rb | Pri: low | Stat: open | Score: -
Easy.
lib/resolv-replace.rb | Pri: medium | Stat: open | Score: -
Easy.
lib/resolv.rb | Pri: high | Stat: open | Score: -
Difficult, though RDed already.
lib/rinda/rinda.rb | Pri: medium | Stat: open | Score: 5
Methods are documented in two of three classes. Introduction required.
lib/rinda/ring.rb | Pri: medium | Stat: open | Score: -
lib/rinda/tuplespace.rb | Pri: medium | Stat: open | Score: 5
Methods are documented in two of three classes. Introduction required.
lib/rss/* | Pri: high | Stat: open | Score: 1
Nothing more than a link to a tutorial at the moment.
lib/scanf.rb | Pri: high | Stat: open | Score: -
Thoroughly RDed.
lib/set.rb | Pri: high | Stat: done | Score: 10
lib/shell.rb | Pri: medium | Stat: open | Score: -
Nothing there at the moment.
lib/shellwords.rb | Pri: low | Stat: done | Score: 9
lib/singleton.rb | Pri: high | Stat: open | Score: 7
Pretty easy.
lib/soap/* | Pri: | Stat: open | Score: -
lib/sync.rb | Pri: medium | Stat: open | Score: -
Looks difficult.
lib/tempfile.rb | Pri: high | Stat: open | Score: 7
Some improvements to be made.
lib/test/unit.rb | Pri: | Stat: done | Score: 10
lib/test/unit/* | Pri: | Stat: open | Score: -
Must review which files need to be documented.
lib/thread.rb | Pri: high | Stat: done | Score: 7
First pass; issues remain.
lib/thwait.rb | Pri: medium | Stat: done | Score: 9
Need to ensure correctness.
lib/time.rb | Pri: high | Stat: done | Score: 10
lib/timeout.rb | Pri: high | Stat: open | Score: -
Easy.
lib/tmpdir.rb | Pri: medium | Stat: open | Score: -
Pretty easy.
lib/tracer.rb | Pri: low | Stat: open | Score: -
lib/tsort.rb | Pri: medium | Stat: done | Score: 8
Lyle did a good job; just need to check consistency.
lib/un.rb | Pri: medium | Stat: open | Score: -
Pretty easy.
lib/uri.rb | Pri: medium | Stat: done | Score: 8
Some improvements possible: background, roadmap, examples; reduce some of the formalism (not all); some English and formatting corrections.
lib/uri/common.rb | Pri: medium | Stat: done | Score: 8
See lib/uri.rb.
lib/uri/ftp.rb | Pri: medium | Stat: done | Score: 8
See lib/uri.rb.
lib/uri/generic.rb | Pri: medium | Stat: done | Score: 8
See lib/uri.rb.
lib/uri/http.rb | Pri: medium | Stat: done | Score: 8
See lib/uri.rb.
lib/uri/https.rb | Pri: medium | Stat: done | Score: 8
See lib/uri.rb.
lib/uri/ldap.rb | Pri: medium | Stat: done | Score: 8
See lib/uri.rb.
lib/uri/mailto.rb | Pri: medium | Stat: done | Score: 8
See lib/uri.rb.
lib/weakref.rb | Pri: high | Stat: open | Score: -
Usage example is there.
lib/webrick.rb | Pri: high | Stat: open | Score: -
lib/webrick/* | Pri: | Stat: open | Score: -
lib/wsdl/* | Pri: high | Stat: open | Score: -
lib/xmlrpc/* | Pri: high | Stat: done | Score: 6
Only a link to the project ('xmlrpc4r') website, which contains full documentation.
lib/xsd/* | Pri: high | Stat: open | Score: -
lib/yaml.rb | Pri: high | Stat: open | Score: -
Should thoroughly document the YAML module.
lib/yaml/* | Pri: | Stat: open | Score: -


Module: Abbrev

Module | Abbrev
In: | 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

[Source]

# File 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


Class: Array

Class | Array
In: | abbrev.rb
Parent: | Object

Methods

abbrev

Public Instance methods

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" }

[Source]

# File abbrev.rb, line 90
  def abbrev(pattern = nil)
    Abbrev::abbrev(self, pattern)
  end


File: abbrev.rb

abbrev.rb

Path: | abbrev.rb
Last Update: | Sat Oct 15 23:44:27 AUS Eastern Standard Time 2005


Module: Base64

Module | Base64
In: | 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"
   puts Base64.b64encode(data)

Generates:

   Tm93IGlzIHRoZSB0aW1lIGZvciBhbGwgZ29vZCBjb2RlcnMKdG8gbGVhcm4g
   UnVieQ==

[Source]

# File base64.rb, line 112
  def b64encode(bin, len = 60)
    encode64(bin).scan(/.{1,#{len}}/o) do
      print $&, "\n"
    end
  end
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...

[Source]

# File base64.rb, line 58
  def decode64(str)
    str.unpack("m")[0]
  end
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.

[Source]

# File 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(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==

[Source]

# File base64.rb, line 96
  def encode64(bin)
    [bin].pack("m")
  end


File: base64.rb

base64.rb

Path: | base64.rb
Last Update: | Sat Oct 15 23:44:27 AUS Eastern Standard Time 2005

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


Module: Benchmark

Module | Benchmark
In: | 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)

[Source]

# File 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(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)

[Source]

# File benchmark.rb, line 206
  def bm(label_width = 0, *labels, &blk) # :yield: report
    benchmark(" "*label_width + CAPTION, label_width, FMTSTR, *labels, &blk)
  end
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.

[Source]

# File 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(label = "") {|| ...}

Returns the time used to execute the given block as a Benchmark::Tms object.

[Source]

# File 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() {|| ...}

Returns the elapsed real time used to execute the given block.

[Source]

# File benchmark.rb, line 306
  def realtime(&blk) # :yield:
    Benchmark::measure(&blk).real
  end


Class: Benchmark::Tms

Class | Benchmark::Tms
In: | benchmark.rb
Parent: | Object

A data object, representing the times associated with a benchmark measurement.

Methods

* + - / add add! format 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.

[Source]

# File 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

Public Instance methods

*(x)

Returns a new Tms object obtained by memberwise multiplication of the individual times for this Tms object by x.

[Source]

# File benchmark.rb, line 468
    def *(x); memberwise(:*, x) end
+(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.

[Source]

# File benchmark.rb, line 455
    def +(other); memberwise(:+, other) end
-(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.

[Source]

# File benchmark.rb, line 462
    def -(other); memberwise(:-, other) end
/(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.

[Source]

# File benchmark.rb, line 475
    def /(x); memberwise(:/, x) end
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).

[Source]

# File benchmark.rb, line 432
    def add(&blk) # :yield:
      self + Benchmark::measure(&blk)
    end
add!()

An in-place version of add.

[Source]

# File 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
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.

[Source]

# File 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_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.

[Source]

# File benchmark.rb, line 519
    def to_a
      [@label, @utime, @stime, @cutime, @cstime, @real]
    end
to_s()

Same as format.

[Source]

# File benchmark.rb, line 509
    def to_s
      format
    end


File: benchmark.rb

benchmark.rb

Path: | benchmark.rb
Last Update: | Sat Oct 15 23:44:27 AUS Eastern Standard Time 2005

Included Modules

Benchmark


Class: BigDecimal

Class | BigDecimal
In: | bigdecimal/lib/bigdecimal/util.rb bigdecimal/bigdecimal.c
Parent: | Numeric

Methods

!= % * ** + +@ - -@ / < <= <=> == === > >= _dump _load abs add ceil coerce div divmod double_fig dup eql? exponent finite? fix floor frac hash induced_from infinite? inspect limit mode modulo mult nan? new nonzero? power precs quo remainder round sign split sqrt sub to_digits to_f to_i to_int to_r to_s truncate ver zero?

Public Class methods

_load(p1)
double_fig()
induced_from(p1)
limit(...)
mode(...)
new(...)
ver()

**** BigDecimal version ****

[Source]

/*
 *  **** BigDecimal version ****
 */
static VALUE
BigDecimal_version(VALUE self)
{
    /*
     * 1.0.0: Ruby 1.8.0
     * 1.0.1: Ruby 1.8.1
    */
    return rb_str_new2("1.0.1");
}

Public Instance methods

!=(p1)
%(p1)
*(p1)
**(p1)
+(p1)
+@()
-(p1)
-@()
/(p1)
<(p1)
<=(p1)
<=>(p1)
==(p1)
===(p1)
>(p1)
>=(p1)
_dump(...)
abs()
add(p1, p2)
ceil(...)
coerce(p1)
div(...)
divmod(p1)
dup()
eql?(p1)
exponent()
finite?()
fix()
floor(...)
frac()
hash()
infinite?()
inspect()
modulo(p1)
mult(p1, p2)
nan?()
nonzero?()
power(p1)
precs()
quo(p1)
remainder(p1)
round(...)
sign()
split()
sqrt(p1)
sub(p1, p2)
to_digits()

to "nnnnnn.mmm" form digit string Use BigDecimal#to_s("F") instead.

[Source]

# File bigdecimal/lib/bigdecimal/util.rb, line 35
  def to_digits
     if self.nan? || self.infinite? || self.zero?
        self.to_s
     else
       i       = self.to_i.to_s
       s,f,y,z = self.frac.split
       i + "." + ("0"*(-z)) + f
     end
  end
to_f()
to_i()
to_int()
to_r()

Convert BigDecimal to Rational

[Source]

# File bigdecimal/lib/bigdecimal/util.rb, line 46
  def to_r
     sign,digits,base,power = self.split
     numerator = sign*digits.to_i
     denomi_power = power - digits.size # base is always 10
     if denomi_power < 0
        denominator = base ** (-denomi_power)
     else
        denominator = base ** denomi_power
     end
     Rational(numerator,denominator)
  end
to_s(...)
truncate(...)
zero?()


Module: BigMath

Module | BigMath
In: | bigdecimal/lib/bigdecimal/math.rb

Contents:

  sqrt(x, prec)
  sin (x, prec)
  cos (x, prec)
  atan(x, prec)  Note: |x|<1, x=0.9999 may not converge.
  exp (x, prec)
  log (x, prec)
  PI  (prec)
  E   (prec) == exp(1.0,prec)

where:

  x    ... BigDecimal number to be computed.
           |x| must be small enough to get convergence.
  prec ... Number of digits to be obtained.

Usage:

  require "bigdecimal"
  require "bigdecimal/math.rb"
  include BigMath
  a = BigDecimal((PI(100)/2).to_s)
  puts sin(a,100) # => 0.10000000000000000000......E1

Methods

E PI atan cos exp log sin sqrt

Public Instance methods

E(prec)

[Source]

# File bigdecimal/lib/bigdecimal/math.rb, line 179
  def E(prec)
    raise ArgumentError, "Zero or negative precision for E" if prec <= 0
    n    = prec + BigDecimal.double_fig
    one  = BigDecimal("1")
    y  = one
    d  = y
    z  = one
    i  = 0
    while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0)
      m = BigDecimal.double_fig if m < BigDecimal.double_fig
      i += 1
      z *= i
      d  = one.div(z,m)
      y += d
    end
    y
  end
PI(prec)

[Source]

# File bigdecimal/lib/bigdecimal/math.rb, line 141
  def PI(prec)
    raise ArgumentError, "Zero or negative argument for PI" if prec <= 0
    n      = prec + BigDecimal.double_fig
    zero   = BigDecimal("0")
    one    = BigDecimal("1")
    two    = BigDecimal("2")

    m25    = BigDecimal("-0.04")
    m57121 = BigDecimal("-57121")

    pi     = zero

    d = one
    k = one
    w = one
    t = BigDecimal("-80")
    while d.nonzero? && ((m = n - (pi.exponent - d.exponent).abs) > 0)
      m = BigDecimal.double_fig if m < BigDecimal.double_fig
      t   = t*m25
      d   = t.div(k,m)
      k   = k+two
      pi  = pi + d
    end

    d = one
    k = one
    w = one
    t = BigDecimal("956")
    while d.nonzero? && ((m = n - (pi.exponent - d.exponent).abs) > 0)
      m = BigDecimal.double_fig if m < BigDecimal.double_fig
      t   = t.div(m57121,n)
      d   = t.div(k,m)
      pi  = pi + d
      k   = k+two
    end
    pi
  end
atan(x, prec)

[Source]

# File bigdecimal/lib/bigdecimal/math.rb, line 79
  def atan(x, prec)
    raise ArgumentError, "Zero or negative precision for atan" if prec <= 0
    return BigDecimal("NaN") if x.infinite? || x.nan?
    raise ArgumentError, "x.abs must be less than 1.0" if x.abs>=1
    n    = prec + BigDecimal.double_fig
    y = x
    d = y
    t = x
    r = BigDecimal("3")
    x2 = x.mult(x,n)
    while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0)
      m = BigDecimal.double_fig if m < BigDecimal.double_fig
      t = -t.mult(x2,n)
      d = t.div(r,m)
      y += d
      r += 2
    end
    y
  end
cos(x, prec)

[Source]

# File bigdecimal/lib/bigdecimal/math.rb, line 54
  def cos(x, prec)
    raise ArgumentError, "Zero or negative precision for cos" if prec <= 0
    return BigDecimal("NaN") if x.infinite? || x.nan?
    n    = prec + BigDecimal.double_fig
    one  = BigDecimal("1")
    two  = BigDecimal("2")
    x1 = one
    x2 = x.mult(x,n)
    sign = 1
    y = one
    d = y
    i = BigDecimal("0")
    z = one
    while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0)
      m = BigDecimal.double_fig if m < BigDecimal.double_fig
      sign = -sign
      x1  = x2.mult(x1,n)
      i  += two
      z  *= (i-one) * i
      d   = sign * x1.div(z,m)
      y  += d
    end
    y
  end
exp(x, prec)

[Source]

# File bigdecimal/lib/bigdecimal/math.rb, line 99
  def exp(x, prec)
    raise ArgumentError, "Zero or negative precision for exp" if prec <= 0
    return BigDecimal("NaN") if x.infinite? || x.nan?
    n    = prec + BigDecimal.double_fig
    one  = BigDecimal("1")
    x1 = one
    y  = one
    d  = y
    z  = one
    i  = 0
    while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0)
      m = BigDecimal.double_fig if m < BigDecimal.double_fig
      x1  = x1.mult(x,n)
      i += 1
      z *= i
      d  = x1.div(z,m)
      y += d
    end
    y
  end
log(x, prec)

[Source]

# File bigdecimal/lib/bigdecimal/math.rb, line 120
  def log(x, prec)
    raise ArgumentError, "Zero or negative argument for log" if x <= 0 || prec <= 0
    return x if x.infinite? || x.nan?
    one = BigDecimal("1")
    two = BigDecimal("2")
    n  = prec + BigDecimal.double_fig
    x  = (x - one).div(x + one,n)
    x2 = x.mult(x,n)
    y  = x
    d  = y
    i = one
    while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0)
      m = BigDecimal.double_fig if m < BigDecimal.double_fig
      x  = x2.mult(x,n)
      i += two
      d  = x.div(i,m)
      y += d
    end
    y*two
  end
sin(x, prec)

[Source]

# File bigdecimal/lib/bigdecimal/math.rb, line 29
  def sin(x, prec)
    raise ArgumentError, "Zero or negative precision for sin" if prec <= 0
    return BigDecimal("NaN") if x.infinite? || x.nan?
    n    = prec + BigDecimal.double_fig
    one  = BigDecimal("1")
    two  = BigDecimal("2")
    x1   = x
    x2   = x.mult(x,n)
    sign = 1
    y    = x
    d    = y
    i    = one
    z    = one
    while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0)
      m = BigDecimal.double_fig if m < BigDecimal.double_fig
      sign = -sign
      x1  = x2.mult(x1,n)
      i  += two
      z  *= (i-one) * i
      d   = sign * x1.div(z,m)
      y  += d
    end
    y
  end
sqrt(x,prec)

[Source]

# File bigdecimal/lib/bigdecimal/math.rb, line 25
  def sqrt(x,prec)
    x.sqrt(prec)
  end


Class: Float

Class | Float
In: | bigdecimal/lib/bigdecimal/util.rb
Parent: | Numeric

BigDecimal utility library.

Contents:

  String#
    to_d      ... to BigDecimal

  Float#
    to_d      ... to BigDecimal

  BigDecimal#
    to_r      ... to Rational

  Rational#
    to_d      ... to BigDecimal

Methods

to_d

Public Instance methods

to_d()

[Source]

# File bigdecimal/lib/bigdecimal/util.rb, line 21
  def to_d
    BigDecimal(self.to_s)
  end


Module: Jacobian

Module | Jacobian
In: | bigdecimal/lib/bigdecimal/jacobian.rb

jacobian.rb

Computes Jacobian matrix of f at x

Methods

dfdxi isEqual jacobian

Public Instance methods

dfdxi(f,fx,x,i)

[Source]

# File bigdecimal/lib/bigdecimal/jacobian.rb, line 21
  def dfdxi(f,fx,x,i)
    nRetry = 0
    n = x.size
    xSave = x[i]
    ok = 0
    ratio = f.ten*f.ten*f.ten
    dx = x[i].abs/ratio
    dx = fx[i].abs/ratio if isEqual(dx,f.zero,f.zero,f.eps)
    dx = f.one/f.ten     if isEqual(dx,f.zero,f.zero,f.eps)
    until ok>0 do
      s = f.zero
      deriv = []
      if(nRetry>100) then
         raize "Singular Jacobian matrix. No change at x[" + i.to_s + "]"
      end
      dx = dx*f.two
      x[i] += dx
      fxNew = f.values(x)
      for j in 0...n do
        if !isEqual(fxNew[j],fx[j],f.zero,f.eps) then
           ok += 1
           deriv <<= (fxNew[j]-fx[j])/dx
        else
           deriv <<= f.zero
        end
      end
      x[i] = xSave
    end
    deriv
  end
isEqual(a,b,zero=0.0,e=1.0e-8)

[Source]

# File bigdecimal/lib/bigdecimal/jacobian.rb, line 7
  def isEqual(a,b,zero=0.0,e=1.0e-8)
    aa = a.abs
    bb = b.abs
    if aa == zero &&  bb == zero then
          true
    else
          if ((a-b)/(aa+bb)).abs < e then
             true
          else
             false
          end
    end
  end
jacobian(f,fx,x)

[Source]

# File bigdecimal/lib/bigdecimal/jacobian.rb, line 52
  def jacobian(f,fx,x)
    n = x.size
    dfdx = Array::new(n*n)
    for i in 0...n do
      df = dfdxi(f,fx,x,i)
      for j in 0...n do
         dfdx[j*n+i] = df[j]
      end
    end
    dfdx
  end


Module: Kernel

Module | Kernel
In: |

Methods

BigDecimal

Public Instance methods

BigDecimal(...)


Module: LUSolve

Module | LUSolve
In: | bigdecimal/lib/bigdecimal/ludcmp.rb

ludcmp.rb

Methods

ludecomp lusolve

Public Instance methods

ludecomp(a,n,zero=0,one=1)

[Source]

# File bigdecimal/lib/bigdecimal/ludcmp.rb, line 5
  def ludecomp(a,n,zero=0,one=1)
    prec = BigDecimal.limit(nil)
    ps     = []
    scales = []
    for i in 0...n do  # pick up largest(abs. val.) element in each row.
      ps <<= i
      nrmrow  = zero
      ixn = i*n
      for j in 0...n do
         biggst = a[ixn+j].abs
         nrmrow = biggst if biggst>nrmrow
      end
      if nrmrow>zero then
         scales <<= one.div(nrmrow,prec)
      else
         raise "Singular matrix"
      end
    end
    n1          = n - 1
    for k in 0...n1 do # Gaussian elimination with partial pivoting.
      biggst  = zero;
      for i in k...n do
         size = a[ps[i]*n+k].abs*scales[ps[i]]
         if size>biggst then
            biggst = size
            pividx  = i
         end
      end
      raise "Singular matrix" if biggst<=zero
      if pividx!=k then
        j = ps[k]
        ps[k] = ps[pividx]
        ps[pividx] = j
      end
      pivot   = a[ps[k]*n+k]
      for i in (k+1)...n do
        psin = ps[i]*n
        a[psin+k] = mult = a[psin+k].div(pivot,prec)
        if mult!=zero then
           pskn = ps[k]*n
           for j in (k+1)...n do
             a[psin+j] -= mult.mult(a[pskn+j],prec)
           end
        end
      end
    end
    raise "Singular matrix" if a[ps[n1]*n+n1] == zero
    ps
  end

  def lusolve(a,b,ps,zero=0.0)
    prec = BigDecimal.limit(nil)
    n = ps.size
    x = []
    for i in 0...n do
      dot = zero
      psin = ps[i]*n
      for j in 0...i do
        dot = a[psin+j].mult(x[j],prec) + dot
      end
      x <<= b[ps[i]] - dot
    end
    (n-1).downto(0) do |i|
       dot = zero
       psin = ps[i]*n
       for j in (i+1)...n do
         dot = a[psin+j].mult(x[j],prec) + dot
       end
       x[i]  = (x[i]-dot).div(a[psin+i],prec)
    end
    x
  end
end
lusolve(a,b,ps,zero=0.0)

[Source]

# File bigdecimal/lib/bigdecimal/ludcmp.rb, line 55
  def lusolve(a,b,ps,zero=0.0)
    prec = BigDecimal.limit(nil)
    n = ps.size
    x = []
    for i in 0...n do
      dot = zero
      psin = ps[i]*n
      for j in 0...i do
        dot = a[psin+j].mult(x[j],prec) + dot
      end
      x <<= b[ps[i]] - dot
    end
    (n-1).downto(0) do |i|
       dot = zero
       psin = ps[i]*n
       for j in (i+1)...n do
         dot = a[psin+j].mult(x[j],prec) + dot
       end
       x[i]  = (x[i]-dot).div(a[psin+i],prec)
    end
    x
  end
end


Module: Newton

Module | Newton
In: | bigdecimal/lib/bigdecimal/newton.rb

Methods

nlsolve norm

Included Modules

LUSolve Jacobian

Public Instance methods

nlsolve(f,x)

[Source]

# File bigdecimal/lib/bigdecimal/newton.rb, line 39
  def nlsolve(f,x)
    nRetry = 0
    n = x.size

    f0 = f.values(x)
    zero = f.zero
    one  = f.one
    two  = f.two
    p5 = one/two
    d  = norm(f0,zero)
    minfact = f.ten*f.ten*f.ten
    minfact = one/minfact
    e = f.eps
    while d >= e do
      nRetry += 1
      # Not yet converged. => Compute Jacobian matrix
      dfdx = jacobian(f,f0,x)
      # Solve dfdx*dx = -f0 to estimate dx
      dx = lusolve(dfdx,f0,ludecomp(dfdx,n,zero,one),zero)
      fact = two
      xs = x.dup
      begin
        fact *= p5
        if fact < minfact then
          raize "Failed to reduce function values."
        end
        for i in 0...n do
          x[i] = xs[i] - dx[i]*fact
        end
        f0 = f.values(x)
        dn = norm(f0,zero)
      end while(dn>=d)
      d = dn
    end
    nRetry
  end
norm(fv,zero=0.0)

[Source]

# File bigdecimal/lib/bigdecimal/newton.rb, line 30
  def norm(fv,zero=0.0)
    s = zero
    n = fv.size
    for i in 0...n do
      s += fv[i]*fv[i]
    end
    s
  end


Class: Rational

Class | Rational
In: | bigdecimal/lib/bigdecimal/util.rb
Parent: | Numeric

Methods

to_d

Public Instance methods

to_d(nFig=0)

Convert Rational to BigDecimal

[Source]

# File bigdecimal/lib/bigdecimal/util.rb, line 61
  def to_d(nFig=0)
     num = self.numerator.to_s
     if nFig<=0
        nFig = BigDecimal.double_fig*2+1
     end
     BigDecimal.new(num).div(self.denominator,nFig)
  end


Class: String

Class | String
In: | bigdecimal/lib/bigdecimal/util.rb
Parent: | Object

Methods

to_d

Public Instance methods

to_d()

[Source]

# File bigdecimal/lib/bigdecimal/util.rb, line 27
  def to_d
    BigDecimal(self)
  end


File: bigdecimal.c

bigdecimal.c

Path: | bigdecimal/bigdecimal.c
Last Update: | Sat Oct 15 23:43:50 AUS Eastern Standard Time 2005


File: jacobian.rb

jacobian.rb

Path: | bigdecimal/lib/bigdecimal/jacobian.rb
Last Update: | Sat Jul 19 01:26:37 AUS Eastern Standard Time 2003

jacobian.rb

Computes Jacobian matrix of f at x


File: ludcmp.rb

ludcmp.rb

Path: | bigdecimal/lib/bigdecimal/ludcmp.rb
Last Update: | Fri Aug 29 23:33:37 AUS Eastern Standard Time 2003

ludcmp.rb


File: math.rb

math.rb

Path: | bigdecimal/lib/bigdecimal/math.rb
Last Update: | Wed Aug 20 00:16:09 AUS Eastern Standard Time 2003

Contents:

  sqrt(x, prec)
  sin (x, prec)
  cos (x, prec)
  atan(x, prec)  Note: |x|<1, x=0.9999 may not converge.
  exp (x, prec)
  log (x, prec)
  PI  (prec)
  E   (prec) == exp(1.0,prec)

where:

  x    ... BigDecimal number to be computed.
           |x| must be small enough to get convergence.
  prec ... Number of digits to be obtained.

Usage:

  require "bigdecimal"
  require "bigdecimal/math.rb"
  include BigMath
  a = BigDecimal((PI(100)/2).to_s)
  puts sin(a,100) # => 0.10000000000000000000......E1


File: newton.rb

newton.rb

Path: | bigdecimal/lib/bigdecimal/newton.rb
Last Update: | Sat Oct 15 23:43:50 AUS Eastern Standard Time 2005

newton.rb

Solves nonlinear algebraic equation system f = 0 by Newton’s method.

 (This program is not dependent on BigDecimal)

To call:

   n = nlsolve(f,x)
 where n is the number of iterations required.
       x is the solution vector.
       f is the object to be solved which must have following methods.

  f ... Object to compute Jacobian matrix of the equation systems.
      [Methods required for f]
        f.values(x) returns values of all functions at x.
        f.zero      returns 0.0
        f.one       returns 1.0
        f.two       returns 1.0
        f.ten       returns 10.0
        f.eps       convergence criterion
  x ... initial values

Required files

bigdecimal/ludcmp bigdecimal/jacobian


File: util.rb

util.rb

Path: | bigdecimal/lib/bigdecimal/util.rb
Last Update: | Sat Aug 16 23:36:40 AUS Eastern Standard Time 2003

BigDecimal utility library.

Contents:

  String#
    to_d      ... to BigDecimal

  Float#
    to_d      ... to BigDecimal

  BigDecimal#
    to_r      ... to Rational

  Rational#
    to_d      ... to BigDecimal


Class: CGI

Class | CGI
In: | cgi.rb cgi/session.rb cgi/session/pstore.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

escape escapeElement escapeHTML header new out parse pretty print rfc1123_date unescape unescapeElement unescapeHTML

Classes and Modules

Module CGI::HtmlExtension
Module CGI::QueryExtension
Class CGI::Cookie
Class CGI::Session

Public Class methods

escape(string)

URL-encode a string.

  url_encoded_string = CGI::escape("'Stop!' said Fred")
     # => "%27Stop%21%27+said+Fred"

[Source]

# File 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
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"

[Source]

# File 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
escapeHTML(string)

Escape special characters in HTML, namely &\"<>

  CGI::escapeHTML('Usage: foo "bar" <baz>')
     # => "Usage: foo &quot;bar&quot; &lt;baz&gt;"

[Source]

# File cgi.rb, line 361
  def CGI::escapeHTML(string)
    string.gsub(/&/n, '&amp;').gsub(/\"/n, '&quot;').gsub(/>/n, '&gt;').gsub(/</n, '&lt;')
  end
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.

[Source]

# File cgi.rb, line 2283
  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
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", ...], ... }

[Source]

# File cgi.rb, line 894
  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(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>

[Source]

# File cgi.rb, line 1210
  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
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

[Source]

# File 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
unescape(string)

URL-decode a string.

  string = CGI::unescape("%27Stop%21%27+said+Fred")
     # => "'Stop!' said Fred"

[Source]

# File cgi.rb, line 351
  def CGI::unescape(string)
    string.tr('+', ' ').gsub(/((?:%[0-9a-fA-F]{2})+)/n) do
      [$1.delete('%')].pack('H*')
    end
  end
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>"

[Source]

# File 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
unescapeHTML(string)

Unescape a string that has been HTML-escaped

  CGI::unescapeHTML("Usage: foo &quot;bar&quot; &lt;baz&gt;")
     # => "Usage: foo \"bar\" <baz>"

[Source]

# File cgi.rb, line 369
  def CGI::unescapeHTML(string)
    string.gsub(/&(.*?);/n) do
      match = $1.dup
      case match
      when /\Aamp\z/ni           then '&'
      when /\Aquot\z/ni          then '"'
      when /\Agt\z/ni            then '>'
      when /\Alt\z/ni            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

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.

[Source]

# File 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/n.match(env_table['SERVER_SOFTWARE'])
      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(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".

[Source]

# File cgi.rb, line 702
  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('-j', content)
        options["language"] = "ja" unless options.has_key?("language")
      when /euc-jp/ni
        content = NKF::nkf('-e', content)
        options["language"] = "ja" unless options.has_key?("language")
      when /shift_jis/ni
        content = NKF::nkf('-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(*options)

Print an argument or list of arguments to the default output stream

  cgi = CGI.new
  cgi.print    # default:  cgi.print == $DEFAULT_OUTPUT.print

[Source]

# File cgi.rb, line 734
  def print(*options)
    stdoutput.print(*options)
  end


Class: CGI::Cookie

Class | CGI::Cookie
In: | 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.

[Source]

# File cgi.rb, line 793
    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
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, ... }

[Source]

# File cgi.rb, line 869
  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

Public Instance methods

secure=(val)

Set whether the Cookie is a secure cookie or not.

val must be a boolean.

[Source]

# File cgi.rb, line 825
    def secure=(val)
      @secure = val if val == true or val == false
      @secure
    end
to_s()

Convert the Cookie to its string representation.

[Source]

# File cgi.rb, line 831
    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


Module: CGI::HtmlExtension

Module | CGI::HtmlExtension
In: | 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>"

[Source]

# File cgi.rb, line 1311
    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(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\">"

[Source]

# File cgi.rb, line 1333
    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(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>

[Source]

# File cgi.rb, line 1356
    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(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>

[Source]

# File cgi.rb, line 1380
    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(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)

[Source]

# File cgi.rb, line 1410
    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(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"])

[Source]

# File cgi.rb, line 1464
    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(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">

[Source]

# File cgi.rb, line 1506
    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(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>

[Source]

# File cgi.rb, line 1540
    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(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">

[Source]

# File cgi.rb, line 1581
    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(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" }

[Source]

# File cgi.rb, line 1633
    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(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">

[Source]

# File cgi.rb, line 1682
    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(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">

[Source]

# File cgi.rb, line 1708
    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(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>

[Source]

# File cgi.rb, line 1734
    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(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">

[Source]

# File cgi.rb, line 1776
    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(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>

[Source]

# File cgi.rb, line 1831
    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(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">

[Source]

# File cgi.rb, line 1880
    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(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"])

[Source]

# File cgi.rb, line 1919
    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(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">

[Source]

# File cgi.rb, line 1954
    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
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">

[Source]

# File cgi.rb, line 1984
    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(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">

[Source]

# File cgi.rb, line 2016
    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(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)

[Source]

# File cgi.rb, line 2042
    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


Module: CGI::QueryExtension

Module | CGI::QueryExtension
In: | 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.

[Source]

# File cgi.rb, line 1159
    def [](key)
      params = @params[key]
      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
has_key?(*args)

Returns true if a given parameter key exists in the query.

[Source]

# File cgi.rb, line 1184
    def has_key?(*args)
      @params.has_key?(*args)
    end
include?(*args)

Alias for has_key?

key?(*args)

Alias for has_key?

keys(*args)

Return all parameter keys as an array.

[Source]

# File cgi.rb, line 1179
    def keys(*args)
      @params.keys(*args)
    end
multipart?()

[Source]

# File cgi.rb, line 1128
    def multipart?
      @multipart
    end
params=(hash)

Set all the parameters.

[Source]

# File cgi.rb, line 962
    def params=(hash)
      @params.clear
      @params.update(hash)
    end
raw_cookie()

Get the raw cookies as a string.

[Source]

# File cgi.rb, line 945
    def raw_cookie
      env_table["HTTP_COOKIE"]
    end
raw_cookie2()

Get the raw RFC2965 cookies as a string.

[Source]

# File cgi.rb, line 950
    def raw_cookie2
      env_table["HTTP_COOKIE2"]
    end


Class: CGI::Session

Class | CGI::Session
In: | cgi/session.rb cgi/session/pstore.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
Class CGI::Session::PStore

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

[Source]

# File 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

Public Instance methods

[](key)

Retrieve the session data for key key.

[Source]

# File cgi/session.rb, line 303
    def [](key)
      unless @data
        @data = @dbman.restore
      end
      @data[key]
    end
[]=(key, val)

[Source]

# File cgi/session/pstore.rb, line 17
    def []=(key, val)
      unless @write_lock
        @write_lock = true
      end
      unless @data
        @data = @dbman.restore
      end
      #@data[key] = String(val)
      @data[key] = val
    end
[]=(key, val)

Set the session date for key key.

[Source]

# File cgi/session.rb, line 311
    def []=(key, val)
      unless @write_lock
        @write_lock = true
      end
      unless @data
        @data = @dbman.restore
      end
      @data[key] = val
    end
close()

Store session data on the server and close the session storage. For some session storage types, this is a no-op.

[Source]

# File cgi/session.rb, line 329
    def close
      @dbman.close
      @dbprot.clear
    end
delete()

Delete the session from storage. Also closes the storage.

Note that the session’s data is not automatically deleted upon the session expiring.

[Source]

# File cgi/session.rb, line 338
    def delete
      @dbman.delete
      @dbprot.clear
    end
update()

Store session data on the server. For some session storage types, this is a no-op.

[Source]

# File cgi/session.rb, line 323
    def update
      @dbman.update
    end


Class: CGI::Session::FileStore

Class | CGI::Session::FileStore
In: | 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.

[Source]

# File cgi/session.rb, line 375
      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
        unless File::exist? @path
          unless session.new_session
            raise CGI::Session::NoSession, "uninitialized session"
          end
          @hash = {}
        end
      end

Public Instance methods

close()

Update and close the session’s FileStore file.

[Source]

# File cgi/session.rb, line 427
      def close
        update
      end
delete()

Close and delete the session’s FileStore file.

[Source]

# File cgi/session.rb, line 432
      def delete
        File::unlink @path
      rescue Errno::ENOENT
      end
restore()

Restore session state from the session’s FileStore file.

Returns the session state as a hash.

[Source]

# File cgi/session.rb, line 394
      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()

Save session state to the session’s FileStore file.

[Source]

# File cgi/session.rb, line 413
      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


Class: CGI::Session::MemoryStore

Class | CGI::Session::MemoryStore
In: | 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.

[Source]

# File cgi/session.rb, line 451
      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

Public Instance methods

close()

Close session storage.

A no-op.

[Source]

# File cgi/session.rb, line 478
      def close
        # don't need to close
      end
delete()

Delete the session state.

[Source]

# File cgi/session.rb, line 483
      def delete
        GLOBAL_HASH_TABLE.delete(@session_id)
      end
restore()

Restore session state.

Returns session data as a hash.

[Source]

# File cgi/session.rb, line 464
      def restore
        GLOBAL_HASH_TABLE[@session_id]
      end
update()

Update session state.

A no-op.

[Source]

# File cgi/session.rb, line 471
      def update
        # don't need to update; hash is shared
      end


Class: CGI::Session::PStore

Class | CGI::Session::PStore
In: | cgi/session/pstore.rb
Parent: | Object

PStore-based session storage class.

This builds upon the top-level PStore class provided by the library file pstore.rb. Session data is marshalled and stored in a file. File locking and transaction services are provided.

Methods

close delete new restore update

Public Class methods

new(session, option={})

Create a new CGI::Session::PStore 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 PStore 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 PStore file. Defaults to the empty string.

This session’s PStore file will be created if it does not exist, or opened if it does.

[Source]

# File cgi/session/pstore.rb, line 56
      def initialize session, option={}
        dir = option['tmpdir'] || Dir::tmpdir
        prefix = option['prefix'] || ''
        id = session.session_id
        require 'digest/md5'
        md5 = Digest::MD5.hexdigest(id)[0,16]
        path = dir+"/"+prefix+md5
        path.untaint
        unless File::exist?(path)
          unless session.new_session
            raise CGI::Session::NoSession, "uninitialized session"
          end
          @hash = {}
        end
        @p = ::PStore.new(path)
        @p.transaction do |p|
          File.chmod(0600, p.path)
        end
      end

Public Instance methods

close()

Update and close the session’s PStore file.

[Source]

# File cgi/session/pstore.rb, line 96
      def close
        update
      end
delete()

Close and delete the session’s PStore file.

[Source]

# File cgi/session/pstore.rb, line 101
      def delete
        path = @p.path
        File::unlink path
      end
restore()

Restore session state from the session’s PStore file.

Returns the session state as a hash.

[Source]

# File cgi/session/pstore.rb, line 79
      def restore
        unless @hash
          @p.transaction do
           @hash = @p['hash'] || {}
          end
        end
        @hash
      end
update()

Save session state to the session’s PStore file.

[Source]

# File cgi/session/pstore.rb, line 89
      def update
        @p.transaction do
            @p['hash'] = @hash
        end
      end


File: cgi.rb

cgi.rb

Path: | cgi.rb
Last Update: | Sat Oct 15 23:44:27 AUS Eastern Standard Time 2005

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: session.rb

session.rb

Path: | cgi/session.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

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


File: pstore.rb

pstore.rb

Path: | cgi/session/pstore.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

cgi/session/pstore.rb - persistent storage of marshalled session data

Documentation: William Webber (william@williamwebber.com)

Overview

This file provides the CGI::Session::PStore class, which builds persistent of session data on top of the pstore library. See cgi/session.rb for more details on session storage managers.

Required files

cgi/session pstore digest/md5


File: complex.rb

complex.rb

Path: | complex.rb
Last Update: | Thu Jul 31 18:42:44 AUS Eastern Standard Time 2003
  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.

[Source]

# File 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


Class: Complex

Class | Complex
In: | complex.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.

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)

[Source]

# File 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
new!(a, b=0)

Creates a Complex number a+b i.

[Source]

# File complex.rb, line 122
  def Complex.new!(a, b=0)
    new(a,b)
  end
polar(r, theta)

Creates a Complex number in terms of r (radius) and theta (angle).

[Source]

# File complex.rb, line 115
  def Complex.polar(r, theta)
    Complex(r*Math.cos(theta), r*Math.sin(theta))
  end

Public Instance methods

%(other)

Remainder after division by a real or complex number.

[Source]

# File 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
*(other)

Multiplication with real or complex number.

[Source]

# File 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
**(other)

Raise this complex number to the given (real or complex) power.

[Source]

# File 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
+(other)

Addition with real or complex number.

[Source]

# File 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
-(other)

Subtraction with real or complex number.

[Source]

# File 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
/(other)

Division by real or complex number.

[Source]

# File 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
<=>(other)

Compares the absolute values of the two numbers.

[Source]

# File complex.rb, line 312
  def <=> (other)
    self.abs <=> other.abs
  end
==(other)

Test for numerical equality (a == a + 0i).

[Source]

# File 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
abs()

Absolute value (aka modulus): distance from the zero point on the complex plane.

[Source]

# File complex.rb, line 275
  def abs
    Math.hypot(@real, @image)
  end
abs2()

Square of the absolute value.

[Source]

# File complex.rb, line 282
  def abs2
    @real*@real + @image*@image
  end
angle()

Alias for arg

arg()

Argument (angle from (1,0) on the complex plane).

[Source]

# File complex.rb, line 289
  def arg
    Math.atan2!(@image, @real)
  end
coerce(other)

Attempts to coerce other to a Complex number.

[Source]

# File complex.rb, line 332
  def coerce(other)
    if Complex.generic?(other)
      return Complex.new!(other), self
    else
      super
    end
  end
conj()

Alias for conjugate

conjugate()

Complex conjugate (z + z.conjugate = 2 * z.real).

[Source]

# File complex.rb, line 304
  def conjugate
    Complex(@real, -@image)
  end
denominator()

FIXME

[Source]

# File complex.rb, line 343
  def denominator
    @real.denominator.lcm(@image.denominator)
  end
hash()

Returns a hash code for the complex number.

[Source]

# File complex.rb, line 386
  def hash
    @real.hash ^ @image.hash
  end
inspect()

Returns "Complex(real, image)".

[Source]

# File complex.rb, line 393
  def inspect
    sprintf("Complex(%s, %s)", @real.inspect, @image.inspect)
  end
numerator()

FIXME

[Source]

# File complex.rb, line 350
  def numerator
    cd = denominator
    Complex(@real.numerator*(cd/@real.denominator),
            @image.numerator*(cd/@image.denominator))
  end
polar()

Returns the absolute value and the argument.

[Source]

# File complex.rb, line 297
  def polar
    return abs, arg
  end
to_s()

Standard string representation of the complex number.

[Source]

# File 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


Module: Math

Module | Math
In: | complex.rb

Methods

acos acosh asin asinh atan atan2 atanh cos cosh exp log log10 sin sinh sqrt tan tanh

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 Instance methods

acos(z)

[Source]

# File 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
acosh(z)

[Source]

# File 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
asin(z)

[Source]

# File 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
asinh(z)

[Source]

# File complex.rb, line 574
  def asinh(z)
    if Complex.generic?(z)
      asinh!(z)
    else
      log( z + sqrt(1.0+z*z) )
    end
  end
atan(z)

[Source]

# File 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(y,x)

[Source]

# File 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
atanh(z)

[Source]

# File 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
cos(z)

Redefined to handle a Complex argument.

[Source]

# File 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
cosh(z)

[Source]

# File 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
exp(z)

Redefined to handle a Complex argument.

[Source]

# File 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
log(z)

Redefined to handle a Complex argument.

[Source]

# File 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(z)

Redefined to handle a Complex argument.

[Source]

# File complex.rb, line 526
  def log10(z)
    if Complex.generic?(z)
      log10!(z)
    else
      log(z)/log!(10)
    end
  end
sin(z)

Redefined to handle a Complex argument.

[Source]

# File 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
sinh(z)

[Source]

# File 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
sqrt(z)

Redefined to handle a Complex argument.

[Source]

# File 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
tan(z)

Redefined to handle a Complex argument.

[Source]

# File complex.rb, line 483
  def tan(z)
    if Complex.generic?(z)
      tan!(z)
    else
      sin(z)/cos(z)
    end
  end
tanh(z)

[Source]

# File complex.rb, line 507
  def tanh(z)
    if Complex.generic?(z)
      tanh!(z)
    else
      sinh(z)/cosh(z)
    end
  end


Class: Numeric

Class | Numeric
In: | 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

angle arg conj conjugate im imag image polar real

Public Instance methods

angle()

Alias for arg

arg()

See Complex#arg.

[Source]

# File complex.rb, line 60
  def arg
    if self >= 0
      return 0
    else
      return Math::PI
    end
  end
conj()

Alias for conjugate

conjugate()

See Complex#conjugate (short answer: returns self).

[Source]

# File complex.rb, line 79
  def conjugate
    self
  end
im()

Returns a Complex number (0,self).

[Source]

# File complex.rb, line 38
  def im
    Complex(0, self)
  end
imag()

Alias for image

image()

The imaginary part of a complex number, i.e. 0.

[Source]

# File complex.rb, line 52
  def image
    0
  end
polar()

See Complex#polar.

[Source]

# File complex.rb, line 72
  def polar
    return abs, arg
  end
real()

The real part of a complex number, i.e. self.

[Source]

# File complex.rb, line 45
  def real
    self
  end


Class: CSV

Class | CSV
In: | 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)

[Source]

# File csv.rb, line 93
  def CSV.foreach(path, rs = nil, &block)
    open_reader(path, 'r', ',', rs, &block)
  end
generate(path, fs = nil, rs = nil, &block)

[Source]

# File csv.rb, line 110
  def CSV.generate(path, fs = nil, rs = nil, &block)
    open_writer(path, 'w', fs, rs, &block)
  end
generate_line(row, fs = nil, rs = nil)

Create a line from cells. each cell is stringified by to_s.

[Source]

# File 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
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.

[Source]

# File 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
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.

[Source]

# File 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
parse(str_or_readable, fs = nil, rs = nil) {|row| ...}

Parse lines from given string or stream. Return rows as an Array of Arrays.

[Source]

# File 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(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.

[Source]

# File 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
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'.

[Source]

# File 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
read(path, length = nil, offset = nil)

[Source]

# File csv.rb, line 97
  def CSV.read(path, length = nil, offset = nil)
    CSV.parse(IO.read(path, length, offset))
  end
readlines(path, rs = nil)

[Source]

# File 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


Class: CSV::BasicWriter

Class | CSV::BasicWriter
In: | csv.rb
Parent: | Writer

Methods

close_on_terminate new

Public Class methods

new(str_or_writable, fs = ',', rs = nil)

[Source]

# File 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

Public Instance methods

close_on_terminate()

Tell this writer to close the IO when terminated (Triggered by invoking CSV::BasicWriter#close).

[Source]

# File csv.rb, line 723
    def close_on_terminate
      @close_on_terminate = true
    end


Class: CSV::Cell

Class | CSV::Cell
In: | csv.rb
Parent: | String

deprecated

Methods

data new

Public Class methods

new(data = "", is_null = false)

[Source]

# File csv.rb, line 16
    def initialize(data = "", is_null = false)
      super(is_null ? "" : data)
    end

Public Instance methods

data()

[Source]

# File csv.rb, line 20
    def data
      to_s
    end


Class: CSV::IOBuf

Class | CSV::IOBuf
In: | 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)

[Source]

# File csv.rb, line 973
    def initialize(s)
      @s = s
      super()
    end

Public Instance methods

close()

[Source]

# File csv.rb, line 978
    def close
      terminate
    end


Class: CSV::IOReader

Class | CSV::IOReader
In: | csv.rb
Parent: | Reader

Methods

close_on_terminate new

Public Class methods

new(io, fs = ',', rs = nil)

[Source]

# File 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

Public Instance methods

close_on_terminate()

Tell this reader to close the IO when terminated (Triggered by invoking CSV::IOReader#close).

[Source]

# File csv.rb, line 630
    def close_on_terminate
      @close_on_terminate = true
    end


Class: CSV::IllegalFormatError

Class | CSV::IllegalFormatError
In: | csv.rb
Parent: | RuntimeError


Class: CSV::Reader

Class | CSV::Reader
In: | 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.

[Source]

# File 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
new(dev)

[Source]

# File csv.rb, line 577
    def initialize(dev)
      raise RuntimeError.new('Do not instanciate this class directly.')
    end
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.

[Source]

# File 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

Public Instance methods

close()

[Source]

# File csv.rb, line 571
    def close
      terminate
    end
each() {|row| ...}

[Source]

# File 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()

[Source]

# File csv.rb, line 565
    def shift
      row = []
      parsed_cells = get_row(row)
      row
    end


Class: CSV::Row

Class | CSV::Row
In: | csv.rb
Parent: | Array

deprecated


Class: CSV::StreamBuf

Class | CSV::StreamBuf
In: | 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

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.

[Source]

# File 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

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.

[Source]

# File 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(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.

[Source]

# File 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
get(idx, n = nil)

Alias for #[]

is_eos?()

[Source]

# File csv.rb, line 882
    def is_eos?
      return idx_is_eos?(0)
    end


Class: CSV::StringReader

Class | CSV::StringReader
In: | csv.rb
Parent: | Reader

Methods

new

Public Class methods

new(string, fs = ',', rs = nil)

[Source]

# File 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


Class: CSV::Writer

Class | CSV::Writer
In: | 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)’.

[Source]

# File csv.rb, line 686
    def Writer.create(str_or_writable, fs = ',', rs = nil)
      BasicWriter.new(str_or_writable, fs, rs)
    end
generate(str_or_writable, fs = ',', rs = nil) {|writer| ...}

Given block is called with the writer instance. str_or_writable must handle ’<<(string)’.

[Source]

# File 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
new(dev)

[Source]

# File csv.rb, line 703
    def initialize(dev)
      raise RuntimeError.new('Do not instanciate this class directly.')
    end

Public Instance methods

<<(row)

dump CSV stream to the device. argument must be an Array of String.

[Source]

# File csv.rb, line 691
    def <<(row)
      CSV.generate_row(row, row.size, @dev, @fs, @rs)
      self
    end
add_row(row)

Alias for #<<

close()

[Source]

# File csv.rb, line 697
    def close
      terminate
    end


File: csv.rb

csv.rb

Path: | csv.rb
Last Update: | Sat Oct 15 23:44:27 AUS Eastern Standard Time 2005

CSV — module for generating/parsing CSV data. Copyright (C) 2000-2004 NAKAMURA, Hiroshi <nakahiro@sarion.co.jp>.


Module: Curses

Module | Curses
In: | curses/curses.c

————————- Initialization ————————-

Methods

addch addstr attroff attron attrset beep bkgd bkgdset can_change_color? cbreak clear close_screen closed? clrtoeol color_content color_pair cols crmode curs_set def_prog_mode delch deleteln doupdate echo flash getch getmouse getstr has_colors? inch init_color init_pair init_screen insch insertln keyname lines mouseinterval mousemask nl nocbreak nocrmode noecho nonl noraw pair_content pair_number raw refresh reset_prog_mode resize resizeterm scrl setpos setscrreg standend standout start_color stdscr timeout= ungetch ungetmouse

Classes and Modules

Module Curses::Key
Class Curses::MouseEvent
Class Curses::Window

Public Instance methods

addch(p1)

def addch(ch)

[Source]

/* def addch(ch) */
static VALUE
curses_addch(obj, ch)
    VALUE obj;
    VALUE ch;
{
    curses_stdscr();
    addch(NUM2CH(ch));
    return Qnil;
}
addstr(p1)

def addstr(str)

[Source]

/* def addstr(str) */
static VALUE
curses_addstr(obj, str)
    VALUE obj;
    VALUE str;
{
    curses_stdscr();
    if (!NIL_P(str)) {
    addstr(STR2CSTR(str));
    }
    return Qnil;
}
attroff(p1)
attron(p1)
attrset(p1)
beep()

def beep

[Source]

/* def beep */
static VALUE
curses_beep(obj)
    VALUE obj;
{
#ifdef HAVE_BEEP
    curses_stdscr();
    beep();
#endif
    return Qnil;
}
bkgd(p1)
bkgdset(p1)
can_change_color?()
cbreak()

def cbreak

[Source]

/* def cbreak */
static VALUE
curses_cbreak(obj)
    VALUE obj;
{
    curses_stdscr();
    cbreak();
    return Qnil;
}
clear()

def clear

[Source]

/* def clear */
static VALUE
curses_clear(obj)
    VALUE obj;
{
    curses_stdscr();
    wclear(stdscr);
    return Qnil;
}
close_screen()

def close_screen

[Source]

/* def close_screen */
static VALUE
curses_close_screen()
{
#ifdef HAVE_ISENDWIN
    if (!isendwin())
#endif
    endwin();
    rb_stdscr = 0;
    return Qnil;
}
closed?()

def closed?

[Source]

/* def closed? */
static VALUE
curses_closed()
{
#ifdef HAVE_ISENDWIN
    if (isendwin()) {
    return Qtrue;
    }
    return Qfalse;
#else
    rb_notimplement();
#endif
}
clrtoeol()

def clrtoeol

[Source]

/* def clrtoeol */
static VALUE
curses_clrtoeol()
{
    curses_stdscr();
    clrtoeol();
    return Qnil;
}
color_content(p1)
color_pair(p1)
cols()
crmode()

Alias for cbreak

curs_set(p1)
def_prog_mode()
delch()

def delch

[Source]

/* def delch */
static VALUE
curses_delch(obj)
    VALUE obj;
{
    delch();
    return Qnil;
}
deleteln()

def delelteln

[Source]

/* def delelteln */
static VALUE
curses_deleteln(obj)
    VALUE obj;
{
#if defined(HAVE_DELETELN) || defined(deleteln)
    deleteln();
#endif
    return Qnil;
}
doupdate()

def doupdate

[Source]

/* def doupdate */
static VALUE
curses_doupdate(obj)
    VALUE obj;
{
    curses_stdscr();
#ifdef HAVE_DOUPDATE
    doupdate();
#else
    refresh();
#endif
    return Qnil;
}
echo()

def echo

[Source]

/* def echo */
static VALUE
curses_echo(obj)
    VALUE obj;
{
    curses_stdscr();
    echo();
    return Qnil;
}
flash()

def flash

[Source]

/* def flash */
static VALUE
curses_flash(obj)
    VALUE obj;
{
#ifdef HAVE_FLASH
    curses_stdscr();
    flash();
#endif
    return Qnil;
}
getch()

def getch

[Source]

/* def getch */
static VALUE
curses_getch(obj)
    VALUE obj;
{
    rb_read_check(stdin);
    curses_stdscr();
    return UINT2NUM(getch());
}
getmouse()
getstr()

def getstr

[Source]

/* def getstr */
static VALUE
curses_getstr(obj)
    VALUE obj;
{
    char rtn[1024]; /* This should be big enough.. I hope */

    rb_read_check(stdin);
#if defined(HAVE_GETNSTR)
    getnstr(rtn,1023);
#else
    getstr(rtn);
#endif
    return rb_tainted_str_new2(rtn);
}
has_colors?()
inch()

def inch

[Source]

/* def inch */
static VALUE
curses_inch(obj)
    VALUE obj;
{
    curses_stdscr();
    return CH2FIX(inch());
}
init_color(p1, p2, p3, p4)
init_pair(p1, p2, p3)
init_screen()

def init_screen

[Source]

/* def init_screen */
static VALUE
curses_init_screen()
{
    rb_secure(4);
    if (rb_stdscr) return rb_stdscr;
    initscr();
    if (stdscr == 0) {
    rb_raise(rb_eRuntimeError, "can't initialize curses");
    }
    clear();
    rb_stdscr = prep_window(cWindow, stdscr);
    return rb_stdscr;
}
insch(p1)

def insch(ch)

[Source]

/* def insch(ch) */
static VALUE
curses_insch(obj, ch)
    VALUE obj;
    VALUE ch;
{
    curses_stdscr();
    insch(NUM2CH(ch));
    return Qnil;
}
insertln()

def insertln

[Source]

/* def insertln */
static VALUE
curses_insertln(obj)
    VALUE obj;
{
#if defined(HAVE_INSERTLN) || defined(insertln)
    insertln();
#endif
    return Qnil;
}
keyname(p1)

def keyname

[Source]

/* def keyname */
static VALUE
curses_keyname(obj, c)
    VALUE obj;
    VALUE c;
{
#ifdef HAVE_KEYNAME
  const char *name;

  name = keyname(NUM2INT(c));
  if (name) {
    return rb_str_new2(name);
  } else {
    return Qnil;
  }
#else
  return Qnil;
#endif
}
lines()
mouseinterval(p1)
mousemask(p1)
nl()

def nl

[Source]

/* def nl */
static VALUE
curses_nl(obj)
    VALUE obj;
{
    curses_stdscr();
    nl();
    return Qnil;
}
nocbreak()

def nocbreak

[Source]

/* def nocbreak */
static VALUE
curses_nocbreak(obj)
    VALUE obj;
{
    curses_stdscr();
    nocbreak();
    return Qnil;
}
nocrmode()

Alias for nocbreak

noecho()

def noecho

[Source]

/* def noecho */
static VALUE
curses_noecho(obj)
    VALUE obj;
{
    curses_stdscr();
    noecho();
    return Qnil;
}
nonl()

def nonl

[Source]

/* def nonl */
static VALUE
curses_nonl(obj)
    VALUE obj;
{
    curses_stdscr();
    nonl();
    return Qnil;
}
noraw()

def noraw

[Source]

/* def noraw */
static VALUE
curses_noraw(obj)
    VALUE obj;
{
    curses_stdscr();
    noraw();
    return Qnil;
}
pair_content(p1)
pair_number(p1)
raw()

def raw

[Source]

/* def raw */
static VALUE
curses_raw(obj)
    VALUE obj;
{
    curses_stdscr();
    raw();
    return Qnil;
}
refresh()

def refresh

[Source]

/* def refresh */
static VALUE
curses_refresh(obj)
    VALUE obj;
{
    curses_stdscr();
    refresh();
    return Qnil;
}
reset_prog_mode()
resize(p1, p2)
resizeterm(p1, p2)
scrl(p1)
setpos(p1, p2)

def setpos(y, x)

[Source]

/* def setpos(y, x) */
static VALUE
curses_setpos(obj, y, x)
    VALUE obj;
    VALUE y;
    VALUE x;
{
    curses_stdscr();
    move(NUM2INT(y), NUM2INT(x));
    return Qnil;
}
setscrreg(p1, p2)
standend()

def standend

[Source]

/* def standend */
static VALUE
curses_standend(obj)
    VALUE obj;
{
    standend();
    return Qnil;
}
standout()

def standout

[Source]

/* def standout */
static VALUE
curses_standout(obj)
    VALUE obj;
{
    standout();
    return Qnil;
}
start_color()
stdscr()
timeout=(p1)

USE_MOUSE

[Source]

/* USE_MOUSE */

static VALUE
curses_timeout(VALUE obj, VALUE delay)
{
#ifdef HAVE_TIMEOUT
  timeout(NUM2INT(delay));
  return Qnil;
#else
    rb_notimplement();
#endif
}
ungetch(p1)

def ungetch

[Source]

/* def ungetch */
static VALUE
curses_ungetch(obj, ch)
    VALUE obj;
    VALUE ch;
{
#ifdef HAVE_UNGETCH
    curses_stdscr();
    ungetch(NUM2INT(ch));
#else
    rb_notimplement();
#endif
    return Qnil;
}
ungetmouse(p1)


Module: Curses::Key

Module | Curses::Key
In: | curses/curses.c


Class: Curses::MouseEvent

Class | Curses::MouseEvent
In: | curses/curses.c
Parent: | Object

Methods

bstate eid x y z

Public Instance methods

bstate()
eid()
x()
y()
z()


Class: Curses::Window

Class | Curses::Window
In: | curses/curses.c
Parent: | Data

Methods

<< addch addstr attroff attron attrset begx begy bkgd bkgdset box clear close clrtoeol color_set curx cury delch deleteln getbkgd getch getstr idlok inch insch insertln keypad keypad= maxx maxy move new nodelay= noutrefresh refresh resize scrl scroll scrollok setpos setscrreg standend standout subwin timeout=

Public Class methods

new(p1, p2, p3, p4)

def initialize(h, w, top, left)

[Source]

/* def initialize(h, w, top, left) */
static VALUE
window_initialize(obj, h, w, top, left)
    VALUE obj;
    VALUE h;
    VALUE w;
    VALUE top;
    VALUE left;
{
    struct windata *winp;
    WINDOW *window;

    rb_secure(4);
    curses_init_screen();
    Data_Get_Struct(obj, struct windata, winp);
    if (winp->window) delwin(winp->window);
    window = newwin(NUM2INT(h), NUM2INT(w), NUM2INT(top), NUM2INT(left));
    wclear(window);
    winp->window = window;

    return obj;
}

Public Instance methods

<<(p1)

def <<(str)

[Source]

/* def <<(str) */
static VALUE
window_addstr2(obj, str)
    VALUE obj;
    VALUE str;
{
    window_addstr(obj, str);
    return obj;
}
addch(p1)

def addch(ch)

[Source]

/* def addch(ch) */
static VALUE
window_addch(obj, ch)
    VALUE obj;
    VALUE ch;
{
    struct windata *winp;

    GetWINDOW(obj, winp);
    waddch(winp->window, NUM2CH(ch));

    return Qnil;
}
addstr(p1)

def addstr(str)

[Source]

/* def addstr(str) */
static VALUE
window_addstr(obj, str)
    VALUE obj;
    VALUE str;
{
    if (!NIL_P(str)) {
    struct windata *winp;

    GetWINDOW(obj, winp);
    waddstr(winp->window, STR2CSTR(str));
    }
    return Qnil;
}
attroff(p1)
attron(p1)
attrset(p1)
begx()

def begx

[Source]

/* def begx */
static VALUE
window_begx(obj)
    VALUE obj;
{
    struct windata *winp;
    int x, y;

    GetWINDOW(obj, winp);
#ifdef getbegyx
    getbegyx(winp->window, y, x);
    return INT2FIX(x);
#else
    return INT2FIX(winp->window->_begx);
#endif
}
begy()

def begy

[Source]

/* def begy */
static VALUE
window_begy(obj)
    VALUE obj;
{
    struct windata *winp;
    int x, y;

    GetWINDOW(obj, winp);
#ifdef getbegyx
    getbegyx(winp->window, y, x);
    return INT2FIX(y);
#else
    return INT2FIX(winp->window->_begy);
#endif
}
bkgd(p1)
bkgdset(p1)
box(...)

def box(vert, hor)

[Source]

/* def box(vert, hor) */
static VALUE
window_box(argc, argv, self)
    int argc;
    VALUE argv[], self;
{
    struct windata *winp;
    VALUE vert, hor, corn;

    rb_scan_args(argc, argv, "21", &vert, &hor, &corn);

    GetWINDOW(self, winp);
    box(winp->window, NUM2CH(vert), NUM2CH(hor));

    if (!NIL_P(corn)) {
      int cur_x, cur_y, x, y;
      chtype c;

      c = NUM2CH(corn);
      getyx(winp->window, cur_y, cur_x);
      x = NUM2INT(window_maxx(self)) - 1;
      y = NUM2INT(window_maxy(self)) - 1;
      wmove(winp->window, 0, 0);
      waddch(winp->window, c);
      wmove(winp->window, y, 0);
      waddch(winp->window, c);
      wmove(winp->window, y, x);
      waddch(winp->window, c);
      wmove(winp->window, 0, x);
      waddch(winp->window, c);
      wmove(winp->window, cur_y, cur_x);
    }

    return Qnil;
}
clear()

def clear

[Source]

/* def clear */
static VALUE
window_clear(obj)
    VALUE obj;
{
    struct windata *winp;

    GetWINDOW(obj, winp);
    wclear(winp->window);

    return Qnil;
}
close()

def close

[Source]

/* def close */
static VALUE
window_close(obj)
    VALUE obj;
{
    struct windata *winp;

    GetWINDOW(obj, winp);
    delwin(winp->window);
    winp->window = 0;

    return Qnil;
}
clrtoeol()

def clrtoeol

[Source]

/* def clrtoeol */
static VALUE
window_clrtoeol(obj)
    VALUE obj;
{
    struct windata *winp;

    GetWINDOW(obj, winp);
    wclrtoeol(winp->window);

    return Qnil;
}
color_set(p1)
curx()

def curx

[Source]

/* def curx */
static VALUE
window_curx(obj)
    VALUE obj;
{
    struct windata *winp;
    int x, y;

    GetWINDOW(obj, winp);
    getyx(winp->window, y, x);
    return INT2FIX(x);
}
cury()

def cury

[Source]

/* def cury */
static VALUE
window_cury(obj)
    VALUE obj;
{
    struct windata *winp;
    int x, y;

    GetWINDOW(obj, winp);
    getyx(winp->window, y, x);
    return INT2FIX(y);
}
delch()

def delch

[Source]

/* def delch */
static VALUE
window_delch(obj)
    VALUE obj;
{
    struct windata *winp;

    GetWINDOW(obj, winp);
    wdelch(winp->window);
    return Qnil;
}
deleteln()

def delelteln

[Source]

/* def delelteln */
static VALUE
window_deleteln(obj)
    VALUE obj;
{
#if defined(HAVE_WDELETELN) || defined(wdeleteln)
    struct windata *winp;

    GetWINDOW(obj, winp);
    wdeleteln(winp->window);
#endif
    return Qnil;
}
getbkgd()
getch()

def getch

[Source]

/* def getch */
static VALUE
window_getch(obj)
    VALUE obj;
{
    struct windata *winp;

    rb_read_check(stdin);
    GetWINDOW(obj, winp);
    return UINT2NUM(wgetch(winp->window));
}
getstr()

def getstr

[Source]

/* def getstr */
static VALUE
window_getstr(obj)
    VALUE obj;
{
    struct windata *winp;
    char rtn[1024]; /* This should be big enough.. I hope */

    GetWINDOW(obj, winp);
    rb_read_check(stdin);
#if defined(HAVE_WGETNSTR)
    wgetnstr(winp->window, rtn, 1023);
#else
    wgetstr(winp->window, rtn);
#endif
    return rb_tainted_str_new2(rtn);
}
idlok(p1)
inch()

def inch

[Source]

/* def inch */
static VALUE
window_inch(obj)
    VALUE obj;
{
    struct windata *winp;

    GetWINDOW(obj, winp);
    return CH2FIX(winch(winp->window));
}
insch(p1)

def insch(ch)

[Source]

/* def insch(ch) */
static VALUE
window_insch(obj, ch)
    VALUE obj;
    VALUE ch;
{
    struct windata *winp;

    GetWINDOW(obj, winp);
    winsch(winp->window, NUM2CH(ch));

    return Qnil;
}
insertln()

def insertln

[Source]

/* def insertln */
static VALUE
window_insertln(obj)
    VALUE obj;
{
#if defined(HAVE_WINSERTLN) || defined(winsertln)
    struct windata *winp;

    GetWINDOW(obj, winp);
    winsertln(winp->window);
#endif
    return Qnil;
}
keypad(p1)
keypad=(p1)
maxx()

def maxx

[Source]

/* def maxx */
static VALUE
window_maxx(obj)
    VALUE obj;
{
    struct windata *winp;

    GetWINDOW(obj, winp);
#if defined(getmaxx)
    return INT2FIX(getmaxx(winp->window));
#elif defined(getmaxyx)
    {
    int x, y;
    getmaxyx(winp->window, y, x);
    return INT2FIX(x);
    }
#else
    return INT2FIX(winp->window->_maxx+1);
#endif
}
maxy()

def maxy

[Source]

/* def maxy */
static VALUE
window_maxy(obj)
    VALUE obj;
{
    struct windata *winp;

    GetWINDOW(obj, winp);
#if defined(getmaxy)
    return INT2FIX(getmaxy(winp->window));
#elif defined(getmaxyx)
    {
    int x, y;
    getmaxyx(winp->window, y, x);
    return INT2FIX(y);
    }
#else
    return INT2FIX(winp->window->_maxy+1);
#endif
}
move(p1, p2)

def move(y, x)

[Source]

/* def move(y, x) */
static VALUE
window_move(obj, y, x)
    VALUE obj;
    VALUE y;
    VALUE x;
{
    struct windata *winp;

    GetWINDOW(obj, winp);
    mvwin(winp->window, NUM2INT(y), NUM2INT(x));

    return Qnil;
}
nodelay=(p1)
noutrefresh()

def noutrefresh

[Source]

/* def noutrefresh */
static VALUE
window_noutrefresh(obj)
    VALUE obj;
{
    struct windata *winp;

    GetWINDOW(obj, winp);
#ifdef HAVE_DOUPDATE
    wnoutrefresh(winp->window);
#else
    wrefresh(winp->window);
#endif

    return Qnil;
}
refresh()

def refresh

[Source]

/* def refresh */
static VALUE
window_refresh(obj)
    VALUE obj;
{
    struct windata *winp;

    GetWINDOW(obj, winp);
    wrefresh(winp->window);

    return Qnil;
}
resize(p1, p2)
scrl(p1)
scroll()

USE_COLOR

[Source]

/* USE_COLOR */

static VALUE
window_scroll(VALUE obj)
{
  struct windata *winp;

  GetWINDOW(obj, winp);
  /* may have to raise exception on ERR */
  return (scroll(winp->window) == OK) ? Qtrue : Qfalse;
}
scrollok(p1)
setpos(p1, p2)

def setpos(y, x)

[Source]

/* def setpos(y, x) */
static VALUE
window_setpos(obj, y, x)
    VALUE obj;
    VALUE y;
    VALUE x;
{
    struct windata *winp;

    GetWINDOW(obj, winp);
    wmove(winp->window, NUM2INT(y), NUM2INT(x));
    return Qnil;
}
setscrreg(p1, p2)
standend()

def standend

[Source]

/* def standend */
static VALUE
window_standend(obj)
    VALUE obj;
{
    struct windata *winp;

    GetWINDOW(obj, winp);
    wstandend(winp->window);
    return Qnil;
}
standout()

def standout

[Source]

/* def standout */
static VALUE
window_standout(obj)
    VALUE obj;
{
    struct windata *winp;

    GetWINDOW(obj, winp);
    wstandout(winp->window);
    return Qnil;
}
subwin(p1, p2, p3, p4)

def subwin(height, width, top, left)

[Source]

/* def subwin(height, width, top, left) */
static VALUE
window_subwin(obj, height, width, top, left)
    VALUE obj;
    VALUE height;
    VALUE width;
    VALUE top;
    VALUE left;
{
    struct windata *winp;
    WINDOW *window;
    VALUE win;
    int h, w, t, l;

    h = NUM2INT(height);
    w = NUM2INT(width);
    t = NUM2INT(top);
    l = NUM2INT(left);
    GetWINDOW(obj, winp);
    window = subwin(winp->window, h, w, t, l);
    win = prep_window(rb_obj_class(obj), window);

    return win;
}
timeout=(p1)


File: curses.c

curses.c

Path: | curses/curses.c
Last Update: | Sat Oct 15 23:43:50 AUS Eastern Standard Time 2005


File: hello.rb

hello.rb

Path: | curses/hello.rb
Last Update: | Mon Aug 13 09:42:44 AUS Eastern Standard Time 2001

Required files

curses

Methods

show_message

Included Modules

Curses

Public Instance methods

show_message(message)

[Source]

# File curses/hello.rb, line 6
def show_message(message)
  width = message.length + 6
  win = Window.new(5, width,
                   (lines - 5) / 2, (cols - width) / 2)
  win.box(?|, ?-)
  win.setpos(2, 3)
  win.addstr(message)
  win.refresh
  win.getch
  win.close
end


File: mouse.rb

mouse.rb

Path: | curses/mouse.rb
Last Update: | Mon Aug 13 09:42:44 AUS Eastern Standard Time 2001

Required files

curses

Methods

show_message

Included Modules

Curses

Public Instance methods

show_message(*msgs)

[Source]

# File curses/mouse.rb, line 6
def show_message(*msgs)
  message = msgs.join
  width = message.length + 6
  win = Window.new(5, width,
                   (lines - 5) / 2, (cols - width) / 2)
  win.keypad = true
  win.attron(color_pair(COLOR_RED)){
    win.box(?|, ?-, ?+)
  }
  win.setpos(2, 3)
  win.addstr(message)
  win.refresh
  win.getch
  win.close
end


File: rain.rb

rain.rb

Path: | curses/rain.rb
Last Update: | Fri Jan 16 22:13:07 AUS Eastern Daylight Time 1998

rain for a curses test

Required files

curses

Methods

onsig ranf

Included Modules

Curses

Public Instance methods

onsig(sig)

[Source]

# File curses/rain.rb, line 7
def onsig(sig)
  close_screen
  exit sig
end
ranf()

[Source]

# File curses/rain.rb, line 12
def ranf
  rand(32767).to_f / 32767
end


File: view.rb

view.rb

Path: | curses/view.rb
Last Update: | Sat Oct 15 23:43:50 AUS Eastern Standard Time 2005

Required files

curses

Included Modules

Curses


File: view2.rb

view2.rb

Path: | curses/view2.rb
Last Update: | Tue Jun 18 16:29:07 AUS Eastern Standard Time 2002

Required files

curses

Methods

scroll_down scroll_up

Public Instance methods

scroll_down()

[Source]

# File curses/view2.rb, line 57
def scroll_down
  if( $top + $screen.maxy < $data_lines.length )
    $screen.scrl(1)
    $top += 1
    str = $data_lines[$top + $screen.maxy - 1]
    if( str )
      $screen.setpos($screen.maxy - 1, 0)
      $screen.addstr(str)
    end
    return true
  else
    return false
  end
end
scroll_up()

[Source]

# File curses/view2.rb, line 42
def scroll_up
  if( $top > 0 )
    $screen.scrl(-1)
    $top -= 1
    str = $data_lines[$top]
    if( str )
      $screen.setpos(0, 0)
      $screen.addstr(str)
    end
    return true
  else
    return false
  end
end


File: date.rb

date.rb

Path: | date.rb
Last Update: | Sat Oct 15 23:44:27 AUS Eastern Standard Time 2005

date.rb - date and time library

Author: Tadayoshi Funaba 1998-2005

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


Class: Date

Class | Date
In: | date.rb date/format.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_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_leap? ld ld_to_jd leap? mday mjd mjd_to_jd mon month new new_start next ns? ns? ordinal ordinal_to_jd os? os? parse start step strftime strptime succ time_to_day_fraction to_s today upto valid_civil? valid_commercial? valid_jd? valid_ordinal? wday yday year zone_to_diff

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 = false A constant used to indicate that a Date should always use the Julian calendar.
GREGORIAN = true A constant used to indicate that a Date should always use the Gregorian calendar.
MONTHS = { 'january' => 1, 'february' => 2, 'march' => 3, 'april' => 4, 'may' => 5, 'june' => 6, 'july' => 7, 'august' => 8, 'september'=> 9, 'october' =>10, 'november' =>11, 'december' =>12
DAYS = { 'sunday' => 0, 'monday' => 1, 'tuesday' => 2, 'wednesday'=> 3, 'thursday' => 4, 'friday' => 5, 'saturday' => 6
ABBR_MONTHS = { 'jan' => 1, 'feb' => 2, 'mar' => 3, 'apr' => 4, 'may' => 5, 'jun' => 6, 'jul' => 7, 'aug' => 8, 'sep' => 9, 'oct' =>10, 'nov' =>11, 'dec' =>12
ABBR_DAYS = { 'sun' => 0, 'mon' => 1, 'tue' => 2, 'wed' => 3, 'thu' => 4, 'fri' => 5, 'sat' => 6
ZONES = { 'ut' => 0*3600, 'gmt' => 0*3600, 'est' => -5*3600, 'edt' => -4*3600, 'cst' => -6*3600, 'cdt' => -5*3600, 'mst' => -7*3600, 'mdt' => -6*3600, 'pst' => -8*3600, 'pdt' => -7*3600, 'a' => 1*3600, 'b' => 2*3600, 'c' => 3*3600, 'd' => 4*3600, 'e' => 5*3600, 'f' => 6*3600, 'g' => 7*3600, 'h' => 8*3600, 'i' => 9*3600, 'k' => 10*3600, 'l' => 11*3600, 'm' => 12*3600, 'n' => -1*3600, 'o' => -2*3600, 'p' => -3*3600, 'q' => -4*3600, 'r' => -5*3600, 's' => -6*3600, 't' => -7*3600, 'u' => -8*3600, 'v' => -9*3600, 'w' =>-10*3600, 'x' =>-11*3600, 'y' =>-12*3600, 'z' => 0*3600, 'utc' => 0*3600, 'wet' => 0*3600, 'bst' => 1*3600, 'wat' => -1*3600, 'at' => -2*3600, 'ast' => -4*3600, 'adt' => -3*3600, 'yst' => -9*3600, 'ydt' => -8*3600, 'hst' =>-10*3600, 'hdt' => -9*3600, 'cat' =>-10*3600, 'ahst'=>-10*3600, 'nt' =>-11*3600, 'idlw'=>-12*3600, 'cet' => 1*3600, 'met' => 1*3600, 'mewt'=> 1*3600, 'mest'=> 2*3600, 'mesz'=> 2*3600, 'swt' => 1*3600, 'sst' => 2*3600, 'fwt' => 1*3600, 'fst' => 2*3600, 'eet' => 2*3600, 'bt' => 3*3600, 'zp4' => 4*3600, 'zp5' => 5*3600, 'zp6' => 6*3600, 'wast'=> 7*3600, 'wadt'=> 8*3600, 'cct' => 8*3600, 'jst' => 9*3600, 'east'=> 10*3600, 'eadt'=> 11*3600, 'gst' => 10*3600, 'nzt' => 12*3600, 'nzst'=> 12*3600, 'nzdt'=> 13*3600, 'idle'=> 12*3600
PARSE_MONTHPAT = ABBR_MONTHS.keys.join('|')
PARSE_DAYPAT = ABBR_DAYS. keys.join('|')

External Aliases

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

Public Class methods

_load(str)

Load from Marshall format.

[Source]

# File date.rb, line 1032
  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
    new0(ajd, of, sg)
  end
_parse(str, comp=false)

[Source]

# File date/format.rb, line 250
  def self._parse(str, comp=false)
    str = str.dup

    str.gsub!(/[^-+,.\/:0-9a-z]+/ino, ' ')

    # day
    if str.sub!(/(#{PARSE_DAYPAT})\S*/ino, ' ')
      wday = ABBR_DAYS[$1.downcase]
    end

    # time
    if str.sub!(
                /(\d+):(\d+)
                 (?:
                   :(\d+)(?:[,.](\d*))?
                 )?
                 (?:
                   \s*
                   ([ap])(?:m\b|\.m\.)
                 )?
                 (?:
                   \s*
                   (
                     [a-z]+(?:\s+dst)?\b
                   |
                     [-+]\d+(?::?\d+)
                   )
                 )?
                /inox,
                ' ')
      hour = $1.to_i
      min = $2.to_i
      sec = $3.to_i if $3
      if $4
        sec_fraction = $4.to_i.to_r / (10**$4.size)
      end

      if $5
        hour %= 12
        if $5.downcase == 'p'
          hour += 12
        end
      end

      if $6
        zone = $6
      end
    end

    # eu
    if str.sub!(
                /(\d+)\S*
                 \s+
                 (#{PARSE_MONTHPAT})\S*
                 (?:
                   \s+
                   (-?\d+)
                 )?
                /inox,
                ' ')
      mday = $1.to_i
      mon = ABBR_MONTHS[$2.downcase]

      if $3
        year = $3.to_i
        if $3.size > 2
          comp = false
        end
      end

    # us
    elsif str.sub!(
                   /(#{PARSE_MONTHPAT})\S*
                    \s+
                    (\d+)\S*
                    (?:
                      \s+
                      (-?\d+)
                    )?
                   /inox,
                   ' ')
      mon = ABBR_MONTHS[$1.downcase]
      mday = $2.to_i

      if $3
        year = $3.to_i
        if $3.size > 2
          comp = false
        end
      end

    # iso
    elsif str.sub!(/([-+]?\d+)-(\d+)-(-?\d+)/no, ' ')
      year = $1.to_i
      mon = $2.to_i
      mday = $3.to_i

      if $1.size > 2
        comp = false
      elsif $3.size > 2
        comp = false
        mday, mon, year = year, mon, mday
      end

    # jis
    elsif str.sub!(/([MTSH])(\d+)\.(\d+)\.(\d+)/ino, ' ')
      e = { 'm'=>1867,
            't'=>1911,
            's'=>1925,
            'h'=>1988
          }[$1.downcase]
      year = $2.to_i + e
      mon = $3.to_i
      mday = $4.to_i

    # vms
    elsif str.sub!(/(-?\d+)-(#{PARSE_MONTHPAT})[^-]*-(-?\d+)/ino, ' ')
      mday = $1.to_i
      mon = ABBR_MONTHS[$2.downcase]
      year = $3.to_i

      if $1.size > 2
        comp = false
        year, mon, mday = mday, mon, year
      elsif $3.size > 2
        comp = false
      end

    # sla
    elsif str.sub!(%r|(-?\d+)/(\d+)(?:/(-?\d+))?|no, ' ')
      mon = $1.to_i
      mday = $2.to_i

      if $3
        year = $3.to_i
        if $3.size > 2
          comp = false
        end
      end

      if $3 && $1.size > 2
        comp = false
        year, mon, mday = mon, mday, year
      end

    # ddd
    elsif str.sub!(
                   /([-+]?)(\d{4,14})
                    (?:
                      \s*
                      T?
                      \s*
                      (\d{2,6})(?:[,.](\d*))?
                    )?
                    (?:
                      \s*
                      (
                        Z
                      |
                        [-+]\d{2,4}
                      )
                      \b
                    )?
                   /inox,
                   ' ')
      case $2.size
      when 4
        mon  = $2[ 0, 2].to_i
        mday = $2[ 2, 2].to_i
      when 6
        year = ($1 + $2[ 0, 2]).to_i
        mon  = $2[ 2, 2].to_i
        mday = $2[ 4, 2].to_i
      when 8, 10, 12, 14
        year = ($1 + $2[ 0, 4]).to_i
        mon  = $2[ 4, 2].to_i
        mday = $2[ 6, 2].to_i
        hour = $2[ 8, 2].to_i if $2.size >= 10
        min  = $2[10, 2].to_i if $2.size >= 12
        sec  = $2[12, 2].to_i if $2.size >= 14
        comp = false
      end
      if $3
        case $3.size
        when 2, 4, 6
          hour = $3[ 0, 2].to_i
          min  = $3[ 2, 2].to_i if $3.size >= 4
          sec  = $3[ 4, 2].to_i if $3.size >= 6
        end
      end
      if $4
        sec_fraction = $4.to_i.to_r / (10**$4.size)
      end
      if $5
        zone = $5
      end
    end

    if str.sub!(/\b(bc\b|bce\b|b\.c\.|b\.c\.e\.)/ino, ' ')
      if year
        year = -year + 1
      end
    end

    if comp and year
      if year >= 0 and year <= 99
        if year >= 69
          year += 1900
        else
          year += 2000
        end
      end
    end

    elem = {}
    elem[:year] = year if year
    elem[:mon] = mon if mon
    elem[:mday] = mday if mday
    elem[:hour] = hour if hour
    elem[:min] = min if min
    elem[:sec] = sec if sec
    elem[:sec_fraction] = sec_fraction if sec_fraction
    elem[:zone] = zone if zone
    offset = zone_to_diff(zone) if zone
    elem[:offset] = offset if offset
    elem[:wday] = wday if wday
    elem
  end
_strptime(str, fmt='%F')

[Source]

# File date/format.rb, line 242
  def self._strptime(str, fmt='%F')
    elem = {}
    elem if __strptime(str.dup, fmt, elem)
  end
ajd_to_amjd(ajd)

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

[Source]

# File date.rb, line 448
  def self.ajd_to_amjd(ajd) ajd - 4800001.to_r/2 end
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.

[Source]

# File date.rb, line 414
  def self.ajd_to_jd(ajd, of=0) clfloor(ajd + of + 1.to_r/2) end
amjd_to_ajd(amjd)

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

[Source]

# File date.rb, line 444
  def self.amjd_to_ajd(amjd) amjd + 4800001.to_r/2 end
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.

[Source]

# File date.rb, line 590
  def self.civil(y=-4712, m=1, d=1, sg=ITALY)
    unless jd = valid_civil?(y, m, d, sg)
      raise ArgumentError, 'invalid date'
    end
    new0(jd_to_ajd(jd, 0, 0), 0, sg)
  end
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.

[Source]

# File date.rb, line 295
  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 os?(jd, sg)
      jd -= b
    end
    jd
  end
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.

[Source]

# File date.rb, line 640
  def self.commercial(y=1582, w=41, d=5, sg=ITALY)
    unless jd = valid_commercial?(y, w, d, sg)
      raise ArgumentError, 'invalid date'
    end
    new0(jd_to_ajd(jd, 0, 0), 0, sg)
  end
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.

[Source]

# File date.rb, line 384
  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
day_fraction_to_time(fr)

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

[Source]

# File date.rb, line 429
  def self.day_fraction_to_time(fr)
    h,   fr = clfloor(fr, 1.to_r/24)
    min, fr = clfloor(fr, 1.to_r/1440)
    s,   fr = clfloor(fr, 1.to_r/86400)
    return h, min, s, fr
  end
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.

[Source]

# File date.rb, line 480
  def self.gregorian_leap? (y) y % 4 == 0 and y % 100 != 0 or y % 400 == 0 end
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.

[Source]

# File date.rb, line 496
  def self.jd(jd=0, sg=ITALY)
    jd = valid_jd?(jd, sg)
    new0(jd_to_ajd(jd, 0, 0), 0, sg)
  end
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.

[Source]

# File date.rb, line 425
  def self.jd_to_ajd(jd, fr, of=0) jd + fr - of - 1.to_r/2 end
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.

[Source]

# File date.rb, line 317
  def self.jd_to_civil(jd, sg=GREGORIAN)
    if os?(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
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]

[Source]

# File date.rb, line 369
  def self.jd_to_commercial(jd, sg=GREGORIAN)
    ns = ns?(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
    d = (jd + 1) % 7
    if d.zero? then d = 7 end
    return y, w, d
  end
jd_to_ld(jd)

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

[Source]

# File date.rb, line 464
  def self.jd_to_ld(jd) jd - 2299160 end
jd_to_mjd(jd)

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

[Source]

# File date.rb, line 456
  def self.jd_to_mjd(jd) jd - 2400001 end
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]

[Source]

# File date.rb, line 356
  def self.jd_to_ordinal(jd, sg=GREGORIAN)
    y = jd_to_civil(jd, sg)[0]
    doy = jd - civil_to_jd(y - 1, 12, 31, ns?(jd, sg))
    return y, doy
  end
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.

[Source]

# File date.rb, line 469
  def self.jd_to_wday(jd) (jd + 1) % 7 end
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.

[Source]

# File date.rb, line 474
  def self.julian_leap? (y) y % 4 == 0 end
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.

[Source]

# File date.rb, line 460
  def self.ld_to_jd(ld) ld + 2299160 end
mjd_to_jd(mjd)

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

[Source]

# File date.rb, line 452
  def self.mjd_to_jd(mjd) mjd + 2400001 end
new(ajd=0, of=0, sg=ITALY)

NOTE this is the documentation for the method new0(). 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.

[Source]

# File date.rb, line 751
  def initialize(ajd=0, of=0, sg=ITALY) @ajd, @of, @sg = ajd, of, sg end
ns?(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.

[Source]

# File date.rb, line 288
  def self.ns? (jd, sg) not os?(jd, sg) end
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.

[Source]

# File date.rb, line 538
  def self.ordinal(y=-4712, d=1, sg=ITALY)
    unless jd = valid_ordinal?(y, d, sg)
      raise ArgumentError, 'invalid date'
    end
    new0(jd_to_ajd(jd, 0, 0), 0, sg)
  end
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.

[Source]

# File date.rb, line 345
  def self.ordinal_to_jd(y, d, sg=GREGORIAN)
    civil_to_jd(y, 1, d, sg)
  end
os?(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.

[Source]

# File date.rb, line 276
  def self.os? (jd, sg)
    case sg
    when Numeric; jd < sg
    else;         not sg
    end
  end
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.

[Source]

# File date.rb, line 694
  def self.parse(str='-4712-01-01', comp=false, sg=ITALY)
    elem = _parse(str, comp)
    new_with_hash(elem, sg)
  end
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.

[Source]

# File date.rb, line 674
  def self.strptime(str='-4712-01-01', fmt='%F', sg=ITALY)
    elem = _strptime(str, fmt)
    new_with_hash(elem, sg)
  end
time_to_day_fraction(h, min, s)

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

[Source]

# File date.rb, line 438
  def self.time_to_day_fraction(h, min, s)
    h.to_r/24 + min.to_r/1440 + s.to_r/86400
  end
today(sg=ITALY)

Create a new Date object representing today.

sg specifies the Day of Calendar Reform.

[Source]

# File date.rb, line 702
  def self.today(sg=ITALY)
    jd = civil_to_jd(*(Time.now.to_a[3..5].reverse << sg))
    new0(jd_to_ajd(jd, 0, 0), 0, sg)
  end
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.

[Source]

# File date.rb, line 557
  def self.valid_civil? (y, m, d, sg=ITALY)
    if m < 0
      m += 13
    end
    if d < 0
      ny, nm = clfloor(y * 12 + m, 12)
      nm,    = clfloor(nm + 1, 1)
      jd = civil_to_jd(ny, nm, d + 1, sg)
      ns = ns?(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?(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.

[Source]

# File date.rb, line 613
  def self.valid_commercial? (y, w, d, sg=ITALY)
    if d < 0
      d += 8
    end
    if w < 0
      w = jd_to_commercial(commercial_to_jd(y + 1, 1, 1) + w * 7)[1]
    end
    jd = commercial_to_jd(y, w, d)
    return unless ns?(jd, sg)
    return unless [y, w, d] == jd_to_commercial(jd)
    jd
  end
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.

[Source]

# File date.rb, line 489
  def self.valid_jd? (jd, sg=ITALY) jd end
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.

[Source]

# File date.rb, line 514
  def self.valid_ordinal? (y, d, sg=ITALY)
    if d < 0
      ny, = clfloor(y + 1, 1)
      jd = ordinal_to_jd(ny, d + 1, sg)
      ns = ns?(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
zone_to_diff(str)

[Source]

# File date/format.rb, line 479
  def self.zone_to_diff(str)
    abb, dst = str.downcase.split(/\s+/o, 2)
    if ZONES.include?(abb)
      offset  = ZONES[abb]
      offset += 3600 if dst
    elsif /\A([-+])(\d{2}):?(\d{2})?\Z/no =~ str
      offset = $2.to_i * 3600 + $3.to_i * 60
      offset *= -1 if $1 == '-'
    end
    offset
  end

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.

[Source]

# File date.rb, line 901
  def + (n)
    case n
    when Numeric; return self.class.new0(@ajd + n, @of, @sg)
    end
    raise TypeError, 'expected numeric'
  end
-(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.

[Source]

# File date.rb, line 916
  def - (x)
    case x
    when Numeric; return self.class.new0(@ajd - x, @of, @sg)
    when Date;    return @ajd - x.ajd
    end
    raise TypeError, 'expected numeric or date'
  end
<<(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.

[Source]

# File date.rb, line 977
  def << (n) self >> -n end
<=>(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.

[Source]

# File date.rb, line 935
  def <=> (other)
    case other
    when Numeric; return @ajd <=> other
    when Date;    return @ajd <=> other.ajd
    end
    nil
  end
===(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.

[Source]

# File date.rb, line 949
  def === (other)
    case other
    when Numeric; return jd == other
    when Date;    return jd == other.jd
    end
    false
  end
>>(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.

[Source]

# File date.rb, line 963
  def >> (n)
    y, m = clfloor(year * 12 + (mon - 1) + n, 12)
    m,   = clfloor(m + 1, 1)
    d = mday
    d -= 1 until jd2 = self.class.valid_civil?(y, m, d, ns?)
    self + (jd2 - jd)
  end
_dump(limit)

Dump to Marshal format.

[Source]

# File date.rb, line 1027
  def _dump(limit) Marshal.dump([@ajd, @of, @sg], -1) end
ajd()

Get the date as an Astronomical Julian Day Number.

[Source]

# File date.rb, line 754
  def ajd() @ajd end
amjd()

Get the date as an Astronomical Modified Julian Day Number.

[Source]

# File date.rb, line 757
  def amjd() self.class.ajd_to_amjd(@ajd) end
asctime()

alias_method :format, :strftime

[Source]

# File date/format.rb, line 582
  def asctime() strftime('%c') end
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.

[Source]

# File date.rb, line 841
  def cwday() commercial[2] end
cweek()

Get the commercial week of the year of this date.

[Source]

# File date.rb, line 837
  def cweek() commercial[1] end
cwyear()

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

[Source]

# File date.rb, line 834
  def cwyear() commercial[0] end
day()

Alias for mday

day_fraction()

Get any fractional day part of the date.

[Source]

# File date.rb, line 765
  def day_fraction() self.class.ajd_to_jd(@ajd, @of)[1] end
downto(min) {|date| ...}

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

[Source]

# File date.rb, line 1001
  def downto(min, &block) # :yield: date
      step(min, -1, &block)
  end
england()

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

[Source]

# File date.rb, line 877
  def england() new_start(self.class::ENGLAND) end
eql?(other)

Is this Date equal to other?

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

[Source]

# File date.rb, line 1013
  def eql? (other) Date === other and self == other end
gregorian()

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

[Source]

# File date.rb, line 885
  def gregorian() new_start(self.class::GREGORIAN) end
hash()

Calculate a hash value for this date.

[Source]

# File date.rb, line 1016
  def hash() @ajd.hash end
inspect()

Return internal object state as a programmer-readable string.

[Source]

# File date.rb, line 1019
  def inspect() format('#<%s: %s,%s,%s>', self.class, @ajd, @of, @sg) end
italy()

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

[Source]

# File date.rb, line 873
  def italy() new_start(self.class::ITALY) end
jd()

Get the date as a Julian Day Number.

[Source]

# File date.rb, line 762
  def jd() self.class.ajd_to_jd(@ajd, @of)[0] end
julian()

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

[Source]

# File date.rb, line 881
  def julian() new_start(self.class::JULIAN) end
ld()

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

[Source]

# File date.rb, line 772
  def ld() self.class.jd_to_ld(jd) end
leap?()

Is this a leap year?

[Source]

# File date.rb, line 858
  def leap?
    self.class.jd_to_civil(self.class.civil_to_jd(year, 3, 1, ns?) - 1,
                     ns?)[-1] == 29
  end
mday()

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

[Source]

# File date.rb, line 802
  def mday() civil[2] end
mjd()

Get the date as a Modified Julian Day Number.

[Source]

# File date.rb, line 768
  def mjd() self.class.jd_to_mjd(jd) end
mon()

Get the month of this date.

January is month 1.

[Source]

# File date.rb, line 799
  def mon() civil[1] end
month()

Alias for mon

new_start(sg=self.class::ITALY)

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

[Source]

# File date.rb, line 869
  def new_start(sg=self.class::ITALY) self.class.new0(@ajd, @of, sg) end
next()

Alias for succ

ns?()

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

[Source]

# File date.rb, line 853
  def ns? () self.class.ns?(jd, @sg) end
os?()

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

[Source]

# File date.rb, line 850
  def os? () self.class.os?(jd, @sg) end
start()

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

[Source]

# File date.rb, line 866
  def start() @sg end
step(limit, step) {|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.

[Source]

# File date.rb, line 983
  def step(limit, step)  # :yield: date
    da = self
    op = [:-,:<=,:>=][step<=>0]
    while da.__send__(op, limit)
      yield da
      da += step
    end
    self
  end
strftime(fmt='%F')

[Source]

# File date/format.rb, line 491
  def strftime(fmt='%F')
    o = ''
    fmt.scan(/%[EO]?.|./o) do |c|
      cc = c.sub(/^%[EO]?(.)$/o, '%\\1')
      case cc
      when '%A'; o << DAYNAMES[wday]
      when '%a'; o << ABBR_DAYNAMES[wday]
      when '%B'; o << MONTHNAMES[mon]
      when '%b'; o << ABBR_MONTHNAMES[mon]
      when '%C'; o << '%02d' % (year / 100.0).floor             # P2,ID
      when '%c'; o << strftime('%a %b %e %H:%M:%S %Y')
      when '%D'; o << strftime('%m/%d/%y')                      # P2,ID
      when '%d'; o << '%02d' % mday
      when '%e'; o <<  '%2d' % mday
      when '%F'; o << strftime('%Y-%m-%d')                      # ID
      when '%G'; o << '%.4d' %  cwyear                          # ID
      when '%g'; o << '%02d' % (cwyear % 100)                   # ID
      when '%H'; o << '%02d' %   hour
      when '%h'; o << strftime('%b')                            # P2,ID
      when '%I'; o << '%02d' % ((hour % 12).nonzero? or 12)
      when '%j'; o << '%03d' % yday
      when '%k'; o <<  '%2d' %   hour                           # AR,TZ,GL
      when '%l'; o <<  '%2d' % ((hour % 12).nonzero? or 12)     # AR,TZ,GL
      when '%M'; o << '%02d' % min
      when '%m'; o << '%02d' % mon
??
      when '%n'; o << "\n"                                      # P2,ID
      when '%P'; o << if hour < 12 then 'am' else 'pm' end      # GL
      when '%p'; o << if hour < 12 then 'AM' else 'PM' end
      when '%R'; o << strftime('%H:%M')                         # ID
      when '%r'; o << strftime('%I:%M:%S %p')                   # P2,ID
      when '%S'; o << '%02d' % sec
      when '%s'                                                 # TZ,GL
        d = ajd - self.class.jd_to_ajd(self.class.civil_to_jd(1970,1,1), 0)
        s = (d * 86400).to_i
        o << '%d' % s
      when '%T'; o << strftime('%H:%M:%S')                      # P2,ID
      when '%t'; o << "\t"                                      # P2,ID
      when '%U', '%W'
        a = self.class.civil_to_jd(year, 1, 1, ns?) + 6
        k = if c == '%U' then 0 else 1 end
        w = (jd - (a - ((a - k) + 1) % 7) + 7) / 7
        o << '%02d' % w
      when '%u'; o <<   '%d' % cwday                            # P2,ID
      when '%V'; o << '%02d' % cweek                            # P2,ID
      when '%v'; o << strftime('%e-%b-%Y')                      # AR,TZ
      when '%w'; o <<   '%d' % wday
      when '%X'; o << strftime('%H:%M:%S')
      when '%x'; o << strftime('%m/%d/%y')
      when '%Y'; o << '%.4d' %  year
      when '%y'; o << '%02d' % (year % 100)
      when '%Z'; o << (if offset.zero? then 'Z' else strftime('%z') end)
      when '%z'                                                 # ID
        o << if offset < 0 then '-' else '+' end
        of = offset.abs
        hh, fr = of.divmod(1.to_r/24)
        mm = fr / (1.to_r/1440)
        o << '%02d' % hh
        o << '%02d' % mm
      when '%%'; o << '%'
      when '%+'; o << strftime('%a %b %e %H:%M:%S %Z %Y')       # TZ
??
      when '%1'
        if $VERBOSE
          warn("warning: %1 is deprecated; forget this")
        end
        o <<   '%d' % jd
      when '%2'
        if $VERBOSE
          warn("warning: %2 is deprecated; use '%Y-%j'")
        end
        o << strftime('%Y-%j')
      when '%3'
        if $VERBOSE
          warn("warning: %3 is deprecated; use '%F'")
        end
        o << strftime('%F')
      else;      o << c
      end
    end
    o
  end
succ()

Return a new Date one day after this one.

[Source]

# File date.rb, line 1006
  def succ() self + 1 end
to_s()

Return the date as a human-readable string.

The format used is YYYY-MM-DD.

[Source]

# File date.rb, line 1024
  def to_s() strftime end
upto(max) {|date| ...}

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

[Source]

# File date.rb, line 995
  def upto(max, &block)  # :yield: date
      step(max, +1, &block)
  end
wday()

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

[Source]

# File date.rb, line 845
  def wday() self.class.jd_to_wday(jd) end
yday()

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

January 1 is day-of-the-year 1

[Source]

# File date.rb, line 794
  def yday() ordinal[1] end
year()

Get the year of this date.

[Source]

# File date.rb, line 789
  def year() civil[0] end


Class: DateTime

Class | DateTime
In: | date.rb date/format.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.

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 now ordinal parse strftime strptime valid_time?

External Aliases

civil -> new

Public Class methods

_strptime(str, fmt='%FT%T%Z')

[Source]

# File date/format.rb, line 590
  def self._strptime(str, fmt='%FT%T%Z')
    super(str, fmt)
  end
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.

[Source]

# File date.rb, line 1172
  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)) and
           (fr = valid_time?(h, min, s))
      raise ArgumentError, 'invalid date'
    end
    new0(jd_to_ajd(jd, fr, of), of, sg)
  end
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.

[Source]

# File date.rb, line 1197
  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)) and
           (fr = valid_time?(h, min, s))
      raise ArgumentError, 'invalid date'
    end
    new0(jd_to_ajd(jd, fr, of), of, sg)
  end
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.

[Source]

# File date.rb, line 1128
  def self.jd(jd=0, h=0, min=0, s=0, of=0, sg=ITALY)
    unless (jd = valid_jd?(jd, sg)) and
           (fr = valid_time?(h, min, s))
      raise ArgumentError, 'invalid date'
    end
    new0(jd_to_ajd(jd, fr, of), of, sg)
  end
now(sg=ITALY)

Create a new DateTime object representing the current time.

sg specifies the Day of Calendar Reform.

[Source]

# File date.rb, line 1268
  def self.now(sg=ITALY)
    i = Time.now
    a = i.to_a[0..5].reverse
    jd = civil_to_jd(*(a[0,3] << sg))
    fr = time_to_day_fraction(*(a[3,3])) + i.usec.to_r/86400000000
    of = i.utc_offset.to_r/86400
    new0(jd_to_ajd(jd, fr, of), of, sg)
  end
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.

[Source]

# File date.rb, line 1150
  def self.ordinal(y=-4712, d=1, h=0, min=0, s=0, of=0, sg=ITALY)
    unless (jd = valid_ordinal?(y, d, sg)) and
           (fr = valid_time?(h, min, s))
      raise ArgumentError, 'invalid date'
    end
    new0(jd_to_ajd(jd, fr, of), of, sg)
  end
parse(str='-4712-01-01T00:00:00Z', 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:00Z’; this is Julian Day Number day 0.

sg specifies the Day of Calendar Reform.

[Source]

# File date.rb, line 1258
  def self.parse(str='-4712-01-01T00:00:00Z', comp=false, sg=ITALY)
    elem = _parse(str, comp)
    new_with_hash(elem, sg)
  end
strptime(str='-4712-01-01T00:00:00Z', 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:00Z’, 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.

[Source]

# File date.rb, line 1238
  def self.strptime(str='-4712-01-01T00:00:00Z', fmt='%FT%T%Z', sg=ITALY)
    elem = _strptime(str, fmt)
    new_with_hash(elem, sg)
  end
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.

[Source]

# File date.rb, line 1105
  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..24) === h and
                  (0..59) === min and
                  (0..59) === s
    time_to_day_fraction(h, min, s)
  end

Public Instance methods

strftime(fmt='%FT%T%Z')

[Source]

# File date/format.rb, line 594
  def strftime(fmt='%FT%T%Z')
    super(fmt)
  end


File: format.rb

format.rb

Path: | date/format.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

format.rb: Written by Tadayoshi Funaba 1999-2005 $Id: format.rb,v 2.15 2005-02-06 13:28:48+09 tadf Exp $

Required files

rational


Class: DBM

Class | DBM
In: | dbm/dbm.c
Parent: | Object

Methods

[] []= clear close closed? delete delete_if each each_key each_pair each_value empty? fetch has_key? has_value? include? index indexes indices invert key? keys length member? new open reject reject! replace select shift size store to_a to_hash update value? values values_at

Included Modules

Enumerable

Public Class methods

new(...)
open(...)

Public Instance methods

[](p1)
[]=(p1, p2)
clear()
close()
closed?()
delete(p1)
delete_if()
each()
each_key()
each_pair()
each_value()
empty?()
fetch(...)
has_key?(p1)
has_value?(p1)
include?(p1)
index(p1)
indexes(...)
indices(...)
invert()
key?(p1)
keys()
length()
member?(p1)
reject()
reject!()
replace(p1)
select(...)
shift()
size()
store(p1, p2)
to_a()
to_hash()
update(p1)
value?(p1)
values()
values_at(...)


Class: DBMError

Class | DBMError
In: | dbm/dbm.c
Parent: | StandardError


File: dbm.c

dbm.c

Path: | dbm/dbm.c
Last Update: | Sat Oct 15 23:43:50 AUS Eastern Standard Time 2005


File: delegate.rb

delegate.rb

Path: | delegate.rb
Last Update: | Sat Oct 15 23:44:27 AUS Eastern Standard Time 2005

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

[Source]

# File delegate.rb, line 257
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


Class: Delegator

Class | Delegator
In: | 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.

[Source]

# File 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

Public Instance methods

__getobj__()

This method must be overridden by subclasses and should return the object method calls are being delegated to.

[Source]

# File delegate.rb, line 177
  def __getobj__
    raise NotImplementedError, "need to define `__getobj__'"
  end
marshal_dump()

Serialization support for the object returned by __getobj__.

[Source]

# File delegate.rb, line 182
  def marshal_dump
    __getobj__
  end
marshal_load(obj)

Reinitializes delegation from a serialized object.

[Source]

# File delegate.rb, line 186
  def marshal_load(obj)
    initialize_methods(obj)
  end
method_missing(m, *args)

Handles the magic of delegation through __getobj__.

[Source]

# File 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?(m)

Checks for a method provided by this the delegate object by fowarding the call through __getobj__.

[Source]

# File delegate.rb, line 168
  def respond_to?(m)
    return true if super
    return self.__getobj__.respond_to?(m)
  end


Class: SimpleDelegator

Class | SimpleDelegator
In: | 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.

[Source]

# File delegate.rb, line 200
  def initialize(obj)
    super
    @_sd_obj = obj
  end

Public Instance methods

__getobj__()

Returns the current object method calls are being delegated to.

[Source]

# File delegate.rb, line 206
  def __getobj__
    @_sd_obj
  end
__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

[Source]

# File delegate.rb, line 224
  def __setobj__(obj)
    raise ArgumentError, "cannot delegate to self" if self.equal?(obj)
    @_sd_obj = obj
  end
clone()

Clone support for the object returned by __getobj__.

[Source]

# File delegate.rb, line 230
  def clone
    super
    __setobj__(__getobj__.clone)
  end
dup(obj)

Duplication support for the object returned by __getobj__.

[Source]

# File delegate.rb, line 235
  def dup(obj)
    super
    __setobj__(__getobj__.dup)
  end


Class: Digest::Base

Class | Digest::Base
In: | digest/digest.c
Parent: | Object

Methods

<< == digest digest hexdigest hexdigest initialize_copy new to_s update

Public Class methods

digest(p1)
hexdigest(p1)
new(...)

Public Instance methods

<<(p1)
==(p1)
digest()
hexdigest()
initialize_copy(p1)
to_s()
update(p1)


Module: Digest

Module | Digest
In: | digest/digest.c

Init

Classes and Modules

Class Digest::Base


Class: MD5

Class | MD5
In: | digest/lib/md5.rb
Parent: | Object

Methods

md5

Public Class methods

md5(*args)

[Source]

# File digest/lib/md5.rb, line 11
  def self.md5(*args)
    new(*args)
  end


Class: SHA1

Class | SHA1
In: | digest/lib/sha1.rb
Parent: | Object

Methods

sha1

Public Class methods

sha1(*args)

[Source]

# File digest/lib/sha1.rb, line 11
  def self.sha1(*args)
    new(*args)
  end


File: digest.c

digest.c

Path: | digest/digest.c
Last Update: | Sat Oct 15 23:43:50 AUS Eastern Standard Time 2005


File: md5.rb

md5.rb

Path: | digest/lib/md5.rb
Last Update: | Sat Jul 14 06:06:14 AUS Eastern Standard Time 2001

just for compatibility; requiring "md5" is obsoleted

$RoughId: md5.rb,v 1.4 2001/07/13 15:38:27 knu Exp $ $Id: md5.rb,v 1.1 2001/07/13 20:06:14 knu Exp $

Required files

digest/md5

Constants

MD5 = Digest::MD5


File: sha1.rb

sha1.rb

Path: | digest/lib/sha1.rb
Last Update: | Sat Jul 14 06:06:14 AUS Eastern Standard Time 2001

just for compatibility; requiring "sha1" is obsoleted

$RoughId: sha1.rb,v 1.4 2001/07/13 15:38:27 knu Exp $ $Id: sha1.rb,v 1.1 2001/07/13 20:06:14 knu Exp $

Required files

digest/sha1

Constants

SHA1 = Digest::SHA1


File: md5.c

md5.c

Path: | digest/md5/md5.c
Last Update: | Sat Jul 14 06:06:14 AUS Eastern Standard Time 2001


File: md5init.c

md5init.c

Path: | digest/md5/md5init.c
Last Update: | Fri Sep 27 02:27:23 AUS Eastern Standard Time 2002


File: md5ossl.c

md5ossl.c

Path: | digest/md5/md5ossl.c
Last Update: | Mon Jan 06 21:47:53 AUS Eastern Daylight Time 2003


File: rmd160.c

rmd160.c

Path: | digest/rmd160/rmd160.c
Last Update: | Sat Jul 14 06:06:14 AUS Eastern Standard Time 2001


File: rmd160hl.c

rmd160hl.c

Path: | digest/rmd160/rmd160hl.c
Last Update: | Sat Jul 14 06:06:14 AUS Eastern Standard Time 2001


File: rmd160init.c

rmd160init.c

Path: | digest/rmd160/rmd160init.c
Last Update: | Fri Sep 27 03:26:46 AUS Eastern Standard Time 2002


File: rmd160ossl.c

rmd160ossl.c

Path: | digest/rmd160/rmd160ossl.c
Last Update: | Fri Sep 27 03:26:46 AUS Eastern Standard Time 2002


File: sha1.c

sha1.c

Path: | digest/sha1/sha1.c
Last Update: | Sat Jul 14 06:06:14 AUS Eastern Standard Time 2001


File: sha1hl.c

sha1hl.c

Path: | digest/sha1/sha1hl.c
Last Update: | Sat Jul 14 06:06:14 AUS Eastern Standard Time 2001


File: sha1init.c

sha1init.c

Path: | digest/sha1/sha1init.c
Last Update: | Sat Oct 15 23:43:50 AUS Eastern Standard Time 2005


File: sha1ossl.c

sha1ossl.c

Path: | digest/sha1/sha1ossl.c
Last Update: | Fri Sep 27 03:44:33 AUS Eastern Standard Time 2002


File: sha2.c

sha2.c

Path: | digest/sha2/sha2.c
Last Update: | Sun Jul 27 01:03:12 AUS Eastern Standard Time 2003


File: sha2hl.c

sha2hl.c

Path: | digest/sha2/sha2hl.c
Last Update: | Sat Jul 14 06:06:14 AUS Eastern Standard Time 2001


File: sha2init.c

sha2init.c

Path: | digest/sha2/sha2init.c
Last Update: | Sun Feb 17 22:43:44 AUS Eastern Daylight Time 2002


Module: DL

Module | DL
In: | dl/lib/dl/types.rb dl/lib/dl/struct.rb dl/lib/dl/import.rb dl/dl.c

Methods

callback define_callback dlopen malloc remove_callback sizeof strdup

Classes and Modules

Module DL::Importable
Class DL::DLError
Class DL::DLTypeError
Class DL::Types

Public Instance methods

callback(...)
define_callback(...)
dlopen(...)
malloc(p1)
remove_callback(p1)
sizeof(p1)
strdup(p1)


Class: Array

Class | Array
In: |

Methods

to_ptr

Public Instance methods

to_ptr(...)


Class: DL::DLError

Class | DL::DLError
In: | dl/dl.c
Parent: | StandardError


Class: DL::DLTypeError

Class | DL::DLTypeError
In: | dl/dl.c
Parent: | DL::DLError


Module: DL::Importable

Module | DL::Importable
In: | dl/lib/dl/struct.rb dl/lib/dl/import.rb

Included Modules

Internal

Classes and Modules

Module DL::Importable::Internal

Constants

LIB_MAP = {}


Module: DL::Importable::Internal

Module | DL::Importable::Internal
In: | dl/lib/dl/struct.rb dl/lib/dl/import.rb

Methods

[] _args_ _retval_ callback define_struct define_union dllink dlload encode_argument_types extern import init_sym init_types parse_cproto struct symbol typealias union

Classes and Modules

Class DL::Importable::Internal::Memory
Class DL::Importable::Internal::Struct
Class DL::Importable::Internal::Union

Public Instance methods

[](name)

[Source]

# File dl/lib/dl/import.rb, line 19
      def [](name)
        return @SYM[name.to_s][0]
      end
_args_()

[Source]

# File dl/lib/dl/import.rb, line 180
      def _args_
        return @args
      end
_retval_()

[Source]

# File dl/lib/dl/import.rb, line 184
      def _retval_
        return @retval
      end
callback(proto)

example:

  callback "int method_name(int, char*)"

[Source]

# File dl/lib/dl/import.rb, line 67
      def callback(proto)
        func,ret,args = parse_cproto(proto)

        init_types()
        init_sym()

        rty,renc,rdec = @types.encode_return_type(ret)
        if( !rty )
          raise(TypeError, "unsupported type: #{ret}")
        end
        ty,enc,dec = encode_argument_types(args)
        symty = rty + ty

        module_eval("module_function :#{func}")
        sym = module_eval([
          "DL::callback(\"#{symty}\"){|*args|",
          "  sym,rdec,enc,dec  = @SYM['#{func}']",
          "  args = enc.call(args) if enc",
          "  r,rs = #{func}(*args)",
          "  r  = renc.call(r) if rdec",
          "  rs = dec.call(rs) if (dec && rs)",
          "  @retval = r",
          "  @args   = rs",
          "  @retval",
          "}",
        ].join("\n"))

        @SYM[func] = [sym,rdec,enc,dec]

        return sym
      end
define_struct(contents)

[Source]

# File dl/lib/dl/struct.rb, line 9
      def define_struct(contents)
        init_types()
        Struct.new(@types, contents)
      end
define_union(contents)

[Source]

# File dl/lib/dl/struct.rb, line 15
      def define_union(contents)
        init_types()
        Union.new(@types, contents)
      end
dllink(*libnames)

Alias for dlload

dlload(*libnames)

[Source]

# File dl/lib/dl/import.rb, line 23
      def dlload(*libnames)
        if( !defined?(@LIBS) )
          @LIBS = []
        end
        libnames.each{|libname|
          if( !LIB_MAP[libname] )
            LIB_MAP[libname] = DL.dlopen(libname)
          end
          @LIBS.push(LIB_MAP[libname])
        }
      end
encode_argument_types(tys)

[Source]

# File dl/lib/dl/import.rb, line 188
      def encode_argument_types(tys)
        init_types()
        encty = []
        enc = nil
        dec = nil
        tys.each_with_index{|ty,idx|
          ty,c1,c2 = @types.encode_argument_type(ty)
          if( !ty )
            raise(TypeError, "unsupported type: #{ty}")
          end
          encty.push(ty)
          if( enc )
            if( c1 )
              conv1 = enc
              enc = proc{|v| v = conv1.call(v); v[idx] = c1.call(v[idx]); v}
            end
          else
            if( c1 )
              enc = proc{|v| v[idx] = c1.call(v[idx]); v}
            end
          end
          if( dec )
            if( c2 )
              conv2 = dec
              dec = proc{|v| v = conv2.call(v); v[idx] = c2.call(v[idx]); v}
            end
          else
            if( c2 )
              dec = proc{|v| v[idx] = c2.call(v[idx]); v}
            end
          end
        }
        return [encty.join, enc, dec]
      end
extern(proto)

example:

  extern "int strlen(char*)"

[Source]

# File dl/lib/dl/import.rb, line 59
      def extern(proto)
        func,ret,args = parse_cproto(proto)
        return import(func, ret, args)
      end
import(name, rettype, argtypes = nil)

example:

  import("get_length", "int", ["void*", "int"])

[Source]

# File dl/lib/dl/import.rb, line 134
      def import(name, rettype, argtypes = nil)
        init_types()
        init_sym()

        rty,_,rdec = @types.encode_return_type(rettype)
        if( !rty )
          raise(TypeError, "unsupported type: #{rettype}")
        end
        ty,enc,dec = encode_argument_types(argtypes)
        symty = rty + ty

        sym = symbol(name, symty)

        mname = name.dup
        if( ?A <= mname[0] && mname[0] <= ?Z )
          mname[0,1] = mname[0,1].downcase
        end
        @SYM[mname] = [sym,rdec,enc,dec]

        module_eval [
          "def #{mname}(*args)",
          "  sym,rdec,enc,dec  = @SYM['#{mname}']",
          "  args = enc.call(args) if enc",
          if( $DEBUG )
            "  p \"[DL] call #{mname} with \#{args.inspect}\""
          else
            ""
          end,
          "  r,rs = sym.call(*args)",
          if( $DEBUG )
            "  p \"[DL] retval=\#{r.inspect} args=\#{rs.inspect}\""
          else
            ""
          end,
          "  r  = rdec.call(r) if rdec",
          "  rs = dec.call(rs) if dec",
          "  @retval = r",
          "  @args   = rs",
          "  return @retval",
          "end",
          "module_function :#{mname}",
        ].join("\n")

        return sym
      end
init_sym()

[Source]

# File dl/lib/dl/import.rb, line 15
      def init_sym()
        @SYM ||= {}
      end
init_types()

[Source]

# File dl/lib/dl/import.rb, line 11
      def init_types()
        @types ||= ::DL::Types.new
      end
parse_cproto(proto)

[Source]

# File dl/lib/dl/import.rb, line 36
      def parse_cproto(proto)
        proto = proto.gsub(/\s+/, " ").strip
        case proto
        when /^([\d\w\*_\s]+)\(([\d\w\*_\s\,\[\]]*)\)$/
          ret = $1
          args = $2.strip()
          ret = ret.split(/\s+/)
          args = args.split(/\s*,\s*/)
          func = ret.pop()
          if( func =~ /^\*/ )
            func.gsub!(/^\*+/,"")
            ret.push("*")
          end
          ret  = ret.join(" ")
          return [func, ret, args]
        else
          raise(RuntimeError,"can't parse the function prototype: #{proto}")
        end
      end
struct(contents)

Alias for define_struct

symbol(name, ty = nil)

example:

 symbol "foo_value"
 symbol "foo_func", "IIP"

[Source]

# File dl/lib/dl/import.rb, line 112
      def symbol(name, ty = nil)
        sym = nil
        @LIBS.each{|lib|
          begin
            if( ty )
              sym = lib[name, ty]
            else
              sym = lib[name]
            end
          rescue
            next
          end
        }
        if( !sym )
          raise(RuntimeError, "can't find the symbol `#{name}'")
        end
        return sym
      end
typealias(alias_type, ty1, enc1=nil, dec1=nil, ty2=nil, enc2=nil, dec2=nil)

example:

 typealias("uint", "unsigned int")

[Source]

# File dl/lib/dl/import.rb, line 102
      def typealias(alias_type, ty1, enc1=nil, dec1=nil, ty2=nil, enc2=nil, dec2=nil)
        init_types()
        @types.typealias(alias_type, ty1, enc1, dec1,
                                     ty2||ty1, enc2, dec2)
      end
union(contents)

Alias for define_union


Class: DL::Importable::Internal::Memory

Class | DL::Importable::Internal::Memory
In: | dl/lib/dl/struct.rb
Parent: | Object

Methods

new size to_ptr

Public Class methods

new(ptr, names, ty, len, enc, dec)

[Source]

# File dl/lib/dl/struct.rb, line 22
        def initialize(ptr, names, ty, len, enc, dec)
          @ptr = ptr
          @names = names
          @ty    = ty
          @len   = len
          @enc   = enc
          @dec   = dec

          # define methods
          @names.each{|name|
            instance_eval [
              "def #{name}",
              "  v = @ptr[\"#{name}\"]",
              "  if( @len[\"#{name}\"] )",
              "    v = v.collect{|x| @dec[\"#{name}\"] ? @dec[\"#{name}\"].call(x) : x }",
              "  else",
              "    v = @dec[\"#{name}\"].call(v) if @dec[\"#{name}\"]",
              "  end",
              "  return v",
              "end",
              "def #{name}=(v)",
              "  if( @len[\"#{name}\"] )",
              "    v = v.collect{|x| @enc[\"#{name}\"] ? @enc[\"#{name}\"].call(x) : x }",
              "  else",
              "    v = @enc[\"#{name}\"].call(v) if @enc[\"#{name}\"]",
              "  end",
              "  @ptr[\"#{name}\"] = v",
              "  return v",
              "end",
            ].join("\n")
          }
        end

Public Instance methods

size()

[Source]

# File dl/lib/dl/struct.rb, line 59
        def size
          return @ptr.size
        end
to_ptr()

[Source]

# File dl/lib/dl/struct.rb, line 55
        def to_ptr
          return @ptr
        end


Class: DL::Importable::Internal::Struct

Class | DL::Importable::Internal::Struct
In: | dl/lib/dl/struct.rb
Parent: | Object

Methods

malloc members new new parse parse_elem size

Public Class methods

new(types, contents)

[Source]

# File dl/lib/dl/struct.rb, line 65
        def initialize(types, contents)
          @names = []
          @ty   = {}
          @len  = {}
          @enc  = {}
          @dec  = {}
          @size = 0
          @tys  = ""
          @types = types
          parse(contents)
        end

Public Instance methods

malloc(size = nil)

[Source]

# File dl/lib/dl/struct.rb, line 92
        def malloc(size = nil)
          if( !size )
            size = @size
          end
          ptr = DL::malloc(size)
          return new(ptr)
        end
members()

[Source]

# File dl/lib/dl/struct.rb, line 81
        def members
          return @names
        end
new(ptr)

ptr must be a PtrData object.

[Source]

# File dl/lib/dl/struct.rb, line 86
        def new(ptr)
          ptr.struct!(@tys, *@names)
          mem = Memory.new(ptr, @names, @ty, @len, @enc, @dec)
          return mem
        end
parse(contents)

[Source]

# File dl/lib/dl/struct.rb, line 100
        def parse(contents)
          contents.each{|elem|
            name,ty,num,enc,dec = parse_elem(elem)
            @names.push(name)
            @ty[name]  = ty
            @len[name] = num
            @enc[name] = enc
            @dec[name] = dec
            if( num )
              @tys += "#{ty}#{num}"
            else
              @tys += ty
            end
          }
          @size = DL.sizeof(@tys)
        end
parse_elem(elem)

[Source]

# File dl/lib/dl/struct.rb, line 117
        def parse_elem(elem)
          elem.strip!
          case elem
          when /^([\w\d_\*]+)([\*\s]+)([\w\d_]+)$/
            ty = ($1 + $2).strip
            name = $3
            num = nil;
          when /^([\w\d_\*]+)([\*\s]+)([\w\d_]+)\[(\d+)\]$/
            ty = ($1 + $2).strip
            name = $3
            num = $4.to_i
          else
            raise(RuntimeError, "invalid element: #{elem}")
          end
          ty,enc,dec = @types.encode_struct_type(ty)
          if( !ty )
            raise(TypeError, "unsupported type: #{ty}")
          end
          return [name,ty,num,enc,dec]
        end
size()

[Source]

# File dl/lib/dl/struct.rb, line 77
        def size
          return @size
        end


Class: DL::Importable::Internal::Union

Class | DL::Importable::Internal::Union
In: | dl/lib/dl/struct.rb
Parent: | Struct

Methods

new

Public Instance methods

new()

[Source]

# File dl/lib/dl/struct.rb, line 140
        def new
          ptr = DL::malloc(@size)
          ptr.union!(@tys, *@names)
          mem = Memory.new(ptr, @names, @ty, @len, @enc, @dec)
          return mem
        end


Class: DL::Types

Class | DL::Types
In: | dl/lib/dl/types.rb
Parent: | Object

Methods

encode_argument_type encode_return_type encode_struct_type init_types new typealias

Constants

TYPES = [ # FORMAT: # ["alias name", # "type name", encoding_method, decoding_method, for function prototypes # "type name", encoding_method, decoding_method] for structures (not implemented) # for Windows ["DWORD", "unsigned long", nil, nil, "unsigned long", nil, nil], ["PDWORD", "unsigned long *", nil, nil, "unsigned long *", nil, nil], ["WORD", "unsigned short", nil, nil, "unsigned short", nil, nil], ["PWORD", "unsigned int *", nil, nil, "unsigned int *", nil, nil], ["BYTE", "unsigned char", nil, nil, "unsigned char", nil, nil], ["PBYTE", "unsigned char *", nil, nil, "unsigned char *", nil, nil], ["BOOL", "ibool", nil, nil, "ibool", nil, nil], ["ATOM", "int", nil, nil, "int", nil, nil], ["BYTE", "unsigned char", nil, nil, "unsigned char", nil, nil], ["PBYTE", "unsigned char *", nil, nil, "unsigned char *", nil, nil], ["UINT", "unsigned int", nil, nil, "unsigned int", nil, nil], ["ULONG", "unsigned long", nil, nil, "unsigned long", nil, nil], ["UCHAR", "unsigned char", nil, nil, "unsigned char", nil, nil], ["HANDLE", "unsigned long", nil, nil, "unsigned long", nil, nil], ["PHANDLE","void*", nil, nil, "void*", nil, nil], ["PVOID", "void*", nil, nil, "void*", nil, nil], ["LPCSTR", "char*", nil, nil, "char*", nil, nil], ["HDC", "unsigned int", nil, nil, "unsigned int", nil, nil], ["HWND", "unsigned int", nil, nil, "unsigned int", nil, nil], # Others ["uint", "unsigned int", nil, nil, "unsigned int", nil, nil], ["u_int", "unsigned int", nil, nil, "unsigned int", nil, nil], ["ulong", "unsigned long", nil, nil, "unsigned long", nil, nil], ["u_long", "unsigned long", nil, nil, "unsigned long", nil, nil], # DL::Importable primitive types ["ibool", "I", proc{|v| v ? 1 : 0}, proc{|v| (v != 0) ? true : false}, "I", proc{|v| v ? 1 : 0 }, proc{|v| (v != 0) ? true : false} ], ["cbool", "C", proc{|v| v ? 1 : 0}, proc{|v| (v != 0) ? true : false}, "C", proc{|v,len| v ? 1 : 0}, proc{|v,len| (v != 0) ? true : false}], ["lbool", "L", proc{|v| v ? 1 : 0}, proc{|v| (v != 0) ? true : false}, "L", proc{|v,len| v ? 1 : 0}, proc{|v,len| (v != 0) ? true : false}], ["unsigned char", "C", proc{|v| [v].pack("C").unpack("c")[0]}, proc{|v| [v].pack("c").unpack("C")[0]}, "C", proc{|v| [v].pack("C").unpack("c")[0]}, proc{|v| [v].pack("c").unpack("C")[0]}], ["unsigned short", "H", proc{|v| [v].pack("S").unpack("s")[0]}, proc{|v| [v].pack("s").unpack("S")[0]}, "H", proc{|v| [v].pack("S").unpack("s")[0]}, proc{|v| [v].pack("s").unpack("S")[0]}], ["unsigned int", "I", proc{|v| [v].pack("I").unpack("i")[0]}, proc{|v| [v].pack("i").unpack("I")[0]}, "I", proc{|v| [v].pack("I").unpack("i")[0]}, proc{|v| [v].pack("i").unpack("I")[0]}], ["unsigned long", "L", proc{|v| [v].pack("L").unpack("l")[0]}, proc{|v| [v].pack("l").unpack("L")[0]}, "L", proc{|v| [v].pack("L").unpack("l")[0]}, proc{|v| [v].pack("l").unpack("L")[0]}], ["unsigned char ref", "c", proc{|v| [v].pack("C").unpack("c")[0]}, proc{|v| [v].pack("c").unpack("C")[0]}, nil, nil, nil], ["unsigned int ref", "i", proc{|v| [v].pack("I").unpack("i")[0]}, proc{|v| [v].pack("i").unpack("I")[0]}, nil, nil, nil], ["unsigned long ref", "l", proc{|v| [v].pack("L").unpack("l")[0]}, proc{|v| [v].pack("l").unpack("L")[0]}, nil, nil, nil], ["char ref", "c", nil, nil, nil, nil, nil], ["short ref", "h", nil, nil, nil, nil, nil], ["int ref", "i", nil, nil, nil, nil, nil], ["long ref", "l", nil, nil, nil, nil, nil], ["float ref", "f", nil, nil, nil, nil, nil], ["double ref","d", nil, nil, nil, nil, nil], ["char", "C", nil, nil, "C", nil, nil], ["short", "H", nil, nil, "H", nil, nil], ["int", "I", nil, nil, "I", nil, nil], ["long", "L", nil, nil, "L", nil, nil], ["float", "F", nil, nil, "F", nil, nil], ["double", "D", nil, nil, "D", nil, nil], [/^char\s*\*$/,"s",nil, nil, "S",nil, nil], [/^const char\s*\*$/,"S",nil, nil, "S",nil, nil], [/^.+\*$/, "P", nil, nil, "P", nil, nil], [/^.+\[\]$/, "a", nil, nil, "a", nil, nil], ["void", "0", nil, nil, nil, nil, nil], ]

Public Class methods

new()

[Source]

# File dl/lib/dl/types.rb, line 164
    def initialize
      init_types()
    end

Public Instance methods

encode_argument_type(alias_type)

[Source]

# File dl/lib/dl/types.rb, line 176
    def encode_argument_type(alias_type)
      proc_encode = nil
      proc_decode = nil
      @TYDEFS.each{|aty,ty,enc,dec,_,_,_|
        if( (aty.is_a?(Regexp) && (aty =~ alias_type)) || (aty == alias_type) )
          alias_type = alias_type.gsub(aty,ty) if ty
          alias_type.strip! if alias_type
          if( proc_encode )
            if( enc )
              conv1 = proc_encode
              proc_encode = proc{|v| enc.call(conv1.call(v))}
            end
          else
            if( enc )
              proc_encode = enc
            end
          end
          if( proc_decode )
            if( dec )
              conv2 = proc_decode
              proc_decode = proc{|v| dec.call(conv2.call(v))}
            end
          else
            if( dec )
              proc_decode = dec
            end
          end
        end
      }
      return [alias_type, proc_encode, proc_decode]
    end
encode_return_type(ty)

[Source]

# File dl/lib/dl/types.rb, line 208
    def encode_return_type(ty)
      ty, enc, dec = encode_argument_type(ty)
      return [ty, enc, dec]
    end
encode_struct_type(alias_type)

[Source]

# File dl/lib/dl/types.rb, line 213
    def encode_struct_type(alias_type)
      proc_encode = nil
      proc_decode = nil
      @TYDEFS.each{|aty,_,_,_,ty,enc,dec|
        if( (aty.is_a?(Regexp) && (aty =~ alias_type)) || (aty == alias_type) )
          alias_type = alias_type.gsub(aty,ty) if ty
          alias_type.strip! if alias_type
          if( proc_encode )
            if( enc )
              conv1 = proc_encode
              proc_encode = proc{|v| enc.call(conv1.call(v))}
            end
          else
            if( enc )
              proc_encode = enc
            end
          end
          if( proc_decode )
            if( dec )
              conv2 = proc_decode
              proc_decode = proc{|v| dec.call(conv2.call(v))}
            end
          else
            if( dec )
              proc_decode = dec
            end
          end
        end
      }
      return [alias_type, proc_encode, proc_decode]
    end
init_types()

[Source]

# File dl/lib/dl/types.rb, line 172
    def init_types
      @TYDEFS = TYPES.dup
    end
typealias(ty1, ty2, enc=nil, dec=nil, ty3=nil, senc=nil, sdec=nil)

[Source]

# File dl/lib/dl/types.rb, line 168
    def typealias(ty1, ty2, enc=nil, dec=nil, ty3=nil, senc=nil, sdec=nil)
      @TYDEFS.unshift([ty1, ty2, enc, dec, ty3, senc, sdec])
    end


Class: IO

Class | IO
In: |

Methods

to_ptr

Public Instance methods

to_ptr()


Class: String

Class | String
In: |

Methods

to_ptr

Public Instance methods

to_ptr()


Class: Win32API

Class | Win32API
In: | dl/lib/dl/win32.rb
Parent: | Object

Methods

Call call new

Constants

DLL = {}

Public Class methods

new(dllname, func, import, export = "0")

[Source]

# File dl/lib/dl/win32.rb, line 8
  def initialize(dllname, func, import, export = "0")
    prototype = (export + import.to_s).tr("VPpNnLlIi", "0SSI")
    handle = DLL[dllname] ||= DL::Handle.new(dllname)
    @sym = handle.sym(func, prototype)
  end

Public Instance methods

Call(*args)

Alias for call

call(*args)

[Source]

# File dl/lib/dl/win32.rb, line 14
  def call(*args)
    import = @sym.proto.split("", 2)[1]
    args.each_with_index do |x, i|
      args[i] = nil if x == 0 and import[i] == ?S
      args[i], = [x].pack("I").unpack("i") if import[i] == ?I
    end
    ret, = @sym.call(*args)
    return ret || 0
  end


File: dl.c

dl.c

Path: | dl/dl.c
Last Update: | Sat Oct 15 23:43:50 AUS Eastern Standard Time 2005


File: handle.c

handle.c

Path: | dl/handle.c
Last Update: | Sat Oct 15 23:43:51 AUS Eastern Standard Time 2005


File: install.rb

install.rb

Path: | dl/install.rb
Last Update: | Tue Apr 02 20:56:13 AUS Eastern Standard Time 2002

Required files

mkmf ftools

Methods

find install

Constants

SO_LIBS = ["dl.so"]

Public Instance methods

find(dir, match = /./)

[Source]

# File dl/install.rb, line 13
def find(dir, match = /./)
  Dir.chdir(dir)
  files = []
  Dir.new(".").each{|file|
    if( file != "." && file != ".." )
      case File.ftype(file)
      when "file"
        if( file =~ match )
          files.push(File.join(dir,file))
        end
      when "directory"
        files += find(file, match).collect{|f| File.join(dir,f)}
      end
    end
  }
  Dir.chdir("..")
  return files
end
install()

[Source]

# File dl/install.rb, line 32
def install()
  rb_files = find(File.join(".","lib"), /.rb$/)

  SO_LIBS.each{|f|
    File.makedirs($rubylibdir, "#{$archdir}")
    File.install(f, File.join($archdir,f), 0555, true)
  }

  rb_files.each{|f|
    origfile = f
    instfile = File.join($rubylibdir, origfile.sub("./lib/",""))
    instdir  = File.dirname(instfile)
    File.makedirs(instdir)
    File.install(origfile, instfile, 0644, true)
  }
end


File: import.rb

import.rb

Path: | dl/lib/dl/import.rb
Last Update: | Sat Oct 15 23:43:52 AUS Eastern Standard Time 2005

-*- ruby -*-

Required files

dl dl/types


File: struct.rb

struct.rb

Path: | dl/lib/dl/struct.rb
Last Update: | Sat Oct 15 23:43:52 AUS Eastern Standard Time 2005

-*- ruby -*-

Required files

dl dl/import


File: types.rb

types.rb

Path: | dl/lib/dl/types.rb
Last Update: | Sat Oct 15 23:43:52 AUS Eastern Standard Time 2005

-*- ruby -*-

Required files

dl


File: win32.rb

win32.rb

Path: | dl/lib/dl/win32.rb
Last Update: | Mon Jan 20 20:22:04 AUS Eastern Daylight Time 2003

-*- ruby -*-

Required files

dl


File: mkcall.rb

mkcall.rb

Path: | dl/mkcall.rb
Last Update: | Fri Nov 08 02:42:07 AUS Eastern Daylight Time 2002

-*- ruby -*-

Required files

mkmf type dlconfig

Methods

output_arg output_args output_callfunc output_case rec_output

Public Instance methods

output_arg(x,i)

[Source]

# File dl/mkcall.rb, line 8
def output_arg(x,i)
  "args[#{i}].#{DLTYPE[x][:stmem]}"
end
output_args(types)

[Source]

# File dl/mkcall.rb, line 12
def output_args(types)
  t = []
  types[1..-1].each_with_index{|x,i| t.push(output_arg(x,i))}
  t.join(",")
end
output_callfunc(types)

[Source]

# File dl/mkcall.rb, line 18
def output_callfunc(types)
  t = types[0]
  stmem = DLTYPE[t][:stmem]
  ctypes = types2ctypes(types)
  if( t == VOID )
    callstm = "(*f)(#{output_args(types)})"
  else
    callstm = "ret.#{stmem} = (*f)(#{output_args(types)})"
  end
  [ "{",
    "#{ctypes[0]} (*f)(#{ctypes[1..-1].join(',')}) = func;",
    "#{callstm};",
    "}"].join(" ")
end
output_case(types)

[Source]

# File dl/mkcall.rb, line 33
def output_case(types)
  num = types2num(types)
  callfunc_stm = output_callfunc(types)
"  case \#{num}:\n#ifdef DEBUG\n    printf(\"\#{callfunc_stm}\\\\n\");\n#endif\n    \#{callfunc_stm};\n    break;\n"
end
rec_output(types = [VOID])

[Source]

# File dl/mkcall.rb, line 47
def rec_output(types = [VOID])
  print output_case(types)
  if( types.length <= MAX_ARG )
    DLTYPE.keys.sort.each{|t|
      if( t != VOID && DLTYPE[t][:sym] )
        rec_output(types + [t])
      end
    }
  end
end


File: mkcallback.rb

mkcallback.rb

Path: | dl/mkcallback.rb
Last Update: | Sat Oct 15 23:43:51 AUS Eastern Standard Time 2005

-*- ruby -*-

Required files

mkmf type dlconfig

Methods

mkfunc

Public Instance methods

mkfunc(rettype, fnum, argc)

[Source]

# File dl/mkcallback.rb, line 8
def mkfunc(rettype, fnum, argc)
  args = (0..(argc-1)).collect{|i| "long arg#{i}"}.join(", ")

  subst_code = (0..(argc-1)).collect{|i|
    "  buff[#{i.to_s}] = arg#{i.to_s};"
  }.join("\n")

  ret_code =
    if( DLTYPE[rettype][:c2rb] )
      "  return #{DLTYPE[rettype][:rb2c]['retval']};"
    else
      "  /* no return value */"
    end

  code = [
    "static #{DLTYPE[rettype][:ctype]}",
    "rb_dl_callback_func_#{rettype.to_s}_#{fnum.to_s}(#{args})",
    "{",
    "  VALUE retval, proto, proc, obj;",
    "  VALUE argv[#{argc.to_s}];",
    "  int  argc;",
    "  long buff[#{argc.to_s}];",
    "",
    subst_code,
    "",
    "  obj = rb_hash_aref(DLFuncTable, rb_assoc_new(INT2NUM(#{rettype.to_s}),INT2NUM(#{fnum.to_s})));",
    "  proto = rb_ary_entry(obj, 0);",
    "  proc  = rb_ary_entry(obj, 1);",
    "  Check_Type(proto, T_STRING);",
    "  if( RSTRING(proto)->len >= #{argc.to_s} )",
    "    rb_raise(rb_eArgError, \"too many arguments\");",
    "  rb_dl_scan_callback_args(buff, RSTRING(proto)->ptr, &argc, argv);",
    "  retval = rb_funcall2(proc, id_call, argc, argv);",
    "",
    ret_code,
    "}",
  ].join("\n")

  return code
end


File: mkcbtable.rb

mkcbtable.rb

Path: | dl/mkcbtable.rb
Last Update: | Mon Jun 10 03:47:33 AUS Eastern Standard Time 2002

-*- ruby -*-

Required files

mkmf type dlconfig

Methods

mktable

Public Instance methods

mktable(rettype, fnum, argc)

[Source]

# File dl/mkcbtable.rb, line 8
def mktable(rettype, fnum, argc)
  code =
    "rb_dl_callback_table[#{rettype}][#{fnum}] = &rb_dl_callback_func_#{rettype.to_s}_#{fnum};"
  return code
end


File: ptr.c

ptr.c

Path: | dl/ptr.c
Last Update: | Thu Oct 23 00:29:20 AUS Eastern Standard Time 2003


File: sym.c

sym.c

Path: | dl/sym.c
Last Update: | Thu Jun 16 09:39:27 AUS Eastern Standard Time 2005


File: type.rb

type.rb

Path: | dl/type.rb
Last Update: | Tue Apr 02 20:56:13 AUS Eastern Standard Time 2002

example:

 DLTYPE[INT][:rb2c]["arg0"] => "NUM2INT(arg0)"
 DLTYPE[DOUBLE][:c2rb]["r"] => "rb_float_new(r)"

Methods

num2types tget tpush types2ctypes types2num

Constants

DLTYPE = { VOID = 0x00 => { :name => 'VOID', :rb2c => nil, :c2rb => nil, :ctype => "void", :stmem => "v", :sym => true, :cb => true, }, CHAR = 0x01 => { :name => 'CHAR', :rb2c => proc{|x| "NUM2CHR(#{x})"}, :c2rb => proc{|x| "CHR2FIX(#{x})"}, :ctype => "char", :stmem => "c", :sym => false, :cb => false, }, SHORT = 0x02 => { :name => 'SHORT', :rb2c => proc{|x| "FIX2INT(#{x})"}, :c2rb => proc{|x| "INT2FIX(#{x})"}, :ctype => "short", :stmem => "h", :sym => false, :cb => false, }, INT = 0x03 => { :name => 'INT', :rb2c => proc{|x| "NUM2INT(#{x})"}, :c2rb => proc{|x| "INT2NUM(#{x})"}, :ctype => "int", :stmem => "i", :sym => true, :cb => false, }, LONG = 0x04 => { :name => 'LONG', :rb2c => proc{|x| "NUM2INT(#{x})"}, :c2rb => proc{|x| "INT2NUM(#{x})"}, :ctype => "long", :stmem => "l", :sym => true, :cb => true, }, FLOAT = 0x05 => { :name => 'FLOAT', :rb2c => proc{|x| "(float)(RFLOAT(#{x})->value)"}, :c2rb => proc{|x| "rb_float_new((double)#{x})"}, :ctype => "float", :stmem => "f", :sym => false, :cb => false, }, DOUBLE = 0x06 => { :name => 'DOUBLE', :rb2c => proc{|x| "RFLOAT(#{x})->value"}, :c2rb => proc{|x| "rb_float_new(#{x})"}, :ctype => "double", :stmem => "d", :sym => true, :cb => true, }, VOIDP = 0x07 => { :name => 'VOIDP', :rb2c => proc{|x| "rb_dlptr2cptr(#{x})"}, :c2rb => proc{|x| "rb_dlptr_new(#{x},sizeof(void*),0)"}, :ctype => "void *", :stmem => "p", :sym => true, :cb => true, }, } example:
 DLTYPE[INT][:rb2c]["arg0"] => "NUM2INT(arg0)"
 DLTYPE[DOUBLE][:c2rb]["r"] => "rb_float_new(r)"

Public Instance methods

num2types(num)

[Source]

# File dl/type.rb, line 97
def num2types(num)
  ts = []
  i  = 0
  t = tget(num,i)
  while( (t != VOID && i > 0) || (i == 0) )
    ts.push(DLTYPE[t][:ctype])
    i += 1
    t = tget(num,i)
  end
  ts
end
tget(t, i)

[Source]

# File dl/type.rb, line 84
def tget(t, i)
  (t & (0x07 << (i * 3))) >> (i * 3)
end
tpush(t, x)

[Source]

# File dl/type.rb, line 80
def tpush(t, x)
  (t << 3)|x
end
types2ctypes(types)

[Source]

# File dl/type.rb, line 109
def types2ctypes(types)
  res = []
  types.each{|t|
    res.push(DLTYPE[t][:ctype])
  }
  res
end
types2num(types)

[Source]

# File dl/type.rb, line 88
def types2num(types)
  res = 0x00
  r = types.reverse
  r.each{|t|
    res = tpush(res,t)
  }
  res
end


Module: DRb

Module | DRb
In: | drb/unix.rb drb/timeridconv.rb drb/ssl.rb drb/observer.rb drb/invokemethod.rb drb/gw.rb drb/extservm.rb drb/extserv.rb drb/eq.rb drb/drb.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.

[Source]

# File drb/drb.rb, line 1680
  def config
    current_server.config
  rescue
    DRbServer.make_config
  end
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.

[Source]

# File drb/drb.rb, line 1644
  def current_server
    drb = Thread.current['DRb']
    server = (drb && drb['server']) ? drb['server'] : @primary_server
    raise DRbServerNotFound unless server
    return server
  end
fetch_server(uri)

[Source]

# File drb/drb.rb, line 1752
  def fetch_server(uri)
    @server[uri]
  end
front()

Get the front object of the current server.

This raises a DRbServerNotFound error if there is no current server. See current_server.

[Source]

# File drb/drb.rb, line 1691
  def front
    current_server.front
  end
here?(uri)

Is uri the URI for the current local server?

[Source]

# File drb/drb.rb, line 1671
  def here?(uri)
    (current_server.uri rescue nil) == uri
  end
install_acl(acl)

Set the default acl.

See DRb::DRbServer.default_acl.

[Source]

# File drb/drb.rb, line 1733
  def install_acl(acl)
    DRbServer.default_acl(acl)
  end
install_id_conv(idconv)

Set the default id conv object.

See DRbServer#default_id_conv.

[Source]

# File drb/drb.rb, line 1725
  def install_id_conv(idconv)
    DRbServer.default_id_conv(idconv)
  end
regist_server(server)

[Source]

# File drb/drb.rb, line 1739
  def regist_server(server)
    @server[server.uri] = server
    Thread.exclusive do
      @primary_server = server unless @primary_server
    end
  end
remove_server(server)

[Source]

# File drb/drb.rb, line 1747
  def remove_server(server)
    @server.delete(server.uri)
  end
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.

[Source]

# File drb/drb.rb, line 1623
  def start_service(uri=nil, front=nil, config=nil)
    @primary_server = DRbServer.new(uri, front, config)
  end
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.

[Source]

# File drb/drb.rb, line 1656
  def stop_service
    @primary_server.stop_service if @primary_server
    @primary_server = nil
  end
thread()

Get the thread of the primary server.

This returns nil if there is no primary server. See primary_server.

[Source]

# File drb/drb.rb, line 1717
  def thread
    @primary_server ? @primary_server.thread : nil
  end
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.

[Source]

# File drb/drb.rb, line 1708
  def to_id(obj)
    current_server.to_id(obj)
  end
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.

[Source]

# File drb/drb.rb, line 1700
  def to_obj(ref)
    current_server.to_obj(ref)
  end
uri()

Get the URI defining the local dRuby space.

This is the URI of the current server. See current_server.

[Source]

# File drb/drb.rb, line 1665
  def uri
    current_server.uri
  end


Class: ACL

Class | ACL
In: | 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)

[Source]

# File drb/acl.rb, line 82
  def initialize(list=nil, order = DENY_ALLOW)
    @order = order
    @deny = ACLList.new
    @allow = ACLList.new
    install_list(list) if list
  end

Public Instance methods

allow_addr?(addr)

[Source]

# File drb/acl.rb, line 95
  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
allow_socket?(soc)

[Source]

# File drb/acl.rb, line 90
  def allow_socket?(soc)
    allow_addr?(soc.peeraddr)
  end
install_list(list)

[Source]

# File drb/acl.rb, line 111
  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


Class: ACL::ACLEntry

Class | ACL::ACLEntry
In: | drb/acl.rb
Parent: | Object

Methods

match new

Public Class methods

new(str)

[Source]

# File drb/acl.rb, line 13
    def initialize(str)
      if str == '*' or str == 'all'
        @pat = [:all]
      else
        begin
          @pat = [:ip, IPAddr.new(str)]
        rescue ArgumentError
          @pat = [:name, dot_pat(str)]
        end
      end
    end

Public Instance methods

match(addr)

[Source]

# File drb/acl.rb, line 40
    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


Class: ACL::ACLList

Class | ACL::ACLList
In: | drb/acl.rb
Parent: | Object

Methods

add match new

Public Class methods

new()

[Source]

# File drb/acl.rb, line 61
    def initialize
      @list = []
    end

Public Instance methods

add(str)

[Source]

# File drb/acl.rb, line 74
    def add(str)
      @list.push(ACLEntry.new(str))
    end
match(addr)

[Source]

# File drb/acl.rb, line 66
    def match(addr)
      @list.each do |e|
        return true if e.match(addr)
      end
      false
    end


Class: DRb::DRbArray

Class | DRb::DRbArray
In: | drb/drb.rb
Parent: | Object

Methods

_dump _load new

Public Class methods

_load(s)

[Source]

# File drb/drb.rb, line 527
    def self._load(s)
      Marshal::load(s)
    end
new(ary)

[Source]

# File drb/drb.rb, line 512
    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

Public Instance methods

_dump(lv)

[Source]

# File drb/drb.rb, line 531
    def _dump(lv)
      Marshal.dump(@ary)
    end


Class: DRb::DRbBadScheme

Class | DRb::DRbBadScheme
In: | 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: | 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: | 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: | drb/drb.rb
Parent: | DRbError

Error raised when an error occurs on the underlying communication protocol.


Class: DRb::DRbError

Class | DRb::DRbError
In: | drb/drb.rb
Parent: | RuntimeError

Superclass of all errors raised in the DRb module.


Class: DRb::DRbIdConv

Class | DRb::DRbIdConv
In: | 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.

[Source]

# File drb/drb.rb, line 382
    def to_id(obj)
      obj.nil? ? nil : obj.__id__
    end
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.

[Source]

# File drb/drb.rb, line 374
    def to_obj(ref)
      ObjectSpace._id2ref(ref)
    end


Class: DRb::DRbMessage

Class | DRb::DRbMessage
In: | 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: | drb/gw.rb drb/eq.rb 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)

[Source]

# File 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
_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.

[Source]

# File drb/drb.rb, line 998
    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(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.

[Source]

# File drb/drb.rb, line 1036
    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
new_with(uri, ref)

[Source]

# File drb/drb.rb, line 1012
    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(uri)

Create a new DRbObject from a URI alone.

[Source]

# File drb/drb.rb, line 1020
    def self.new_with_uri(uri)
      self.new(nil, uri)
    end
prepare_backtrace(uri, result)

[Source]

# File drb/drb.rb, line 1109
    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
with_friend(uri) {|| ...}

[Source]

# File drb/drb.rb, line 1098
    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

Public Instance methods

==(other)

[Source]

# File drb/eq.rb, line 5
    def ==(other)
      return false unless DRbObject === other
     (@ref == other.__drbref) && (@uri == other.__drburi)
    end
__drbref()

Get the reference of the object, if local.

[Source]

# File drb/drb.rb, line 1055
    def __drbref
      @ref
    end
__drburi()

Get the URI of the remote object.

[Source]

# File drb/drb.rb, line 1050
    def __drburi
      @uri
    end
_dump(lv)

[Source]

# File 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
_dump(lv)

Marshall this object.

The URI and ref of the object are marshalled.

[Source]

# File drb/drb.rb, line 1027
    def _dump(lv)
      Marshal.dump([@uri, @ref])
    end
eql?(other)

Alias for #==

hash()

[Source]

# File drb/eq.rb, line 10
    def hash
      [@uri, @ref].hash
    end
method_missing(msg_id, *a, &b)

Routes method calls to the referenced object.

[Source]

# File drb/drb.rb, line 1074
    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
respond_to?(msg_id, priv=false)

[Source]

# File drb/drb.rb, line 1062
    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


Module: DRb::DRbObservable

Module | DRb::DRbObservable
In: | drb/observer.rb

Methods

notify_observers

Included Modules

Observable

Public Instance methods

notify_observers(*arg)

[Source]

# File 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


Module: DRb::DRbProtocol

Module | DRb::DRbProtocol
In: | 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.

[Source]

# File drb/drb.rb, line 713
    def add_protocol(prot)
      @protocol.push(prot)
    end
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.

[Source]

# File drb/drb.rb, line 725
    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(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.

[Source]

# File drb/drb.rb, line 753
    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(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.

[Source]

# File drb/drb.rb, line 774
    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


Class: DRb::DRbRemoteError

Class | DRb::DRbRemoteError
In: | drb/drb.rb
Parent: | DRbError

Methods

new

Attributes

reason [R]

Public Class methods

new(error)

[Source]

# File drb/drb.rb, line 434
    def initialize(error)
      @reason = error.class.to_s
      super("#{error.message} (#{error.class})")
      set_backtrace(error.backtrace)
    end


Class: DRb::DRbSSLSocket

Class | DRb::DRbSSLSocket
In: | 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)

[Source]

# File drb/ssl.rb, line 158
    def initialize(uri, soc, config, is_established)
      @ssl = is_established ? soc : nil
      super(uri, soc.to_io, config)
    end
open(uri, config)

[Source]

# File 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(uri, config)

[Source]

# File 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
parse_uri(uri)

[Source]

# File 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
uri_option(uri, config)

[Source]

# File drb/ssl.rb, line 153
    def self.uri_option(uri, config)
      host, port, option = parse_uri(uri)
      return "drbssl://#{host}:#{port}", option
    end

Public Instance methods

accept()

[Source]

# File 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 verbose
        retry
      end
    end
close()

[Source]

# File drb/ssl.rb, line 165
    def close
      if @ssl
        @ssl.close
        @ssl = nil
      end
      super
    end
stream()

[Source]

# File drb/ssl.rb, line 163
    def stream; @ssl; end


Class: DRb::DRbSSLSocket::SSLConfig

Class | DRb::DRbSSLSocket::SSLConfig
In: | 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)

[Source]

# File drb/ssl.rb, line 27
      def initialize(config)
        @config  = config
        @cert    = config[:SSLCertificate]
        @pkey    = config[:SSLPrivateKey]
        @ssl_ctx = nil
      end

Public Instance methods

[](key)

[Source]

# File drb/ssl.rb, line 34
      def [](key);
        @config[key] || DEFAULT[key]
      end
accept(tcp)

[Source]

# File drb/ssl.rb, line 45
      def accept(tcp)
        ssl = OpenSSL::SSL::SSLSocket.new(tcp, @ssl_ctx)
        ssl.sync = true
        ssl.accept
        ssl
      end
connect(tcp)

[Source]

# File drb/ssl.rb, line 38
      def connect(tcp)
        ssl = ::OpenSSL::SSL::SSLSocket.new(tcp, @ssl_ctx)
        ssl.sync = true
        ssl.connect
        ssl
      end
setup_certificate()

[Source]

# File 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()

[Source]

# File 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


Class: DRb::DRbServer

Class | DRb::DRbServer
In: | drb/invokemethod.rb 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.

[Source]

# File drb/drb.rb, line 1242
    def self.default_acl(acl)
      @@acl = acl
    end
default_argc_limit(argc)

Set the default value for the :argc_limit option.

See new(). The initial default value is 256.

[Source]

# File drb/drb.rb, line 1228
    def self.default_argc_limit(argc)
      @@argc_limit = argc
    end
default_id_conv(idconv)

Set the default value for the :id_conv option.

See new(). The initial default value is a DRbIdConv instance.

[Source]

# File drb/drb.rb, line 1249
    def self.default_id_conv(idconv)
      @@idconv = idconv
    end
default_load_limit(sz)

Set the default value for the :load_limit option.

See new(). The initial default value is 25 MB.

[Source]

# File drb/drb.rb, line 1235
    def self.default_load_limit(sz)
      @@load_limit = sz
    end
default_safe_level(level)

[Source]

# File drb/drb.rb, line 1253
    def self.default_safe_level(level)
      @@safe_level = level
    end
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.

[Source]

# File drb/drb.rb, line 1324
    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()

Get the default value of the :verbose option.

[Source]

# File drb/drb.rb, line 1265
    def self.verbose
      @@verbose
    end
verbose=(on)

Set the default value of the :verbose option.

See new(). The initial default value is false.

[Source]

# File drb/drb.rb, line 1260
    def self.verbose=(on)
      @@verbose = on
    end

Public Instance methods

alive?()

Is this server alive?

[Source]

# File drb/drb.rb, line 1381
    def alive?
      @thread.alive?
    end
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.

[Source]

# File drb/drb.rb, line 1464
    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
stop_service()

Stop this server.

[Source]

# File drb/drb.rb, line 1386
    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_id(obj)

Convert a local object to a dRuby reference.

[Source]

# File drb/drb.rb, line 1403
    def to_id(obj)
      return nil if obj.__id__ == front.__id__
      @idconv.to_id(obj)
    end
to_obj(ref)

Convert a dRuby reference to the local object it refers to.

[Source]

# File drb/drb.rb, line 1396
    def to_obj(ref)
      return front if ref.nil?
      return front[ref.to_s] if DRbURIOption === ref
      @idconv.to_obj(ref)
    end
verbose()

Get whether the server is in verbose mode.

In verbose mode, failed calls are logged to stdout.

[Source]

# File drb/drb.rb, line 1378
    def verbose; @config[:verbose]; end
verbose=(v)

Set whether to operate in verbose mode.

In verbose mode, failed calls are logged to stdout.

[Source]

# File drb/drb.rb, line 1373
    def verbose=(v); @config[:verbose]=v; end


Module: DRb::DRbServer::InvokeMethod18Mixin

Module | DRb::DRbServer::InvokeMethod18Mixin
In: | drb/invokemethod.rb

Methods

block_yield perform_with_block

Public Instance methods

block_yield(x)

[Source]

# File 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()

[Source]

# File 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


Class: DRb::DRbServerNotFound

Class | DRb::DRbServerNotFound
In: | 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: | 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()

[Source]

# File drb/drb.rb, line 827
    def self.getservername
      host = Socket::gethostname
      begin
        Socket::gethostbyname(host)[0]
      rescue
        host
      end
    end
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.

[Source]

# File drb/drb.rb, line 880
    def initialize(uri, soc, config={})
      @uri = uri
      @socket = soc
      @config = config
      @acl = config[:tcp_acl]
      @msg = DRbMessage.new(config)
      set_sockopt(@socket)
    end
open(uri, config)

Open a client connection to uri using configuration config.

[Source]

# File drb/drb.rb, line 819
    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
open_server(uri, config)

Open a server listening for connections at uri using configuration config.

[Source]

# File drb/drb.rb, line 855
    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
open_server_inaddr_any(host, port)

[Source]

# File drb/drb.rb, line 836
    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
uri_option(uri, config)

Parse uri into a [uri, option] pair.

[Source]

# File drb/drb.rb, line 870
    def self.uri_option(uri, config)
      host, port, option = parse_uri(uri)
      return "druby://#{host}:#{port}", option
    end

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.

[Source]

# File drb/drb.rb, line 939
    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?()

Check to see if this connection is alive.

[Source]

# File drb/drb.rb, line 949
    def alive?
      return false unless @socket
      if IO.select([@socket], nil, nil, 0)
        close
        return false
      end
      true
    end
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.

[Source]

# File drb/drb.rb, line 929
    def close
      if @socket
        @socket.close
        @socket = nil
      end
    end
peeraddr()

Get the address of our TCP peer (the other end of the socket we are bound to.

[Source]

# File drb/drb.rb, line 894
    def peeraddr
      @socket.peeraddr
    end
recv_reply()

On the client side, receive a reply from the server.

[Source]

# File drb/drb.rb, line 917
    def recv_reply
      @msg.recv_reply(stream)
    end
recv_request()

On the server side, receive a request from the client.

[Source]

# File drb/drb.rb, line 907
    def recv_request
      @msg.recv_request(stream)
    end
send_reply(succ, result)

On the server side, send a reply to the client.

[Source]

# File drb/drb.rb, line 912
    def send_reply(succ, result)
      @msg.send_reply(stream, succ, result)
    end
send_request(ref, msg_id, arg, b)

On the client side, send a request to the server.

[Source]

# File drb/drb.rb, line 902
    def send_request(ref, msg_id, arg, b)
      @msg.send_request(stream, ref, msg_id, arg, b)
    end
stream()

Get the socket.

[Source]

# File drb/drb.rb, line 899
    def stream; @socket; end


Class: DRb::DRbUNIXSocket

Class | DRb::DRbUNIXSocket
In: | 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)

[Source]

# File 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
open(uri, config)

[Source]

# File 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(uri, config)

[Source]

# File 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
parse_uri(uri)

[Source]

# File 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
uri_option(uri, config)

[Source]

# File drb/unix.rb, line 51
    def self.uri_option(uri, config)
      filename, option = parse_uri(uri)
      return "drbunix:#{filename}", option
    end

Public Instance methods

accept()

[Source]

# File drb/unix.rb, line 97
    def accept
      s = @socket.accept
      self.class.new(nil, s, @config)
    end
close()

[Source]

# File drb/unix.rb, line 89
    def close
      return unless @socket
      path = @socket.path
      @socket.close
      File.unlink(path) if @server_mode
      @socket = nil
    end
set_sockopt(soc)

[Source]

# File drb/unix.rb, line 102
    def set_sockopt(soc)
      soc.fcntl(Fcntl::F_SETFL, Fcntl::FD_CLOEXEC) if defined? Fcntl::FD_CLOEXEC
    end


Module: DRb::DRbUndumped

Module | DRb::DRbUndumped
In: | 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: | 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.

[Source]

# File drb/drb.rb, line 463
    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

Public Instance methods

exception()

Create a DRbUnknownError exception containing this object.

[Source]

# File drb/drb.rb, line 506
    def exception
      DRbUnknownError.new(self)
    end
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.

[Source]

# File drb/drb.rb, line 501
    def reload
      self.class._load(@buf)
    end


Class: DRb::DRbUnknownError

Class | DRb::DRbUnknownError
In: | 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

[Source]

# File drb/drb.rb, line 416
    def initialize(unknown)
      @unknown = unknown
      super(unknown.name)
    end


Class: DRb::ExtServ

Class | DRb::ExtServ
In: | 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)

[Source]

# File 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

Public Instance methods

alive?()

[Source]

# File drb/extserv.rb, line 32
    def alive?
      @server ? @server.alive? : false
    end
front()

[Source]

# File drb/extserv.rb, line 20
    def front
      DRbObject.new(nil, @server.uri)
    end
stop_service()

[Source]

# File drb/extserv.rb, line 24
    def stop_service
      @invoker.unregist(@name)
      server = @server
      @server = nil
      server.stop_service
      true
    end


Class: DRb::ExtServManager

Class | DRb::ExtServManager
In: | drb/extservm.rb
Parent: | Object

Methods

command command= new regist service unregist

Included Modules

DRbUndumped

Attributes

uri [RW]

Public Class methods

command()

[Source]

# File drb/extservm.rb, line 15
    def self.command
      @@command
    end
command=(cmd)

[Source]

# File drb/extservm.rb, line 19
    def self.command=(cmd)
      @@command = cmd
    end
new()

[Source]

# File drb/extservm.rb, line 23
    def initialize
      @servers = {}
      @waiting = []
      @queue = Queue.new
      @thread = invoke_thread
      @uri = nil
    end

Public Instance methods

regist(name, ro)

[Source]

# File 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
service(name)

[Source]

# File 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
unregist(name)

[Source]

# File drb/extservm.rb, line 59
    def unregist(name)
      Thread.exclusive do
        @servers.delete(name)
      end
    end


Class: DRb::GW

Class | DRb::GW
In: | drb/gw.rb
Parent: | Object

Methods

[] []= new

Included Modules

MonitorMixin

Public Class methods

new()

[Source]

# File drb/gw.rb, line 16
    def initialize
      super()
      @hash = {}
    end

Public Instance methods

[](key)

[Source]

# File drb/gw.rb, line 21
    def [](key)
      synchronize do
        @hash[key]
      end
    end
[]=(key, v)

[Source]

# File drb/gw.rb, line 27
    def []=(key, v)
      synchronize do
        @hash[key] = v
      end
    end


Class: DRb::GWIdConv

Class | DRb::GWIdConv
In: | drb/gw.rb
Parent: | DRbIdConv

Methods

to_obj

Public Instance methods

to_obj(ref)

[Source]

# File 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


Class: DRb::TimerIdConv

Class | DRb::TimerIdConv
In: | drb/timeridconv.rb
Parent: | DRbIdConv

Methods

new to_id to_obj

Classes and Modules

Class DRb::TimerIdConv::TimerHolder2

Public Class methods

new(timeout=600)

[Source]

# File drb/timeridconv.rb, line 74
    def initialize(timeout=600)
      @holder = TimerHolder2.new(timeout)
    end

Public Instance methods

to_id(obj)

[Source]

# File drb/timeridconv.rb, line 85
    def to_id(obj)
      return @holder.add(obj)
    end
to_obj(ref)

[Source]

# File drb/timeridconv.rb, line 78
    def to_obj(ref)
      return super if ref.nil?
      @holder.fetch(ref)
    rescue TimerHolder2::InvalidIndexError
      raise "invalid reference"
    end


Class: DRb::TimerIdConv::TimerHolder2

Class | DRb::TimerIdConv::TimerHolder2
In: | 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)

[Source]

# File drb/timeridconv.rb, line 11
      def initialize(timeout=600)
        super()
        @sentinel = Object.new
        @gc = {}
        @curr = {}
        @renew = {}
        @timeout = timeout
        @keeper = keeper
      end

Public Instance methods

add(obj)

[Source]

# File drb/timeridconv.rb, line 21
      def add(obj)
        synchronize do
          key = obj.__id__
          @curr[key] = obj
          return key
        end
      end
fetch(key, dv=@sentinel)

[Source]

# File 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?(key)

[Source]

# File drb/timeridconv.rb, line 41
      def include?(key)
        synchronize do
          obj = peek(key)
          return false if obj == @sentinel
          true
        end
      end
peek(key)

[Source]

# File drb/timeridconv.rb, line 49
      def peek(key)
        synchronize do
          return @curr.fetch(key, @renew.fetch(key, @gc.fetch(key, @sentinel)))
        end
      end


Class: DRb::TimerIdConv::TimerHolder2::InvalidIndexError

Class | DRb::TimerIdConv::TimerHolder2::InvalidIndexError
In: | drb/timeridconv.rb
Parent: | RuntimeError


Class: Foo

Class | Foo
In: | drb/extserv.rb
Parent: | Object

Methods

hello new to_s

Included Modules

DRbUndumped

Public Class methods

new(str)

[Source]

# File drb/extserv.rb, line 42
    def initialize(str)
      @str = str
    end

Public Instance methods

hello(it)

[Source]

# File drb/extserv.rb, line 46
    def hello(it)
      "#{it}: #{self}"
    end
to_s()

[Source]

# File drb/extserv.rb, line 50
    def to_s
      @str
    end


File: drb.rb

drb.rb

Path: | drb.rb
Last Update: | Thu Jun 19 01:42:57 AUS Eastern Standard Time 2003

Required files

drb/drb


File: acl.rb

acl.rb

Path: | drb/acl.rb
Last Update: | Sun Oct 05 03:08:23 AUS Eastern Standard Time 2003

acl-2.0 - simple Access Control List

Copyright © 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: | drb/drb.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

drb/drb.rb

Distributed Ruby: dRuby version 2.0.4

Copyright © 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: | drb/eq.rb
Last Update: | Thu Jun 19 01:43:10 AUS Eastern Standard Time 2003

Required files

drb/drb


File: extserv.rb

extserv.rb

Path: | drb/extserv.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

Required files

drb/drb


File: extservm.rb

extservm.rb

Path: | drb/extservm.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

Required files

drb/drb thread


File: gw.rb

gw.rb

Path: | drb/gw.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

Required files

drb/drb monitor


File: invokemethod.rb

invokemethod.rb

Path: | drb/invokemethod.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

for ruby-1.8.0


File: observer.rb

observer.rb

Path: | drb/observer.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

Required files

observer


File: ssl.rb

ssl.rb

Path: | drb/ssl.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

Required files

socket openssl drb/drb singleton


File: timeridconv.rb

timeridconv.rb

Path: | drb/timeridconv.rb
Last Update: | Thu Jun 19 01:43:10 AUS Eastern Standard Time 2003

Required files

drb/drb monitor


File: unix.rb

unix.rb

Path: | drb/unix.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

Required files

socket drb/drb tmpdir etc


File: English.rb

English.rb

Path: | English.rb
Last Update: | Sat Oct 15 23:44:27 AUS Eastern Standard Time 2005

Include the English library file in a Ruby script, and you can reference the global variables such as \VAR{\$_} using less cryptic names, listed in the following table.% \vref{tab:english}.

Without ‘English’:

    $\ = ' -- '
    "waterbuffalo" =~ /buff/
    print $", $', $$, "\n"

With English:

    require "English"

    $OUTPUT_FIELD_SEPARATOR = ' -- '
    "waterbuffalo" =~ /buff/
    print $LOADED_FEATURES, $POSTMATCH, $PID, "\n"

External Aliases

$! | -> | $ERROR_INFO
 | The exception object passed to raise.
$@ | -> | $ERROR_POSITION
 | The stack backtrace generated by the last exception. See Kernel.caller for details. Thread local.
$; | -> | $FS
 | The default separator pattern used by String.split. May be set from the command line using the -F flag.
$; | -> | $FIELD_SEPARATOR
 | The default separator pattern used by String.split. May be set from the command line using the -F flag.
$, | -> | $OFS
 | The separator string output between the parameters to methods such as Kernel.print and Array.join. Defaults to nil, which adds no text.
$, | -> | $OUTPUT_FIELD_SEPARATOR
 | The separator string output between the parameters to methods such as Kernel.print and Array.join. Defaults to nil, which adds no text.
$/ | -> | $RS
 | The input record separator (newline by default). This is the value that routines such as Kernel.gets use to determine record boundaries. If set to nil, gets will read the entire file.
$/ | -> | $INPUT_RECORD_SEPARATOR
 | The input record separator (newline by default). This is the value that routines such as Kernel.gets use to determine record boundaries. If set to nil, gets will read the entire file.
$\ | -> | $ORS
 | The string appended to the output of every call to methods such as Kernel.print and IO.write. The default value is nil.
$\ | -> | $OUTPUT_RECORD_SEPARATOR
 | The string appended to the output of every call to methods such as Kernel.print and IO.write. The default value is nil.
$. | -> | $INPUT_LINE_NUMBER
 | The number of the last line read from the current input file.
$. | -> | $NR
 | The number of the last line read from the current input file.
$_ | -> | $LAST_READ_LINE
 | The last line read by Kernel.gets or Kernel.readline. Many string-related functions in the Kernel module operate on $_ by default. The variable is local to the current scope. Thread local.
$> | -> | $DEFAULT_OUTPUT
 | The destination of output for Kernel.print and Kernel.printf. The default value is $stdout.
$< | -> | $DEFAULT_INPUT
 | An object that provides access to the concatenation of the contents of all the files given as command-line arguments, or $stdin (in the case where there are no arguments). $< supports methods similar to a File object: inmode, close, closed?, each, each_byte, each_line, eof, eof?, file, filename, fileno, getc, gets, lineno, lineno=, path, pos, pos=, read, readchar, readline, readlines, rewind, seek, skip, tell, to_a, to_i, to_io, to_s, along with the methods in Enumerable. The method file returns a File object for the file currently being read. This may change as $< reads through the files on the command line. Read only.
$$ | -> | $PID
 | The process number of the program being executed. Read only.
$$ | -> | $PROCESS_ID
 | The process number of the program being executed. Read only.
$? | -> | $CHILD_STATUS
 | The exit status of the last child process to terminate. Read only. Thread local.
$~ | -> | $LAST_MATCH_INFO
 | A MatchData object that encapsulates the results of a successful pattern match. The variables $&, $`, $’, and $1 to $9 are all derived from $~. Assigning to $~ changes the values of these derived variables. This variable is local to the current scope. Thread local.
$= | -> | $IGNORECASE
 | If set to any value apart from nil or false, all pattern matches will be case insensitive, string comparisons will ignore case, and string hash values will be case insensitive. Deprecated
$* | -> | $ARGV
 | An array of strings containing the command-line options from the invocation of the program. Options used by the Ruby interpreter will have been removed. Read only. Also known simply as ARGV.
$& | -> | $MATCH
 | The string matched by the last successful pattern match. This variable is local to the current scope. Read only. Thread local.
$` | -> | $PREMATCH
 | The string preceding the match in the last successful pattern match. This variable is local to the current scope. Read only. Thread local.
$' | -> | $POSTMATCH
 | The string following the match in the last successful pattern match. This variable is local to the current scope. Read only. Thread local.
$+ | -> | $LAST_PAREN_MATCH
 | The contents of the highest-numbered group matched in the last successful pattern match. Thus, in "cat" =~ /(c|a)(t|z)/, $+ will be set to "t". This variable is local to the current scope. Read only. Thread local.


Module: Enumerable

Module | Enumerable
In: |

Methods

each_cons each_slice enum_cons enum_slice enum_with_index

Public Instance methods

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]

[Source]

/*
 *  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;
}
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]

[Source]

/*
 *  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;
}
e.enum_cons(n)

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

[Source]

/*
 *  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);
}
e.enum_slice(n)

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

[Source]

/*
 *  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);
}
enum_with_index

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

[Source]

/*
 *  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);
}


Class: Object

Class | Object
In: |

Methods

enum_for to_enum

Public Instance methods

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)

[Source]

/*
 *  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);
}
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)

[Source]

/*
 *  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);
}


File: enumerator.c

enumerator.c

Path: | enumerator/enumerator.c
Last Update: | Mon Oct 24 20:16:27 AUS Eastern Standard Time 2005


Class: ERB

Class | ERB
In: | 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: 2005/02/12 16:30:58 $'

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.

[Source]

# File erb.rb, line 686
  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
version()

Returns revision information for the erb.rb module.

[Source]

# File erb.rb, line 242
  def self.version
    "erb.rb [2.0.4 #{ERB::Revision.split[1]}]"
  end

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.

[Source]

# File erb.rb, line 733
  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
run(b=TOPLEVEL_BINDING)

Generate results and print them. (see ERB#result)

[Source]

# File erb.rb, line 721
  def run(b=TOPLEVEL_BINDING)
    print self.result(b)
  end
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.

[Source]

# File erb.rb, line 706
  def set_eoutvar(compiler, eoutvar = '_erbout')
    compiler.put_cmd = "#{eoutvar}.concat"

    cmd = []
    cmd.push "#{eoutvar} = ''"

    compiler.pre_cmd = cmd

    cmd = []
    cmd.push(eoutvar)

    compiler.post_cmd = cmd
  end


Module: ERB::Util

Module | ERB::Util
In: | 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?

[Source]

# File erb.rb, line 780
    def html_escape(s)
      s.to_s.gsub(/&/, "&amp;").gsub(/\"/, "&quot;").gsub(/>/, "&gt;").gsub(/</, "&lt;")
    end
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

[Source]

# File erb.rb, line 799
    def url_encode(s)
      s.to_s.gsub(/[^a-zA-Z0-9_\-.]/n){ sprintf("%%%02X", $&.unpack("C")[0]) }
    end


File: erb.rb

erb.rb

Path: | erb.rb
Last Update: | Sat Oct 15 23:44:27 AUS Eastern Standard Time 2005

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 © 1999-2000,2002,2003 Masatoshi SEKI

You can redistribute it and/or modify it under the same terms as Ruby.

Required files

strscan


Module: Etc

Module | Etc
In: | etc/etc.c

The etc module provides access to information from the /etc/passwd and /etc/group files on Linux and Unix systems.

Documented by mathew <meta@pobox.com>.

Methods

endgrent endpwent getgrent getgrgid getgrnam getlogin getpwent getpwnam getpwuid group passwd setgrent setpwent

Public Instance methods

endgrent()

Ends the process of scanning through the /etc/group file begun by getgrent, and closes the file.

[Source]

/* Ends the process of scanning through the /etc/group file begun by
 * getgrent, and closes the file.
 */
static VALUE
etc_endgrent(obj)
    VALUE obj;
{
#ifdef HAVE_GETGRENT
    endgrent();
#endif
    return Qnil;
}
endpwent()

Ends the process of scanning through the /etc/passwd file begun with getpwent, and closes the file.

[Source]

/* Ends the process of scanning through the /etc/passwd file begun with
 * getpwent, and closes the file.
 */
static VALUE
etc_endpwent(obj)
    VALUE obj;
{
#ifdef HAVE_GETPWENT
    endpwent();
#endif
    return Qnil;
}
getgrent()

Returns an entry from the /etc/group file. The first time it is called it opens the file and returns the first entry; each successive call returns the next entry, or nil if the end of the file has been reached.

To close the file when processing is complete, call endgrent.

Each entry is returned as a Struct::Group:

  • Group#name contains the name of the group as a String.
  • Group#passwd contains the encrypted password as a String. An ‘x’ is returned if password access to the group is not available; an empty string is returned if no password is needed to obtain membership of the group.
  • Group#gid contains the group’s numeric ID as an integer.
  • Group#mem is an Array of Strings containing the short login names of the members of the group.

[Source]

/* Returns an entry from the /etc/group file. The first time it is called it
 * opens the file and returns the first entry; each successive call returns
 * the next entry, or nil if the end of the file has been reached.
 *
 * To close the file when processing is complete, call endgrent.
 *
 * Each entry is returned as a Struct::Group:
 *
 * - Group#name contains the name of the group as a String.
 *
 * - Group#passwd contains the encrypted password as a String. An 'x' is
 *   returned if password access to the group is not available; an empty
 *   string is returned if no password is needed to obtain membership of
 *   the group.
 *
 * - Group#gid contains the group's numeric ID as an integer.
 *
 * - Group#mem is an Array of Strings containing the short login names of the
 *   members of the group.
 */
static VALUE
etc_getgrent(obj)
    VALUE obj;
{
#ifdef HAVE_GETGRENT
    struct group *gr;

    if (gr = getgrent()) {
    return setup_group(gr);
    }
#endif
    return Qnil;
}
getgrgid(p1)

Returns information about the group with specified integer group id (gid), as found in /etc/group.

The information is returned as a Struct::Group; see getgrent above for details.

e.g. Etc.getgrgid(100) -> #<struct
Struct::Group name="users", passwd="x", gid=100,
mem=["meta", "root"]>

[Source]

/* Returns information about the group with specified integer group id (gid),
 * as found in /etc/group.
 *
 * The information is returned as a Struct::Group; see getgrent above for
 * details.
 *
 * e.g.  Etc.getgrgid(100) -> #<struct Struct::Group name="users", passwd="x",
 * gid=100, mem=["meta", "root"]>
 *
 */
static VALUE
etc_getgrgid(obj, id)
    VALUE obj, id;
{
#ifdef HAVE_GETGRENT
    int gid;
    struct group *grp;

    rb_secure(4);
    gid = NUM2INT(id);
    grp = getgrgid(gid);
    if (grp == 0) rb_raise(rb_eArgError, "can't find group for %d", gid);
    return setup_group(grp);
#else
    return Qnil;
#endif
}
getgrnam(p1)

Returns information about the group with specified String name, as found in /etc/group.

The information is returned as a Struct::Group; see getgrent above for details.

e.g. Etc.getgrnam(‘users’) ->
#<struct Struct::Group name="users", passwd="x",
gid=100, mem=["meta", "root"]>

[Source]

/* Returns information about the group with specified String name, as found
 * in /etc/group.
 *
 * The information is returned as a Struct::Group; see getgrent above for
 * details.
 *
 * e.g.  Etc.getgrnam('users') -> #<struct Struct::Group name="users",
 * passwd="x", gid=100, mem=["meta", "root"]>
 *
 */
static VALUE
etc_getgrnam(obj, nam)
    VALUE obj, nam;
{
#ifdef HAVE_GETGRENT
    struct group *grp;

    rb_secure(4);
    SafeStringValue(nam);
    grp = getgrnam(RSTRING(nam)->ptr);
    if (grp == 0) rb_raise(rb_eArgError, "can't find group for %s", RSTRING(nam)->ptr);
    return setup_group(grp);
#else
    return Qnil;
#endif
}
getlogin()

Returns the short user name of the currently logged in user.

e.g.

  Etc.getlogin -> 'guest'

[Source]

/* Returns the short user name of the currently logged in user.
 *
 * e.g.
 *   Etc.getlogin -> 'guest'
 */
static VALUE
etc_getlogin(obj)
    VALUE obj;
{
    char *login;

    rb_secure(4);
#ifdef HAVE_GETLOGIN
    login = getlogin();
    if (!login) login = getenv("USER");
#else
    login = getenv("USER");
#endif

    if (login)
    return rb_tainted_str_new2(login);
    return Qnil;
}
getpwent()

Returns an entry from the /etc/passwd file. The first time it is called it opens the file and returns the first entry; each successive call returns the next entry, or nil if the end of the file has been reached.

To close the file when processing is complete, call endpwent.

Each entry is returned as a Struct::Passwd:

  • Passwd#name contains the short login name of the user as a String.
  • Passwd#passwd contains the encrypted password of the user as a String. an ‘x’ is returned if shadow passwords are in use. An ’*’ is returned if the user cannot log in using a password.
  • Passwd#uid contains the integer user ID (uid) of the user.
  • Passwd#gid contains the integer group ID (gid) of the user’s primary group.
  • Passwd#gecos contains a longer String description of the user, such as a full name. Some Unix systems provide structured information in the gecos field, but this is system-dependent.
  • Passwd#dir contains the path to the home directory of the user as a String.
  • Passwd#shell contains the path to the login shell of the user as a String.

[Source]

/* Returns an entry from the /etc/passwd file. The first time it is called it
 * opens the file and returns the first entry; each successive call returns
 * the next entry, or nil if the end of the file has been reached.
 *
 * To close the file when processing is complete, call endpwent.
 *
 * Each entry is returned as a Struct::Passwd:
 *
 * - Passwd#name contains the short login name of the user as a String.
 *
 * - Passwd#passwd contains the encrypted password of the user as a String.
 *   an 'x' is returned if shadow passwords are in use. An '*' is returned
 *   if the user cannot log in using a password.
 *
 * - Passwd#uid contains the integer user ID (uid) of the user.
 *
 * - Passwd#gid contains the integer group ID (gid) of the user's primary group.
 *
 * - Passwd#gecos contains a longer String description of the user, such as
 *   a full name. Some Unix systems provide structured information in the
 *   gecos field, but this is system-dependent.
 *
 * - Passwd#dir contains the path to the home directory of the user as a String.
 *
 * - Passwd#shell contains the path to the login shell of the user as a String.
 */
static VALUE
etc_getpwent(obj)
    VALUE obj;
{
#ifdef HAVE_GETPWENT
    struct passwd *pw;

    if (pw = getpwent()) {
    return setup_passwd(pw);
    }
#endif
    return Qnil;
}
getpwnam(p1)

Returns the /etc/passwd information for the user with specified login name.

The information is returned as a Struct::Passwd; see getpwent above for details.

e.g. * Etc.getpwnam(‘root’)
-> #<struct Struct::Passwd name="root",
passwd="x", uid=0, gid=0,
gecos="root",dir="/root",
shell="/bin/bash">

[Source]

/* Returns the /etc/passwd information for the user with specified login name.
 *
 * The information is returned as a Struct::Passwd; see getpwent above for
 * details.
 *
 * e.g.  * Etc.getpwnam('root') -> #<struct Struct::Passwd name="root",
 * passwd="x", uid=0, gid=0, gecos="root",dir="/root", shell="/bin/bash">
 */
static VALUE
etc_getpwnam(obj, nam)
    VALUE obj, nam;
{
#ifdef HAVE_GETPWENT
    struct passwd *pwd;

    SafeStringValue(nam);
    pwd = getpwnam(RSTRING(nam)->ptr);
    if (pwd == 0) rb_raise(rb_eArgError, "can't find user for %s", RSTRING(nam)->ptr);
    return setup_passwd(pwd);
#else
    return Qnil;
#endif
}
getpwuid(...)

Returns the /etc/passwd information for the user with specified integer user id (uid).

The information is returned as a Struct::Passwd; see getpwent above for details.

e.g. * Etc.getpwuid(0) -> #<struct
Struct::Passwd name="root", passwd="x", uid=0, gid=0,
gecos="root",dir="/root",
shell="/bin/bash">

[Source]

/* Returns the /etc/passwd information for the user with specified integer
 * user id (uid).
 *
 * The information is returned as a Struct::Passwd; see getpwent above for
 * details.
 *
 * e.g.  * Etc.getpwuid(0) -> #<struct Struct::Passwd name="root",
 * passwd="x", uid=0, gid=0, gecos="root",dir="/root", shell="/bin/bash">
 */
static VALUE
etc_getpwuid(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
#if defined(HAVE_GETPWENT)
    VALUE id;
    int uid;
    struct passwd *pwd;

    rb_secure(4);
    if (rb_scan_args(argc, argv, "01", &id) == 1) {
    uid = NUM2INT(id);
    }
    else {
    uid = getuid();
    }
    pwd = getpwuid(uid);
    if (pwd == 0) rb_raise(rb_eArgError, "can't find user for %d", uid);
    return setup_passwd(pwd);
#else
    return Qnil;
#endif
}
group()

Provides a convenient Ruby iterator which executes a block for each entry in the /etc/group file.

The code block is passed an Etc::Group struct; see getgrent above for details.

Example:

    require 'etc'

    Etc.group {|g|
      puts g.name + ": " + g.mem.join(', ')
    }

[Source]

/* Provides a convenient Ruby iterator which executes a block for each entry
 * in the /etc/group file.
 *
 * The code block is passed an Etc::Group struct; see getgrent above for
 * details.
 *
 * Example:
 *
 *     require 'etc'
 *
 *     Etc.group {|g|
 *       puts g.name + ": " + g.mem.join(', ')
 *     }
 *
 */
static VALUE
etc_group(obj)
    VALUE obj;
{
#ifdef HAVE_GETGRENT
    struct group *grp;

    rb_secure(4);
    if (rb_block_given_p()) {
    if (group_blocking) {
        rb_raise(rb_eRuntimeError, "parallel group iteration");
    }
    group_blocking = Qtrue;
    rb_ensure(group_iterate, 0, group_ensure, 0);
    }
    if (grp = getgrent()) {
    return setup_group(grp);
    }
#endif
    return Qnil;
}
passwd()

Provides a convenient Ruby iterator which executes a block for each entry in the /etc/passwd file.

The code block is passed an Etc::Passwd struct; see getpwent above for details.

Example:

    require 'etc'

    Etc.passwd {|u|
      puts u.name + " = " + u.gecos
    }

[Source]

/* Provides a convenient Ruby iterator which executes a block for each entry
 * in the /etc/passwd file.
 *
 * The code block is passed an Etc::Passwd struct; see getpwent above for
 * details.
 *
 * Example:
 *
 *     require 'etc'
 *
 *     Etc.passwd {|u|
 *       puts u.name + " = " + u.gecos
 *     }
 *
 */
static VALUE
etc_passwd(obj)
    VALUE obj;
{
#ifdef HAVE_GETPWENT
    struct passwd *pw;

    rb_secure(4);
    if (rb_block_given_p()) {
    if (passwd_blocking) {
        rb_raise(rb_eRuntimeError, "parallel passwd iteration");
    }
    passwd_blocking = Qtrue;
    rb_ensure(passwd_iterate, 0, passwd_ensure, 0);
    }
    if (pw = getpwent()) {
    return setup_passwd(pw);
    }
#endif
    return Qnil;
}
setgrent()

Resets the process of reading the /etc/group file, so that the next call to getgrent will return the first entry again.

[Source]

/* Resets the process of reading the /etc/group file, so that the next call
 * to getgrent will return the first entry again.
 */
static VALUE
etc_setgrent(obj)
    VALUE obj;
{
#ifdef HAVE_GETGRENT
    setgrent();
#endif
    return Qnil;
}
setpwent()

Resets the process of reading the /etc/passwd file, so that the next call to getpwent will return the first entry again.

[Source]

/* Resets the process of reading the /etc/passwd file, so that the next call
 * to getpwent will return the first entry again.
 */
static VALUE
etc_setpwent(obj)
    VALUE obj;
{
#ifdef HAVE_GETPWENT
    setpwent();
#endif
    return Qnil;
}


File: etc.c

etc.c

Path: | etc/etc.c
Last Update: | Sat Oct 29 10:38:08 AUS Eastern Standard Time 2005


Module: Fcntl

Module | Fcntl
In: | fcntl/fcntl.c

Fcntl loads the constants defined in the system’s <fcntl.h> C header file, and used with both the fcntl(2) and open(2) POSIX system calls.

Copyright (C) 1997-2001 Yukihiro Matsumoto

Documented by mathew <meta@pobox.com>

Usage

To perform a fcntl(2) operation, use IO::fcntl in the core classes.

To perform an open(2) operation, use IO::sysopen.

The set of operations and constants available depends upon specific OS platform. Some values listed below may not be supported on your system.

The constants supported by Ruby for use with IO::fcntl are:

  • F_DUPFD - duplicate a close-on-exec file handle to a non-close-on-exec file handle.
  • F_GETFD - read the close-on-exec flag of a file handle.
  • F_SETFD - set the close-on-exec flag of a file handle.
  • FD_CLOEXEC - the value of the close-on-exec flag.
  • F_GETFL - get file descriptor flags.
  • F_SETFL - set file descriptor flags.
  • O_APPEND, O_NONBLOCK, etc (see below) - file descriptor flag values for the above.
  • F_GETLK - determine whether a given region of a file is locked.
  • F_SETLK - acquire a lock on a region of a file.
  • F_SETLKW - acquire a lock on a region of a file, waiting if necessary.
  • F_RDLCK, F_WRLCK, F_UNLCK - types of lock for the above.

The constants supported by Ruby for use with IO::sysopen are:

  • O_APPEND - open file in append mode.
  • O_NOCTTY - open tty without it becoming controlling tty.
  • O_CREAT - create file if it doesn’t exist.
  • O_EXCL - used with O_CREAT, fail if file exists.
  • O_TRUNC - truncate file on open.
  • O_NONBLOCK / O_NDELAY - open in non-blocking mode.
  • O_RDONLY - open read-only.
  • O_WRONLY - open write-only.
  • O_RDWR - open read-write.
  • O_ACCMODE - mask to extract read/write flags.

Example:

  require 'fcntl'

  fd = IO::sysopen('/tmp/tempfile',
       Fcntl::O_WRONLY | Fcntl::O_EXCL | Fcntl::O_CREAT)
  f = IO.open(fd)
  f.syswrite("TEMP DATA")
  f.close


File: fcntl.c

fcntl.c

Path: | fcntl/fcntl.c
Last Update: | Sat Oct 29 10:38:08 AUS Eastern Standard Time 2005


Module: FileUtils

Module | FileUtils
In: | fileutils.rb

fileutils.rb

Copyright © 2000-2005 Minero Aoki <aamine@loveruby.net>

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() - ['private_module_function']

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

[Source]

# File fileutils.rb, line 118
  def cd(dir, options = {}, &block) # :yield: dir
    fu_check_options options, :verbose
    fu_output_message "cd #{dir}" if options[:verbose]
    Dir.chdir(dir, &block)
    fu_output_message 'cd -' if options[:verbose] and block
  end
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

[Source]

# File fileutils.rb, line 853
  def chmod(mode, list, options = {})
    fu_check_options options, :noop, :verbose
    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(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.#{$$}"

[Source]

# File fileutils.rb, line 874
  def chmod_R(mode, list, options = {})
    fu_check_options options, :noop, :verbose, :force
    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(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

[Source]

# File fileutils.rb, line 907
  def chown(user, group, list, options = {})
    fu_check_options options, :noop, :verbose
    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(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

[Source]

# File fileutils.rb, line 936
  def chown_R(user, group, list, options = {})
    fu_check_options options, :noop, :verbose, :force
    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
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

[Source]

# File fileutils.rb, line 782
  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(a, b)

Returns true if the contents of a stream a and b are identical.

[Source]

# File fileutils.rb, line 800
  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
copy(src, dest, options = {})

Alias for cp

copy_entry(src, dest, preserve = false, dereference_root = 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.

[Source]

# File fileutils.rb, line 444
  def copy_entry(src, dest, preserve = false, dereference_root = false)
    Entry_.new(src, nil, dereference_root).traverse do |ent|
      destent = Entry_.new(dest, ent.rel, false)
      ent.copy destent.path
      ent.copy_metadata destent.path if preserve
    end
  end
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.

[Source]

# File fileutils.rb, line 457
  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(src, dest)

Copies stream src to dest. src must respond to read(n) and dest must respond to write(str).

[Source]

# File fileutils.rb, line 469
  def copy_stream(src, dest)
    fu_copy_stream0 src, dest, fu_stream_blksize(src, dest)
  end
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

[Source]

# File fileutils.rb, line 378
  def cp(src, dest, options = {})
    fu_check_options options, :preserve, :noop, :verbose
    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(src, dest, options = {})

Options: preserve noop verbose dereference_root

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.

[Source]

# File fileutils.rb, line 417
  def cp_r(src, dest, options = {})
    fu_check_options options, :preserve, :noop, :verbose, :dereference_root
    fu_output_message "cp -r#{options[:preserve] ? 'p' : ''} #{[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]
    end
  end
fu_have_symlink?(

[Source]

# File fileutils.rb, line 722
  def fu_have_symlink?   #:nodoc
    File.symlink nil, nil
  rescue NotImplementedError
    return false
  rescue
    return true
  end
fu_world_writable?(st)

[Source]

# File fileutils.rb, line 718
  def fu_world_writable?(st)
    (st.mode & 0002) != 0
  end
getwd()

Alias for pwd

identical?(a, b)

Alias for compare_file

install(src, dest, options = {})

Options: mode 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.

  FileUtils.install 'ruby', '/usr/local/bin/ruby', :mode => 0755, :verbose => true
  FileUtils.install 'lib.rb', '/usr/local/lib/ruby/site_ruby', :verbose => true

[Source]

# File fileutils.rb, line 825
  def install(src, dest, options = {})
    fu_check_options options, :mode, :preserve, :noop, :verbose
    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
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 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 '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.

[Source]

# File fileutils.rb, line 293
  def ln(src, dest, options = {})
    fu_check_options options, :force, :noop, :verbose
    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(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'

[Source]

# File fileutils.rb, line 332
  def ln_s(src, dest, options = {})
    fu_check_options options, :force, :noop, :verbose
    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(src, dest, options = {})

Options: noop verbose

Same as

  #ln_s(src, dest, :force)

[Source]

# File fileutils.rb, line 355
  def ln_sf(src, dest, options = {})
    fu_check_options options, :noop, :verbose
    options = options.dup
    options[:force] = true
    ln_s src, dest, options
  end
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

[Source]

# File fileutils.rb, line 165
  def mkdir(list, options = {})
    fu_check_options options, :mode, :noop, :verbose
    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(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.

[Source]

# File fileutils.rb, line 195
  def mkdir_p(list, options = {})
    fu_check_options options, :mode, :noop, :verbose
    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
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

[Source]

# File fileutils.rb, line 486
  def mv(src, dest, options = {})
    fu_check_options options, :force, :noop, :verbose
    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
        end
      rescue SystemCallError
        raise unless options[:force]
      end
    end
  end
pwd()

Options: (none)

Returns the name of the current directory.

[Source]

# File fileutils.rb, line 100
  def pwd
    Dir.pwd
  end
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.

[Source]

# File fileutils.rb, line 771
  def remove_dir(path, force = false)
    remove_entry path, force   # FIXME?? check if it is a directory
  end
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.

[Source]

# File fileutils.rb, line 743
  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_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].

[Source]

# File fileutils.rb, line 667
  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
remove_file(path, force = false)

Removes a file path. This method ignores StandardError if force is true.

[Source]

# File fileutils.rb, line 760
  def remove_file(path, force = false)
    Entry_.new(path).remove_file
  rescue
    raise unless force
  end
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

[Source]

# File fileutils.rb, line 533
  def rm(list, options = {})
    fu_check_options options, :force, :noop, :verbose
    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(list, options = {})

Options: noop verbose

Equivalent to

  #rm(list, :force => true)

[Source]

# File fileutils.rb, line 558
  def rm_f(list, options = {})
    fu_check_options options, :noop, :verbose
    options = options.dup
    options[:force] = true
    rm list, options
  end
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.

[Source]

# File fileutils.rb, line 593
  def rm_r(list, options = {})
    fu_check_options options, :force, :noop, :verbose, :secure
    # 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(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.

[Source]

# File fileutils.rb, line 621
  def rm_rf(list, options = {})
    fu_check_options options, :noop, :verbose, :secure
    options = options.dup
    options[:force] = true
    rm_r list, options
  end
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

[Source]

# File fileutils.rb, line 258
  def rmdir(list, options = {})
    fu_check_options options, :noop, :verbose
    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
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'

[Source]

# File fileutils.rb, line 1006
  def touch(list, options = {})
    fu_check_options options, :noop, :verbose
    list = fu_list(list)
    fu_output_message "touch #{list.join ' '}" if options[:verbose]
    return if options[:noop]
    t = Time.now
    list.each do |path|
      begin
        File.utime(t, t, path)
      rescue Errno::ENOENT
        File.open(path, 'a') {
          ;
        }
      end
    end
  end
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'

[Source]

# File 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


Module: FileUtils::DryRun

Module | FileUtils::DryRun
In: | 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: | 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: | fileutils.rb


Module: FileUtils::Verbose

Module | FileUtils::Verbose
In: | 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


File: fileutils.rb

fileutils.rb

Path: | fileutils.rb
Last Update: | Sat Oct 15 23:44:27 AUS Eastern Standard Time 2005

fileutils.rb

Copyright © 2000-2005 Minero Aoki <aamine@loveruby.net>

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


Module: Finalizer

Module | Finalizer
In: | finalize.rb
  finalizer.rb -
      $Release Version: 0.3$
      $Revision: 1.4 $
      $Date: 1998/02/27 05:34:33 $
      by Keiju ISHITSUKA

—

  Usage:

  add(obj, dependant, method = :finalize, *opt)
  add_dependency(obj, dependant, method = :finalize, *opt)
      add dependency R_method(obj, dependant)

  delete(obj_or_id, dependant, method = :finalize)
  delete_dependency(obj_or_id, dependant, method = :finalize)
      delete dependency R_method(obj, dependant)
  delete_all_dependency(obj_or_id, dependant)
      delete dependency R_*(obj, dependant)
  delete_by_dependant(dependant, method = :finalize)
      delete dependency R_method(*, dependant)
  delete_all_by_dependant(dependant)
      delete dependency R_*(*, dependant)
  delete_all
      delete all dependency R_*(*, *)

  finalize(obj_or_id, dependant, method = :finalize)
  finalize_dependency(obj_or_id, dependant, method = :finalize)
      finalize the dependant connected by dependency R_method(obj, dependtant).
  finalize_all_dependency(obj_or_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_all_by_dependant(dependant)
      finalize all dependants connected by dependency R_*(*, dependant).
  finalize_all
      finalize all dependency registered to the Finalizer.

  safe{..}
      stop invoking Finalizer on GC.

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)

[Source]

# File finalize.rb, line 51
    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_all_by_dependant(dependant)

delete dependency R_*(*, dependant)

[Source]

# File finalize.rb, line 99
    def delete_all_by_dependant(dependant)
      for id in @dependency.keys
        delete_all_dependency(id, dependant)
      end
    end
delete_all_dependency(id, dependant)

delete dependency R_*(obj, dependant)

[Source]

# File finalize.rb, line 78
    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(dependant, method = :finalize)

delete dependency R_method(*, dependant)

[Source]

# File finalize.rb, line 91
    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_dependency(id, dependant, method = :finalize)

delete dependency R_method(obj, dependant)

[Source]

# File finalize.rb, line 64
    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
finalize_all()

finalize all dependants registered to the Finalizer.

[Source]

# File finalize.rb, line 149
    def finalize_all
      for id, assocs in @dependency
        for dependant, method, *opt in assocs
          dependant.send(method, id, *opt)
        end
        assocs.clear
      end
    end
finalize_all_by_dependant(dependant)

finalize all dependants connected by dependency R_*(*, dependtant)

[Source]

# File finalize.rb, line 142
    def finalize_all_by_dependant(dependant)
      for id in @dependency.keys
        finalize_all_dependency(id, dependant)
      end
    end
finalize_all_dependency(id, dependant)

finalize all dependants connected by dependency R_*(obj, dependtant)

[Source]

# File finalize.rb, line 121
    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(dependant, method = :finalize)

finalize the dependant connected by dependency R_method(*, dependtant)

[Source]

# File finalize.rb, line 134
    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_dependency(id, dependant, method = :finalize)

finalize the depandant connected by dependency R_method(obj, dependtant)

[Source]

# File finalize.rb, line 106
    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
safe() {|| ...}

method to call finalize_* safely.

[Source]

# File finalize.rb, line 159
    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


File: finalize.rb

finalize.rb

Path: | finalize.rb
Last Update: | Fri Nov 08 05:18:14 AUS Eastern Daylight Time 2002
  finalizer.rb -
      $Release Version: 0.3$
      $Revision: 1.4 $
      $Date: 1998/02/27 05:34:33 $
      by Keiju ISHITSUKA

—

  Usage:

  add(obj, dependant, method = :finalize, *opt)
  add_dependency(obj, dependant, method = :finalize, *opt)
      add dependency R_method(obj, dependant)

  delete(obj_or_id, dependant, method = :finalize)
  delete_dependency(obj_or_id, dependant, method = :finalize)
      delete dependency R_method(obj, dependant)
  delete_all_dependency(obj_or_id, dependant)
      delete dependency R_*(obj, dependant)
  delete_by_dependant(dependant, method = :finalize)
      delete dependency R_method(*, dependant)
  delete_all_by_dependant(dependant)
      delete dependency R_*(*, dependant)
  delete_all
      delete all dependency R_*(*, *)

  finalize(obj_or_id, dependant, method = :finalize)
  finalize_dependency(obj_or_id, dependant, method = :finalize)
      finalize the dependant connected by dependency R_method(obj, dependtant).
  finalize_all_dependency(obj_or_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_all_by_dependant(dependant)
      finalize all dependants connected by dependency R_*(*, dependant).
  finalize_all
      finalize all dependency registered to the Finalizer.

  safe{..}
      stop invoking Finalizer on GC.


Module: Find

Module | Find
In: | 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.

[Source]

# File find.rb, line 35
  def find(*paths) # :yield: path
    paths.collect!{|d| d.dup}
    while file = paths.shift
      catch(:prune) do
        next unless File.exist? file
        yield file.dup.taint
        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()

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.

[Source]

# File find.rb, line 74
  def prune
    throw :prune
  end


File: find.rb

find.rb

Path: | find.rb
Last Update: | Sat Oct 15 23:44:27 AUS Eastern Standard Time 2005

find.rb: the Find module for processing all files under a given directory.


File: forwardable.rb

forwardable.rb

Path: | forwardable.rb
Last Update: | Sat Oct 15 23:44:27 AUS Eastern Standard Time 2005

forwardable - Support for the Delegation Pattern

   $Release Version: 1.1$
   $Revision: 1.2.2.1 $
   $Date: 2005/09/26 13:59:45 $
   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!


Module: Forwardable

Module | Forwardable
In: | 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
    extends 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
    # extends 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.

[Source]

# File 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
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.

[Source]

# File forwardable.rb, line 130
  def def_instance_delegators(accessor, *methods)
    for method in methods
      def_instance_delegator(accessor, method)
    end
  end


Module: SingleForwardable

Module | SingleForwardable
In: | 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.

[Source]

# File 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
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.

[Source]

# File forwardable.rb, line 187
  def def_singleton_delegators(accessor, *methods)
    for method in methods
      def_singleton_delegator(accessor, method)
    end
  end


File: ftools.rb

ftools.rb

Path: | ftools.rb
Last Update: | Sat Oct 15 23:44:27 AUS Eastern Standard Time 2005

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.


Class: File

Class | File
In: | ftools.rb
Parent: | Object

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

catname chmod compare copy install makedirs move safe_unlink syscopy

Constants

BUFSIZE = 8 * 1024

External Aliases

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

Public Class methods

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.

[Source]

# File ftools.rb, line 47
  def catname(from, to)
    if directory? to
      join to.sub(%r([/\\]$), ''), basename(from)
    else
      to
    end
  end
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

[Source]

# File ftools.rb, line 240
  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
compare(from, to, verbose = false)

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

[Source]

# File ftools.rb, line 133
  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
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.

[Source]

# File ftools.rb, line 90
  def copy(from, to, verbose = false)
    $stderr.print from, " -> ", catname(from, to), "\n" if verbose
    syscopy from, to
  end
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.

[Source]

# File ftools.rb, line 253
  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
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.

[Source]

# File ftools.rb, line 208
  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
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.

[Source]

# File ftools.rb, line 102
  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
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.

[Source]

# File ftools.rb, line 171
  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
syscopy(from, to)

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

[Source]

# File ftools.rb, line 59
  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


Class: GDBM

Class | GDBM
In: | gdbm/gdbm.c
Parent: | Object

Methods

[] []= cachesize= clear close closed? delete delete_if each each_key each_pair each_value empty? fastmode= fetch has_key? has_value? include? index indexes indices invert key? keys length member? new open reject reject! reorganize replace select setopt shift size store sync syncmode= to_a to_hash update value? values values_at

Included Modules

Enumerable

Public Class methods

new(...)
open(...)

Public Instance methods

[](p1)
[]=(p1, p2)
cachesize=(p1)
clear()
close()
closed?()
delete(p1)
delete_if()
each()
each_key()
each_pair()
each_value()
empty?()
fastmode=(p1)
fetch(...)
has_key?(p1)
has_value?(p1)
include?(p1)
index(p1)
indexes(...)
indices(...)
invert()
key?(p1)
keys()
length()
member?(p1)
reject()
reject!()
reorganize()
replace(p1)
select(...)
setopt(p1, p2)
shift()
size()
store(p1, p2)
sync()
syncmode=(p1)
to_a()
to_hash()
update(p1)
value?(p1)
values()
values_at(...)


Class: GDBMError

Class | GDBMError
In: | gdbm/gdbm.c
Parent: | StandardError


Class: GDBMFatalError

Class | GDBMFatalError
In: | gdbm/gdbm.c
Parent: | Exception


File: gdbm.c

gdbm.c

Path: | gdbm/gdbm.c
Last Update: | Sat Oct 15 23:43:53 AUS Eastern Standard Time 2005


Class: Generator

Class | Generator
In: | 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.

[Source]

# File 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

Public Instance methods

current()

Returns the element at the current position.

[Source]

# File generator.rb, line 141
  def current()
    if @queue.empty?
      raise EOFError, "no more elements available"
    end

    @queue.first
  end
each() {|self.next| ...}

Rewinds the generator and enumerates the elements.

[Source]

# File generator.rb, line 157
  def each
    rewind

    until end?
      yield self.next
    end

    self
  end
end?()

Returns true if the generator has reached the end.

[Source]

# File generator.rb, line 102
  def end?()
    if @cont_endp = callcc { |c| c }
      @cont_yield.nil? && @queue.empty?
    else
      @queue.empty?
    end
  end
index()

Returns the current index (position) counting from zero.

[Source]

# File generator.rb, line 116
  def index()
    @index
  end
next()

Returns the element at the current position and moves forward.

[Source]

# File 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
next?()

Returns true if the generator has not reached the end yet.

[Source]

# File generator.rb, line 111
  def next?()
    !end?
  end
pos()

Returns the current index (position) counting from zero.

[Source]

# File generator.rb, line 121
  def pos()
    @index
  end
rewind()

Rewinds the generator.

[Source]

# File generator.rb, line 150
  def rewind()
    initialize(nil, &@block) if @index.nonzero?

    self
  end
yield(value)

Yields an element to the generator.

[Source]

# File generator.rb, line 92
  def yield(value)
    if @cont_yield = callcc { |c| c }
      @queue << value
      @cont_next.call(nil)
    end

    self
  end


Class: SyncEnumerator

Class | SyncEnumerator
In: | 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.

[Source]

# File generator.rb, line 186
  def initialize(*enums)
    @gens = enums.map { |e| Generator.new(e) }
  end

Public Instance methods

each() {|ret| ...}

Enumerates rows of the Enumerable objects.

[Source]

# File 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
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.

[Source]

# File generator.rb, line 205
  def end?(i = nil)
    if i.nil?
      @gens.detect { |g| g.end? } ? true : false
    else
      @gens[i].end?
    end
  end
length()

Returns the number of enumerated Enumerable objects, i.e. the size of each row.

[Source]

# File generator.rb, line 198
  def length
    @gens.length
  end
size()

Returns the number of enumerated Enumerable objects, i.e. the size of each row.

[Source]

# File generator.rb, line 192
  def size
    @gens.size
  end


File: generator.rb

generator.rb

Path: | generator.rb
Last Update: | Sat Oct 15 23:44:27 AUS Eastern Standard Time 2005

generator.rb: convert an internal iterator to an external one

Copyright © 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.


Class: GetoptLong

Class | GetoptLong
In: | getoptlong.rb
Parent: | Object

Parse command line options just like GNU getopt_long().

Methods

each each_option error_message get get_option new ordering= 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 `quit’ mode.
quiet | [R] | Return the flag of `quiet’ mode.

Public Class methods

new(*arguments)

Initializer.

[Source]

# File getoptlong.rb, line 45
  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

Public Instance methods

each() {|option_name, option_argument| ...}

Iterator version of `get’.

[Source]

# File getoptlong.rb, line 456
  def each
    loop do
      option_name, option_argument = get_option
      break if option_name == nil
      yield option_name, option_argument
    end
  end
each_option()

Alias for each

error_message()

Return an error message.

[Source]

# File getoptlong.rb, line 282
  def error_message
    return @error_message
  end
get()

Get next option name and its argument as an array.

[Source]

# File getoptlong.rb, line 289
  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
get_option()

Alias for get

ordering=(ordering)

Set ordering.

[Source]

# File getoptlong.rb, line 108
  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(*arguments)

Set options

[Source]

# File getoptlong.rb, line 139
  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()

Terminate option processing.

[Source]

# File getoptlong.rb, line 228
  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?()

Examine whether option processing is terminated or not.

[Source]

# File getoptlong.rb, line 248
  def terminated?
    return @status == STATUS_TERMINATED
  end


Class: GetoptLong::AmbigousOption

Class | GetoptLong::AmbigousOption
In: | getoptlong.rb
Parent: | Error


Class: GetoptLong::Error

Class | GetoptLong::Error
In: | getoptlong.rb
Parent: | StandardError

Error types.


Class: GetoptLong::InvalidOption

Class | GetoptLong::InvalidOption
In: | getoptlong.rb
Parent: | Error


Class: GetoptLong::MissingArgument

Class | GetoptLong::MissingArgument
In: | getoptlong.rb
Parent: | Error


Class: GetoptLong::NeedlessArgument

Class | GetoptLong::NeedlessArgument
In: | getoptlong.rb
Parent: | Error


File: getoptlong.rb

getoptlong.rb

Path: | getoptlong.rb
Last Update: | Sat Oct 15 23:44:27 AUS Eastern Standard Time 2005
                                                        -*- Ruby -*-

Copyright (C) 1998, 1999, 2000 Motoyuki Kasahara

You may redistribute it and/or modify it under the same license terms as Ruby.


Class: GServer

Class | GServer
In: | gserver.rb
Parent: | Object

GServer implements a generic server, featuring thread pool management, simple logging, and multi-server management. See 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

connections in_service? join new serve shutdown start stop stop stopped?

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)

[Source]

# File gserver.rb, line 98
  def GServer.in_service?(port, host = DEFAULT_HOST)
    @@services.has_key?(host) and
      @@services[host].has_key?(port)
  end
new(port, host = DEFAULT_HOST, maxConnections = 4, stdlog = $stderr, audit = false, debug = false)

[Source]

# File gserver.rb, line 167
  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
stop(port, host = DEFAULT_HOST)

[Source]

# File gserver.rb, line 92
  def GServer.stop(port, host = DEFAULT_HOST)
    @@servicesMutex.synchronize {
      @@services[host][port].stop
    }
  end

Public Instance methods

connections()

[Source]

# File gserver.rb, line 119
  def connections
    @connections.size
  end
join()

[Source]

# File gserver.rb, line 123
  def join
    @tcpServerThread.join if @tcpServerThread
  end
serve(io)

[Source]

# File gserver.rb, line 86
  def serve(io)
  end
shutdown()

[Source]

# File gserver.rb, line 115
  def shutdown
    @shutdown = true
  end
start(maxConnections = -1)

[Source]

# File gserver.rb, line 181
  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
stop()

[Source]

# File gserver.rb, line 103
  def stop
    @connectionsMutex.synchronize  {
      if @tcpServerThread
        @tcpServerThread.raise "stop"
      end
    }
  end
stopped?()

[Source]

# File gserver.rb, line 111
  def stopped?
    @tcpServerThread == nil
  end


File: gserver.rb

gserver.rb

Path: | gserver.rb
Last Update: | Sat Oct 15 23:44:27 AUS Eastern Standard Time 2005

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


Class: Iconv

Class | Iconv
In: | iconv/iconv.c
Parent: | Data

Summary

Ruby extension for charset conversion.

Abstract

Iconv is a wrapper class for the UNIX 95 iconv() function family, which translates string between various encoding systems.

See Open Group’s on-line documents for more details.

  • iconv.h: www.opengroup.org/onlinepubs/007908799/xsh/iconv.h.html
  • iconv_open(): www.opengroup.org/onlinepubs/007908799/xsh/iconv_open.html
  • iconv(): www.opengroup.org/onlinepubs/007908799/xsh/iconv.html
  • iconv_close(): www.opengroup.org/onlinepubs/007908799/xsh/iconv_close.html

Which coding systems are available is platform-dependent.

Examples

  1. Instantiate a new Iconv and use method Iconv#iconv.
      cd = Iconv.new(to, from)
  begin
    input.each { |s| output << cd.iconv(s) }
    output << cd.iconv(nil)                   # Don't forget this!
  ensure
    cd.close
  end
  2. Invoke Iconv.open with a block.
      Iconv.open(to, from) do |cd|
    input.each { |s| output << cd.iconv(s) }
    output << cd.iconv(nil)
  end
  3. Shorthand for (2).
      Iconv.iconv(to, from, *input.to_a)
  4. Simple conversion between two charsets.
      converted_text = Iconv.new('iso-8859-15', 'utf-8').iconv(text)

Methods

charset_map close conv iconv iconv new open

Classes and Modules

Module Iconv::Failure
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.iconv(to, from, *strs)

Document-method: Iconv::conv

Shorthand for

  Iconv.iconv(to, from, str).join

See Iconv.iconv.

[Source]

/*
 * Document-method: Iconv::conv
 * call-seq: Iconv.iconv(to, from, *strs)
 *
 * 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));
}
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.

[Source]

/*
 * 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));
}
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

[Source]

/*
 * 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.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.

[Source]

/*
 * 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;
    }
}

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.

[Source]

/*
 * 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);
}


Module: Iconv::Failure

Module | Iconv::Failure
In: | 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.

[Source]

/*
 * 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

Returns inspected string like as: #<class: success, failed>

[Source]

/*
 * 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);
}
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.

[Source]

/*
 * 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);
}


Class: Iconv::IllegalSequence

Class | Iconv::IllegalSequence
In: | 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

rb_eIconvFailure


Class: Iconv::InvalidCharacter

Class | Iconv::InvalidCharacter
In: | 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

rb_eIconvFailure


Class: Iconv::InvalidEncoding

Class | Iconv::InvalidEncoding
In: | iconv/iconv.c
Parent: | ArgError

Requested coding-system is not available on this system.

Included Modules

rb_eIconvFailure


Class: Iconv::OutOfRange

Class | Iconv::OutOfRange
In: | iconv/iconv.c
Parent: | RuntimeError

Iconv library internal error. Must not occur.

Included Modules

rb_eIconvFailure


File: iconv.c

iconv.c

Path: | iconv/iconv.c
Last Update: | Sat Oct 15 23:43:53 AUS Eastern Standard Time 2005


File: importenv.rb

importenv.rb

Path: | importenv.rb
Last Update: | Sat Oct 15 23:44:27 AUS Eastern Standard Time 2005

importenv.rb — imports environment variables as global variables, Perlish ;(

Usage:

 require 'importenv'
 p $USER
 $USER = "matz"
 p ENV["USER"]


Class: IO

Class | IO
In: | io/wait/lib/nonblock.rb

Methods

nonblock nonblock= nonblock? ready? wait

Public Instance methods

nonblock(nb = true) {|| ...}

[Source]

# File io/wait/lib/nonblock.rb, line 17
  def nonblock(nb = true)
    nb, self.nonblock = nonblock?, nb
    yield
  ensure
    self.nonblock = nb
  end
nonblock=(nb)

[Source]

# File io/wait/lib/nonblock.rb, line 7
  def nonblock=(nb)
    f = fcntl(Fcntl::F_GETFL)
    if nb
      f |= File::NONBLOCK
    else
      f &= ~File::NONBLOCK
    end
    fcntl(Fcntl::F_SETFL, f)
  end
nonblock?()

[Source]

# File io/wait/lib/nonblock.rb, line 3
  def nonblock?
    (fcntl(Fcntl::F_GETFL) & File::NONBLOCK) != 0
  end
ready?()

begin

— IO#ready?

    returns non-nil if input available without blocking, or nil.

end

[Source]

/*
=begin
--- IO#ready?
    returns non-nil if input available without blocking, or nil.
=end
*/
static VALUE
io_ready_p(io)
    VALUE io;
{
    OpenFile *fptr;
    FILE *fp;
    ioctl_arg n;

    GetOpenFile(io, fptr);
    rb_io_check_readable(fptr);
    if (!FIONREAD_POSSIBLE_P(fileno(fptr->f))) return Qfalse;
    fp = fptr->f;
    if (feof(fp)) return Qfalse;
    if (rb_read_pending(fp)) return Qtrue;
    if (ioctl(fileno(fp), FIONREAD, &n)) rb_sys_fail(0);
    if (n > 0) return ioctl_arg2num(n);
    return Qnil;
}
wait(...)

begin

— IO#wait([timeout])

    waits until input available or timed out and returns self, or nil
    when EOF reached.

end

[Source]

/*
=begin
--- IO#wait([timeout])
    waits until input available or timed out and returns self, or nil
    when EOF reached.
=end
*/
static VALUE
io_wait(argc, argv, io)
    int argc;
    VALUE *argv;
    VALUE io;
{
    OpenFile *fptr;
    fd_set rd;
    FILE *fp;
    int fd;
    ioctl_arg n;
    VALUE timeout;
    struct timeval *tp, timerec;

    GetOpenFile(io, fptr);
    rb_io_check_readable(fptr);
    rb_scan_args(argc, argv, "01", &timeout);
    if (NIL_P(timeout)) {
    tp = 0;
    }
    else {
    timerec = rb_time_interval(timeout);
    tp = &timerec;
    }

    fp = fptr->f;
    if (feof(fp)) return Qfalse;
    if (rb_read_pending(fp)) return Qtrue;
    fd = fileno(fp);
    FD_ZERO(&rd);
    FD_SET(fd, &rd);
    if (rb_thread_select(fd + 1, &rd, NULL, NULL, tp) < 0)
    rb_sys_fail(0);
    rb_io_check_closed(fptr);
    if (!FIONREAD_POSSIBLE_P(fileno(fptr->f))) return Qfalse;
    if (ioctl(fileno(fp), FIONREAD, &n)) rb_sys_fail(0);
    if (n > 0) return io;
    return Qnil;
}


File: nonblock.rb

nonblock.rb

Path: | io/wait/lib/nonblock.rb
Last Update: | Sat Oct 15 23:43:53 AUS Eastern Standard Time 2005

Required files

fcntl


File: wait.c

wait.c

Path: | io/wait/wait.c
Last Update: | Sat Oct 15 23:43:53 AUS Eastern Standard Time 2005


File: ipaddr.rb

ipaddr.rb

Path: | ipaddr.rb
Last Update: | Sat Oct 15 23:44:27 AUS Eastern Standard Time 2005
 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,v 1.5.2.2 2005/01/19 09:14:42 usa Exp $

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>

Required files

socket


Class: IPAddr

Class | IPAddr
In: | ipaddr.rb
Parent: | Object

IPAddr provides a set of methods to manipulate an IP address. Both IPv4 and IPv6 are supported.

Methods

& << == === >> hton include? inspect ip6_arpa ip6_int ipv4? ipv4_compat ipv4_compat? ipv4_mapped ipv4_mapped? ipv6? mask native new new_ntoh ntop reverse 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.

[Source]

# File ipaddr.rb, line 403
  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
new_ntoh(addr)

Creates a new ipaddr containing the given network byte ordered string form of an IP address.

[Source]

# File ipaddr.rb, line 91
  def IPAddr::new_ntoh(addr)
    return IPAddr.new(IPAddr::ntop(addr))
  end
ntop(addr)

Convert a network byte ordered string form of an IP address into human readable form.

[Source]

# File ipaddr.rb, line 97
  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

Public Instance methods

&(other)

Returns a new ipaddr built by bitwise AND.

[Source]

# File ipaddr.rb, line 110
  def &(other)
    return self.clone.set(@addr & other.to_i)
  end
<<(num)

Returns a new ipaddr built by bitwise left shift.

[Source]

# File ipaddr.rb, line 125
  def <<(num)
    return self.clone.set(addr_mask(@addr << num))
  end
==(other)

Returns true if two ipaddr are equal.

[Source]

# File ipaddr.rb, line 135
  def ==(other)
    if other.kind_of?(IPAddr) && @family != other.family
      return false
    end
    return (@addr == other.to_i)
  end
===(other)

Alias for include?

>>(num)

Returns a new ipaddr built by bitwise right-shift.

[Source]

# File ipaddr.rb, line 120
  def >>(num)
    return self.clone.set(@addr >> num)
  end
hton()

Returns a network byte ordered string form of the IP address.

[Source]

# File ipaddr.rb, line 226
  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
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

[Source]

# File ipaddr.rb, line 156
  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
inspect()

Returns a string containing a human-readable representation of the ipaddr. ("#<IPAddr: family:address/mask>")

[Source]

# File ipaddr.rb, line 322
  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
ip6_arpa()

Returns a string for DNS reverse lookup compatible with RFC3172.

[Source]

# File ipaddr.rb, line 305
  def ip6_arpa
    if !ipv6?
      raise ArgumentError, "not an IPv6 address"
    end
    return _reverse + ".ip6.arpa"
  end
ip6_int()

Returns a string for DNS reverse lookup compatible with RFC1886.

[Source]

# File ipaddr.rb, line 313
  def ip6_int
    if !ipv6?
      raise ArgumentError, "not an IPv6 address"
    end
    return _reverse + ".ip6.int"
  end
ipv4?()

Returns true if the ipaddr is an IPv4 address.

[Source]

# File ipaddr.rb, line 240
  def ipv4?
    return @family == Socket::AF_INET
  end
ipv4_compat()

Returns a new ipaddr built by converting the native IPv4 address into an IPv4-compatible IPv6 address.

[Source]

# File ipaddr.rb, line 274
  def ipv4_compat
    if !ipv4?
      raise ArgumentError, "not an IPv4 address"
    end
    return self.clone.set(@addr, Socket::AF_INET6)
  end
ipv4_compat?()

Returns true if the ipaddr is an IPv4-compatible IPv6 address.

[Source]

# File ipaddr.rb, line 255
  def ipv4_compat?
    if !ipv6? || (@addr >> 32) != 0
      return false
    end
    a = (@addr & IN4MASK)
    return a != 0 && a != 1
  end
ipv4_mapped()

Returns a new ipaddr built by converting the native IPv4 address into an IPv4-mapped IPv6 address.

[Source]

# File ipaddr.rb, line 265
  def ipv4_mapped
    if !ipv4?
      raise ArgumentError, "not an IPv4 address"
    end
    return self.clone.set(@addr | 0xffff00000000, Socket::AF_INET6)
  end
ipv4_mapped?()

Returns true if the ipaddr is an IPv4-mapped IPv6 address.

[Source]

# File ipaddr.rb, line 250
  def ipv4_mapped?
    return ipv6? && (@addr >> 32) == 0xffff
  end
ipv6?()

Returns true if the ipaddr is an IPv6 address.

[Source]

# File ipaddr.rb, line 245
  def ipv6?
    return @family == Socket::AF_INET6
  end
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.)

[Source]

# File ipaddr.rb, line 144
  def mask(prefixlen)
    return self.clone.mask!(prefixlen)
  end
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.

[Source]

# File ipaddr.rb, line 284
  def native
    if !ipv4_mapped? && !ipv4_compat?
      return self
    end
    return self.clone.set(@addr & IN4MASK, Socket::AF_INET)
  end
reverse()

Returns a string for DNS reverse lookup. It returns a string in RFC3172 form for an IPv6 address.

[Source]

# File ipaddr.rb, line 293
  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
to_i()

Returns the integer representation of the ipaddr.

[Source]

# File ipaddr.rb, line 190
  def to_i
    return @addr
  end
to_s()

Returns a string containing the IP address representation.

[Source]

# File ipaddr.rb, line 195
  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()

Returns a string containing the IP address representation in canonical form.

[Source]

# File ipaddr.rb, line 221
  def to_string
    return _to_string(@addr)
  end
|(other)

Returns a new ipaddr built by bitwise OR.

[Source]

# File ipaddr.rb, line 115
  def |(other)
    return self.clone.set(@addr | other.to_i)
  end
~()

Returns a new ipaddr built by bitwise negation.

[Source]

# File ipaddr.rb, line 130
  def ~
    return self.clone.set(addr_mask(~@addr))
  end


Class: Socket

Class | Socket
In: | ipaddr.rb
Parent: | Object

Constants

AF_INET6 = Object.new


Class: String

Class | String
In: | jcode.rb
Parent: | Object

Methods

chop chop! delete delete! each_char end_regexp jcount jlength jsize mbchar? squeeze squeeze! succ succ! tr tr! tr_s tr_s!

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 | = | {}

External Aliases

succ! | -> | original_succ!
succ | -> | original_succ

Public Instance methods

chop()

[Source]

# File jcode.rb, line 196
  def chop
    (str = self.dup).chop! or str
  end
chop!()

[Source]

# File jcode.rb, line 192
  def chop!
    self.gsub!(/(?:.|\r?\n)\z/, '')
  end
delete(del)

[Source]

# File jcode.rb, line 156
  def delete(del)
    (str = self.dup).delete!(del) or str
  end
delete!(del)

[Source]

# File jcode.rb, line 151
  def delete!(del)
    return nil if del == ""
    self.gsub!(DeletePatternCache[del] ||= /[#{_regex_quote(del)}]+/, '')
  end
each_char() {|x| ...}

[Source]

# File jcode.rb, line 209
  def each_char
    if block_given?
      scan(/./m) do |x|
        yield x
      end
    else
      scan(/./m)
    end
  end
end_regexp()

[Source]

# File 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
jcount(str)

[Source]

# File jcode.rb, line 205
  def jcount(str)
    self.delete("^#{str}").jlength
  end
jlength()

[Source]

# File jcode.rb, line 200
  def jlength
    self.gsub(/[^\Wa-zA-Z_\d]/, ' ').length
  end
jsize()

Alias for jlength

mbchar?()

[Source]

# File 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
squeeze(del=nil)

[Source]

# File jcode.rb, line 171
  def squeeze(del=nil)
    (str = self.dup).squeeze!(del) or str
  end
squeeze!(del=nil)

[Source]

# File 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
succ()

[Source]

# File jcode.rb, line 92
  def succ
    str = self.dup
    str.succ! or str
  end
succ!()

[Source]

# File jcode.rb, line 78
  def succ!
    reg = end_regexp
    if 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
tr(from, to)

[Source]

# File jcode.rb, line 147
  def tr(from, to)
    (str = self.dup).tr!(from, to) or str
  end
tr!(from, to)

[Source]

# File 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_s(from, to)

[Source]

# File jcode.rb, line 188
  def tr_s(from, to)
    (str = self.dup).tr_s!(from,to) or str
  end
tr_s!(from, to)

[Source]

# File 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


File: jcode.rb

jcode.rb

Path: | jcode.rb
Last Update: | Sat Oct 15 23:44:27 AUS Eastern Standard Time 2005

jcode.rb - ruby code to handle japanese (EUC/SJIS) string


Class: Logger

Class | Logger
In: | logger.rb
Parent: | Object

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. formattercall 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 logdevwrite-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.

[Source]

# File logger.rb, line 265
  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

Public Instance methods

<<(msg)

Dump given message to the log device without any formatting. If no log device exists, return nil.

[Source]

# File logger.rb, line 345
  def <<(msg)
    unless @logdev.nil?
      @logdev.write(msg)
    end
  end
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.

[Source]

# File logger.rb, line 321
  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
close()

Close the logging device.

[Source]

# File logger.rb, line 426
  def close
    @logdev.close if @logdev
  end
datetime_format()

[Source]

# File logger.rb, line 210
  def datetime_format
    @default_formatter.datetime_format
  end
datetime_format=(datetime_format)

Logging date-time format (string passed to strftime).

[Source]

# File logger.rb, line 206
  def datetime_format=(datetime_format)
    @default_formatter.datetime_format = datetime_format
  end
debug(progname = nil, &block)

Log a DEBUG message.

See info for more information.

[Source]

# File logger.rb, line 356
  def debug(progname = nil, &block)
    add(DEBUG, nil, progname, &block)
  end
debug?()

Returns true iff the current severity level allows for the printing of DEBUG messages.

[Source]

# File logger.rb, line 226
  def debug?; @level <= DEBUG; end
error(progname = nil, &block)

Log an ERROR message.

See info for more information.

[Source]

# File logger.rb, line 400
  def error(progname = nil, &block)
    add(ERROR, nil, progname, &block)
  end
error?()

Returns true iff the current severity level allows for the printing of ERROR messages.

[Source]

# File logger.rb, line 238
  def error?; @level <= ERROR; end
fatal(progname = nil, &block)

Log a FATAL message.

See info for more information.

[Source]

# File logger.rb, line 409
  def fatal(progname = nil, &block)
    add(FATAL, nil, progname, &block)
  end
fatal?()

Returns true iff the current severity level allows for the printing of FATAL messages.

[Source]

# File logger.rb, line 242
  def fatal?; @level <= FATAL; end
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.

[Source]

# File logger.rb, line 382
  def info(progname = nil, &block)
    add(INFO, nil, progname, &block)
  end
info?()

Returns true iff the current severity level allows for the printing of INFO messages.

[Source]

# File logger.rb, line 230
  def info?; @level <= INFO; end
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.

[Source]

# File logger.rb, line 419
  def unknown(progname = nil, &block)
    add(UNKNOWN, nil, progname, &block)
  end
warn(progname = nil, &block)

Log a WARN message.

See info for more information.

[Source]

# File logger.rb, line 391
  def warn(progname = nil, &block)
    add(WARN, nil, progname, &block)
  end
warn?()

Returns true iff the current severity level allows for the printing of WARN messages.

[Source]

# File logger.rb, line 234
  def warn?; @level <= WARN; end


Class: Logger::Application

Class | Logger::Application
In: | 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.

[Source]

# File logger.rb, line 654
    def initialize(appname = nil)
      @appname = appname
      @log = Logger.new(STDERR)
      @log.progname = @appname
      @level = @log.level
    end

Public Instance methods

level=(level)

Set the logging threshold, just like Logger#level=.

[Source]

# File logger.rb, line 694
    def level=(level)
      @level = level
      @log.level = @level
    end
log(severity, message = nil, &block)

See Logger#add. This application’s appname is used.

[Source]

# File logger.rb, line 702
    def log(severity, message = nil, &block)
      @log.add(severity, message, @appname, &block) if @log
    end
log=(logdev)

[Source]

# File logger.rb, line 687
    def log=(logdev)
      set_log(logdev)
    end
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.

[Source]

# File logger.rb, line 681
    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
start()

Start the application. Return the status code.

[Source]

# File logger.rb, line 664
    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


Class: Logger::Error

Class | Logger::Error
In: | logger.rb
Parent: | RuntimeError


Class: Logger::Formatter

Class | Logger::Formatter
In: | logger.rb
Parent: | Object

Methods

call new

Constants

Format = "%s, [%s#%d] %5s -- %s: %s\n"

Attributes

datetime_format [RW]

Public Class methods

new()

[Source]

# File logger.rb, line 449
    def initialize
      @datetime_format = nil
    end

Public Instance methods

call(severity, time, progname, msg)

[Source]

# File logger.rb, line 453
    def call(severity, time, progname, msg)
      Format % [severity[0..0], format_datetime(time), $$, severity, progname,
        msg2str(msg)]
    end


Class: Logger::LogDevice

Class | Logger::LogDevice
In: | 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 = {})

[Source]

# File logger.rb, line 490
    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

Public Instance methods

close()

[Source]

# File logger.rb, line 517
    def close
      @mutex.synchronize do
        @dev.close
      end
    end
write(message)

[Source]

# File logger.rb, line 504
    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


Class: Logger::LogDevice::LogDeviceMutex

Class | Logger::LogDevice::LogDeviceMutex
In: | logger.rb
Parent: | Object

Included Modules

MonitorMixin


Module: Logger::Severity

Module | Logger::Severity
In: | logger.rb

Logging severity.

Constants

DEBUG | = | 0
INFO | = | 1
WARN | = | 2
ERROR | = | 3
FATAL | = | 4
UNKNOWN | = | 5


Class: Logger::ShiftingError

Class | Logger::ShiftingError
In: | logger.rb
Parent: | Error


File: logger.rb

logger.rb

Path: | logger.rb
Last Update: | Sat Oct 15 23:44:27 AUS Eastern Standard Time 2005

logger.rb - saimple logging utility Copyright (C) 2000-2003, 2005 NAKAMURA, Hiroshi <nakahiro@sarion.co.jp>.

Required files

monitor


Class: Mail

Class | Mail
In: | mailread.rb
Parent: | Object

Methods

[] body header new

Public Class methods

new(f)

[Source]

# File mailread.rb, line 3
  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

Public Instance methods

[](field)

[Source]

# File mailread.rb, line 45
  def [](field)
    @header[field.capitalize]
  end
body()

[Source]

# File mailread.rb, line 41
  def body
    return @body
  end
header()

[Source]

# File mailread.rb, line 37
  def header
    return @header
  end


File: mailread.rb

mailread.rb

Path: | mailread.rb
Last Update: | Tue Oct 02 14:31:23 AUS Eastern Standard Time 2001


File: mathn.rb

mathn.rb

Path: | mathn.rb
Last Update: | Sat Oct 15 23:44:27 AUS Eastern Standard Time 2005
  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


Class: Bignum

Class | Bignum
In: | mathn.rb
Parent: | Object

External Aliases

quo -> /


Class: Complex

Class | Complex
In: | mathn.rb
Parent: | Object

Constants

Unify = true


Class: Fixnum

Class | Fixnum
In: | mathn.rb
Parent: | Object

External Aliases

quo -> /


Class: Integer

Class | Integer
In: | mathn.rb
Parent: | Object

Methods

from_prime_division gcd2 prime_division

Public Class methods

from_prime_division(pd)

[Source]

# File mathn.rb, line 37
  def Integer.from_prime_division(pd)
    value = 1
    for prime, index in pd
      value *= prime**index
    end
    value
  end

Public Instance methods

gcd2(int)

[Source]

# File 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
prime_division()

[Source]

# File mathn.rb, line 45
  def prime_division
    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


Module: Math

Module | Math
In: | mathn.rb

Methods

rsqrt sqrt

Public Instance methods

rsqrt(a)

[Source]

# File mathn.rb, line 255
  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
sqrt(a)

[Source]

# File mathn.rb, line 232
  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


Class: Prime

Class | Prime
In: | mathn.rb
Parent: | Object

Methods

each new next succ

Included Modules

Enumerable

Public Class methods

new()

[Source]

# File mathn.rb, line 71
  def initialize
    @seed = 1
    @primes = []
    @counts = []
  end

Public Instance methods

each() {|succ| ...}

[Source]

# File mathn.rb, line 101
  def each
    loop do
      yield succ
    end
  end
next()

Alias for succ

succ()

[Source]

# File mathn.rb, line 77
  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


Class: Rational

Class | Rational
In: | mathn.rb
Parent: | Object

Methods

** inspect power2

Constants

Unify = true

External Aliases

** -> power!

Public Instance methods

**(other)

[Source]

# File mathn.rb, line 125
  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
inspect()

[Source]

# File mathn.rb, line 119
  def inspect
    format "%s/%s", numerator.inspect, denominator.inspect
  end
power2(other)

[Source]

# File mathn.rb, line 186
  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


Class: Matrix

Class | Matrix
In: | 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

[Source]

# File matrix.rb, line 122
  def Matrix.[](*rows)
    new(:init_rows, rows, false)
  end
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

[Source]

# File 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
columns(columns)

Creates a matrix using columns as an array of column vectors.

  Matrix.columns([[25, 93], [-1, 66]])
     =>  25 -1
         93 66

[Source]

# File 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(*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

[Source]

# File 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
identity(n)

Creates an n by n identity matrix.

  Matrix.identity(2)
    => 1 0
       0 1

[Source]

# File matrix.rb, line 190
  def Matrix.identity(n)
    Matrix.scalar(n, 1)
  end
new(init_method, *argv)

This method is used by the other methods that create matrices, and is of no use to general users.

[Source]

# File matrix.rb, line 248
  def initialize(init_method, *argv)
    self.send(init_method, *argv)
  end
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

[Source]

# File 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
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

[Source]

# File matrix.rb, line 133
  def Matrix.rows(rows, copy = true)
    new(:init_rows, rows, copy)
  end
scalar(n, value)

Creates an n by n diagonal matrix where each diagonal element is value.

  Matrix.scalar(2, 5)
    => 5 0
       0 5

[Source]

# File matrix.rb, line 180
  def Matrix.scalar(n, value)
    Matrix.diagonal(*Array.new(n).fill(value, 0, n))
  end
zero(n)

Creates an n by n zero matrix.

  Matrix.zero(2)
    => 0 0
       0 0

[Source]

# File matrix.rb, line 204
  def Matrix.zero(n)
    Matrix.scalar(n, 0)
  end

Public Instance methods

*(m)

Matrix multiplication.

  Matrix[[2,4], [6,8]] * Matrix.identity(2)
    => 2 4
       6 8

[Source]

# File 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
**(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

[Source]

# File 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
+(m)

Matrix addition.

  Matrix.scalar(2,5) + Matrix[[1,0], [-4,7]]
    =>  6  0
       -4 12

[Source]

# File 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
-(m)

Matrix subtraction.

  Matrix[[1,5], [4,2]] - Matrix[[9,3], [-4,1]]
    => -8  2
        8  1

[Source]

# File 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
/(other)

Matrix division (multiplication by the inverse).

  Matrix[[7,6], [3,9]] / Matrix[[2,9], [3,1]]
    => -7  1
       -3 -6

[Source]

# File 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
==(other)

Returns true if and only if the two matrices contain equal elements.

[Source]

# File matrix.rb, line 400
  def ==(other)
    return false unless Matrix === other

    other.compare_by_row_vectors(@rows)
  end
[](i, j)

Returns element (i,j) of the matrix. That is: row i, column j.

[Source]

# File matrix.rb, line 265
  def [](i, j)
    @rows[i][j]
  end
clone()

Returns a clone of the matrix, so that the contents of each do not reference identical objects.

[Source]

# File matrix.rb, line 424
  def clone
    Matrix.rows(@rows)
  end
coerce(other)

FIXME: describe coerce.

[Source]

# File 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
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

[Source]

# File matrix.rb, line 327
  def collect # :yield: e
    rows = @rows.collect{|row| row.collect{|e| yield e}}
    Matrix.rows(rows, false)
  end
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.

[Source]

# File 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
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.

[Source]

# File matrix.rb, line 282
  def column_size
    @rows[0].size
  end
column_vectors()

Returns an array of the column vectors of the matrix. See Vector.

[Source]

# File matrix.rb, line 832
  def column_vectors
    columns = (0 .. column_size - 1).collect {
      |i|
      column(i)
    }
    columns
  end
compare_by_row_vectors(rows)

Not really intended for general consumption.

[Source]

# File 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
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

[Source]

# File 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
eql?(other)

Alias for #==

hash()

Returns a hash-code for the matrix.

[Source]

# File matrix.rb, line 431
  def hash
    value = 0
    for row in @rows
      for e in row
        value ^= e.hash
      end
    end
    return value
  end
inspect()

Overrides Object#inspect

[Source]

# File matrix.rb, line 864
  def inspect
    "Matrix"+@rows.inspect
  end
inv()

Alias for inverse

inverse()

Returns the inverse of the matrix.

  Matrix[[1, 2], [2, 1]].inverse
    => -1  1
        0 -1

[Source]

# File matrix.rb, line 579
  def inverse
    Matrix.Raise ErrDimensionMismatch unless square?
    Matrix.I(row_size).inverse_from(self)
  end
inverse_from(src)

Not for public consumption?

[Source]

# File 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
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

[Source]

# File 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
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

[Source]

# File 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
regular?()

Returns true if this is a regular matrix.

[Source]

# File matrix.rb, line 374
  def regular?
    square? and rank == column_size
  end
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.

[Source]

# File 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
row_size()

Returns the number of rows.

[Source]

# File matrix.rb, line 272
  def row_size
    @rows.size
  end
row_vectors()

Returns an array of the row vectors of the matrix. See Vector.

[Source]

# File matrix.rb, line 821
  def row_vectors
    rows = (0 .. row_size - 1).collect {
      |i|
      row(i)
    }
    rows
  end
singular?()

Returns true is this is a singular (i.e. non-regular) matrix.

[Source]

# File matrix.rb, line 381
  def singular?
    not regular?
  end
square?()

Returns true is this is a square matrix. See note in column_size about this being unreliable, though.

[Source]

# File matrix.rb, line 389
  def square?
    column_size == row_size
  end
t()

Alias for transpose

to_a()

Returns an array of arrays that describe the rows of the matrix.

[Source]

# File matrix.rb, line 843
  def to_a
    @rows.collect{|row| row.collect{|e| e}}
  end
to_s()

Overrides Object#to_s

[Source]

# File matrix.rb, line 854
  def to_s
    "Matrix[" + @rows.collect{
      |row|
      "[" + row.collect{|e| e.to_s}.join(", ") + "]"
    }.join(", ")+"]"
  end
tr()

Alias for trace

trace()

Returns the trace (sum of diagonal elements) of the matrix.

  Matrix[[7,6], [3,9]].trace
    => 16

[Source]

# File matrix.rb, line 777
  def trace
    tr = 0
    0.upto(column_size - 1) do
      |i|
      tr += @rows[i][i]
    end
    tr
  end
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

[Source]

# File matrix.rb, line 797
  def transpose
    Matrix.columns(@rows)
  end


Class: Vector

Class | Vector
In: | 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, ...]

[Source]

# File matrix.rb, line 999
  def Vector.[](*array)
    new(:init_elements, array, copy = false)
  end
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.

[Source]

# File matrix.rb, line 1007
  def Vector.elements(array, copy = true)
    new(:init_elements, array, copy)
  end
new(method, array, copy)

For internal use.

[Source]

# File matrix.rb, line 1014
  def initialize(method, array, copy)
    self.send(method, array, copy)
  end

Public Instance methods

*(x)

Multiplies the vector by x, where x is a number or another vector.

[Source]

# File 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
+(v)

Vector addition.

[Source]

# File 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
-(v)

Vector subtraction.

[Source]

# File 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
==(other)

Returns true iff the two vectors have the same elements in the same order.

[Source]

# File matrix.rb, line 1079
  def ==(other)
    return false unless Vector === other

    other.compare_by(@elements)
  end
[](i)

Returns element number i (starting at zero) of the vector.

[Source]

# File matrix.rb, line 1034
  def [](i)
    @elements[i]
  end
clone()

Return a copy of the vector.

[Source]

# File matrix.rb, line 1096
  def clone
    Vector.elements(@elements)
  end
coerce(other)

FIXME: describe Vector#coerce.

[Source]

# File 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
collect( {|e| ...}

Like Array#collect.

[Source]

# File matrix.rb, line 1189
  def collect # :yield: e
    els = @elements.collect {
      |v|
      yield v
    }
    Vector.elements(els, false)
  end
collect2(v) {|e1, e2| ...}

Collects (as in Enumerable#collect) over the elements of this vector and v in conjunction.

[Source]

# File 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
compare_by(elements)

For internal use.

[Source]

# File matrix.rb, line 1089
  def compare_by(elements)
    @elements == elements
  end
covector()

Creates a single-row matrix from this vector.

[Source]

# File matrix.rb, line 1228
  def covector
    Matrix.row_vector(self)
  end
each2(v) {|e1, e2| ...}

Iterate over the elements of this vector and v in conjunction.

[Source]

# File 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
eqn?(other)

Alias for #==

hash()

Return a hash-code for the vector.

[Source]

# File matrix.rb, line 1103
  def hash
    @elements.hash
  end
init_elements(array, copy)

For internal use.

[Source]

# File matrix.rb, line 1021
  def init_elements(array, copy)
    if copy
      @elements = array.dup
    else
      @elements = array
    end
  end
inner_product(v)

Returns the inner product of this vector with the other.

  Vector[4,7].inner_product Vector[10,1]  => 47

[Source]

# File 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
inspect()

Overrides Object#inspect

[Source]

# File matrix.rb, line 1265
  def inspect
    str = "Vector"+@elements.inspect
  end
map(

Alias for collect

map2(v) {|e1, e2| ...}

Like Vector#collect2, but returns a Vector instead of an Array.

[Source]

# File matrix.rb, line 1201
  def map2(v) # :yield: e1, e2
    els = collect2(v) {
      |v1, v2|
      yield v1, v2
    }
    Vector.elements(els, false)
  end
r()

Returns the modulus (Pythagorean distance) of the vector.

  Vector[5,8,2].r => 9.643650761

[Source]

# File matrix.rb, line 1213
  def r
    v = 0
    for e in @elements
      v += e*e
    end
    return Math.sqrt(v)
  end
size()

Returns the number of elements in the vector.

[Source]

# File matrix.rb, line 1041
  def size
    @elements.size
  end
to_a()

Returns the elements of the vector in an array.

[Source]

# File matrix.rb, line 1235
  def to_a
    @elements.dup
  end
to_s()

Overrides Object#to_s

[Source]

# File matrix.rb, line 1258
  def to_s
    "Vector[" + @elements.join(", ") + "]"
  end


File: matrix.rb

matrix.rb

Path: | matrix.rb
Last Update: | Sat Oct 15 23:44:27 AUS Eastern Standard Time 2005

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: | mkmf.rb
Last Update: | Mon Oct 24 20:15:37 AUS Eastern Standard Time 2005

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 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") unless hdr.empty?)
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) $(CFLAGS) $(CPPFLAGS) -c $<'
COMPILE_CXX | = | config_string('COMPILE_CXX') || '$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c $<'
TRY_LINK | = | config_string('TRY_LINK') || "$(CC) #{OUTFLAG}conftest $(INCFLAGS) -I$(hdrdir) $(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)

[Source]

# File mkmf.rb, line 531
def append_library(libs, lib)
  format(LIBARG, lib) + " " + libs
end
arg_config(config, *defaults, &block)

[Source]

# File mkmf.rb, line 801
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
cc_command(opt="")

[Source]

# File mkmf.rb, line 276
def cc_command(opt="")
  Config::expand("$(CC) -c #$INCFLAGS -I$(hdrdir) " \
                 "#$CPPFLAGS #$CFLAGS #$ARCH_FLAG #{opt} #{CONFTEST_C}",
                 CONFIG.merge('hdrdir' => $hdrdir.quote))
end
check_sizeof(type, header = nil, &b)

[Source]

# File mkmf.rb, line 699
def check_sizeof(type, header = nil, &b)
  expr = "sizeof(#{type})"
  m = "checking size of #{type}... "
  message "%s", m
  a = size = nil
  Logging::postpone do
    if size = try_constant(expr, header, &b)
      $defs.push(format("-DSIZEOF_%s=%d", type.upcase.tr_s("^A-Z0-9_", "_"), size))
      a = "#{size}\n"
    else
      a = "failed\n"
    end
    "check_sizeof: #{m}-------------------- #{a}\n"
  end
  message(a)
  Logging::message "--------------------\n\n"
  size
end
checking_for(m, fmt = nil) {|| ...}

[Source]

# File mkmf.rb, line 542
def checking_for(m, fmt = nil)
  f = caller[0][/in `(.*)'$/, 1] and f << ": " #` for vim
  m = "checking 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
config_string(key, config = CONFIG) {|s| ...}

[Source]

# File mkmf.rb, line 64
def config_string(key, config = CONFIG)
  s = config[key] and !s.empty? and block_given? ? yield(s) : s
end
configuration(srcdir)

[Source]

# File mkmf.rb, line 923
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'])}
}
  drive = File::PATH_SEPARATOR == ';' ? /\A\w:/ : /\A/
  if destdir = CONFIG["prefix"].scan(drive)[0] and !destdir.empty?
    mk << "\nDESTDIR = #{destdir}\n"
  end
  CONFIG.each do |key, var|
    next unless /prefix$/ =~ key
    mk << "#{key} = #{with_destdir(var.sub(drive, ''))}\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.sub(drive, ''))}\n"
  end
  if !$extmk and !$configure_args.has_key?('--ruby') and
      sep = config_string('BUILD_FILE_SEPARATOR')
    sep = ":/=#{sep}"
  else
    sep = ""
  end
  mk << %{
CC = #{CONFIG['CC']}
LIBRUBY = #{CONFIG['LIBRUBY']}
LIBRUBY_A = #{CONFIG['LIBRUBY_A']}
LIBRUBYARG_SHARED = #$LIBRUBYARG_SHARED
LIBRUBYARG_STATIC = #$LIBRUBYARG_STATIC

CFLAGS   = #{CONFIG['CCDLFLAGS'] unless $static} #$CFLAGS #$ARCH_FLAG
CPPFLAGS = -I. -I$(topdir) -I$(hdrdir) -I$(srcdir) #{$defs.join(" ")} #{$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.join(" ") if $preload}
}
  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
cpp_command(outfile, opt="")

[Source]

# File mkmf.rb, line 282
def cpp_command(outfile, opt="")
  Config::expand("$(CPP) #$INCFLAGS -I$(hdrdir) " \
                 "#$CPPFLAGS #$CFLAGS #{opt} #{CONFTEST_C} #{outfile}",
                 CONFIG.merge('hdrdir' => $hdrdir.quote))
end
cpp_include(header)

[Source]

# File mkmf.rb, line 316
def cpp_include(header)
  if header
    header = [header] unless header.kind_of? Array
    header.map {|h| "#include <#{h}>\n"}.join
  else
    ""
  end
end
create_header(header = "extconf.h")

[Source]

# File mkmf.rb, line 840
def create_header(header = "extconf.h")
  message "creating %s\n", header
  if $defs.length > 0
    sym = header.tr("a-z./\055", "A-Z___")
    open(header, "w") do |hfile|
      hfile.print "#ifndef #{sym}\n#define #{sym}\n"
      for line in $defs
        case line
        when /^-D([^=]+)(?:=(.*))?/
          hfile.print "#define #$1 #{$2 || 1}\n"
        when /^-U(.*)/
          hfile.print "#undef #$1\n"
        end
      end
      hfile.print "#endif\n"
    end
  end
end
create_makefile(target, srcprefix = nil)

[Source]

# File mkmf.rb, line 1021
def create_makefile(target, srcprefix = nil)
  $target = target
  libpath = $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
  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

  libpath = libpathflag(libpath)

  dllib = target ? "$(TARGET).#{CONFIG['DLEXT']}" : ""
  staticlib = target ? "$(TARGET).#$LIBEXT" : ""
  mfile = open("Makefile", "wb")
  mfile.print configuration(srcprefix)
  mfile.print %{
libpath = #{$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}
STATIC_LIB = #{staticlib unless $static.nil?}

}
  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:            #{target ? $extout ? "install" : "$(DLLIB)" : "Makefile"}
static:         $(STATIC_LIB)#{$extout ? " install-rb" : ""}
}
  mfile.print CLEANINGS
  dirs = []
  mfile.print "install: install-so install-rb\n\n"
  sodir = dir = "$(RUBYARCHDIR)"
  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"
    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")
      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\t"
  mfile.print "@-$(RM) $@\n\t"
  mfile.print "@-$(MAKEDIRS) $(@D)\n\t" if $extout
  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[$\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 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
    mfile.print "$(OBJS): ", headers.join(' '), "\n"
  end

  $makefile_created = true
ensure
  mfile.close if mfile
end
create_tmpsrc(src) {|src| ...}

[Source]

# File mkmf.rb, line 246
def create_tmpsrc(src)
  src = yield(src) if block_given?
  src = src.sub(/[^\n]\z/, "\\&\n")
  open(CONFTEST_C, "wb") do |cfile|
    cfile.print src
  end
  src
end
dir_config(target, idefault=nil, ldefault=nil)

[Source]

# File mkmf.rb, line 859
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
dir_re(dir)

[Source]

# File mkmf.rb, line 68
def dir_re(dir)
  Regexp.new('\$(?:\('+dir+'\)|\{'+dir+'\})(?:\$\(target_prefix\)|\{target_prefix\})?')
end
dummy_makefile(srcdir)

[Source]

# File mkmf.rb, line 1010
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
egrep_cpp(pat, src, opt = "", &b)

[Source]

# File mkmf.rb, line 442
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
enable_config(config, *defaults) {|config, *defaults| ...}

[Source]

# File mkmf.rb, line 828
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
find_executable(bin, path = nil)

[Source]

# File mkmf.rb, line 795
def find_executable(bin, path = nil)
  checking_for bin do
    find_executable0(bin, path)
  end
end
find_executable0(bin, path = nil)

[Source]

# File mkmf.rb, line 775
def  find_executable0find_executable0(bin, path = nil)
  ext = config_string('EXEEXT')
  if File.expand_path(bin) == bin
    return bin if File.executable?(bin)
    return file if ext and File.executable?(file = bin + ext)
    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_header(header, *paths)

[Source]

# File mkmf.rb, line 638
def find_header(header, *paths)
  checking_for header do
    if try_cpp(cpp_include(header))
      true
    else
      found = false
      paths.each do |dir|
        opt = "-I#{dir}".quote
        if try_cpp(cpp_include(header), opt)
          $INCFLAGS << " " << opt
          found = true
          break
        end
      end
      found
    end
  end
end
find_library(lib, func, *paths, &b)

[Source]

# File mkmf.rb, line 583
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(func, headers = nil, &b)

[Source]

# File mkmf.rb, line 605
def have_func(func, headers = nil, &b)
  checking_for "#{func}()" do
    if try_func(func, $libs, headers, &b)
      $defs.push(format("-DHAVE_%s", func.upcase))
      true
    else
      false
    end
  end
end
have_header(header, &b)

[Source]

# File mkmf.rb, line 627
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
have_library(lib, func = nil, header=nil, &b)

[Source]

# File mkmf.rb, line 565
def have_library(lib, func = nil, header=nil, &b)
  func = "main" if !func or func.empty?
  lib = with_config(lib+'lib', lib)
  checking_for "#{func}() in #{LIBARG%lib}" do
    if COMMON_LIBS.include?(lib)
      true
    else
      libs = append_library($libs, lib)
      if try_func(func, libs, header, &b)
        $libs = libs
        true
      else
        false
      end
    end
  end
end
have_macro(macro, headers = nil, opt = "", &b)

[Source]

# File mkmf.rb, line 557
def have_macro(macro, headers = nil, opt = "", &b)
  m = "#{macro}"
  m << " in #{headers.inspect}" if headers
  checking_for m do
    macro_defined?(macro, cpp_include(headers), opt, &b)
  end
end
have_struct_member(type, member, header = nil, &b)

[Source]

# File mkmf.rb, line 657
def have_struct_member(type, member, header = nil, &b)
  checking_for "#{type}.#{member}" do
    if try_compile("\#{COMMON_HEADERS}\n\#{cpp_include(header)}\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(type, header = nil, opt = "", &b)

[Source]

# File mkmf.rb, line 675
def have_type(type, header = nil, opt = "", &b)
  checking_for type do
    header = cpp_include(header)
    if try_compile("\#{COMMON_HEADERS}\n\#{header}\n/*top*/\nstatic \#{type} t;\n", opt, &b) or (/\A\w+\z/n =~ type && try_compile("\#{COMMON_HEADERS}\n\#{header}\n/*top*/\nstatic \#{type} *t;\n", opt, &b))
      $defs.push(format("-DHAVE_TYPE_%s", type.strip.upcase.tr_s("^A-Z0-9_", "_")))
      true
    else
      false
    end
  end
end
have_var(var, headers = nil, &b)

[Source]

# File mkmf.rb, line 616
def have_var(var, headers = nil, &b)
  checking_for "#{var}" do
    if try_var(var, headers, &b)
      $defs.push(format("-DHAVE_%s", var.upcase))
      true
    else
      false
    end
  end
end
init_mkmf(config = CONFIG)

[Source]

# File mkmf.rb, line 1277
def init_mkmf(config = CONFIG)
  $makefile_created = false
  $arg_config = []
  $enable_shared = config['ENABLE_SHARED'] == 'yes'
  $defs = []
  $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") || "").dup
  $INCFLAGS = "-I$(topdir)"
  $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']
  $LIBPATH = $extmk ? ["$(topdir)"] : CROSS_COMPILING ? [] : ["$(libdir)"]
  $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)} || []
  $distcleanfiles = config_string('DISTCLEANFILES') {|s| Shellwords.shellwords(s)} || []

  $extout ||= nil
  $extout_prefix ||= nil

  $arg_config.clear
  dir_config("opt")
end
install_dirs(target_prefix = nil)

[Source]

# File mkmf.rb, line 81
def install_dirs(target_prefix = nil)
  if $extout
    dirs = [
      ['RUBYCOMMONDIR', '$(extout)'],
      ['RUBYLIBDIR',    '$(extout)$(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
install_files(mfile, ifiles, map = nil, srcprefix = nil)

[Source]

# File mkmf.rb, line 490
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(mfile, dest, srcdir = nil)

[Source]

# File mkmf.rb, line 527
def install_rb(mfile, dest, srcdir = nil)
  install_files(mfile, [["lib/**/*.rb", dest, "lib"]], nil, srcdir)
end
libpathflag(libpath=$LIBPATH)

[Source]

# File mkmf.rb, line 288
def libpathflag(libpath=$LIBPATH)
  libpath.map{|x|
    (x == "$(topdir)" ? LIBPATHFLAG : LIBPATHFLAG+RPATHFLAG) % x.quote
  }.join
end
link_command(ldflags, opt="", libpath=$LIBPATH)

[Source]

# File mkmf.rb, line 262
def link_command(ldflags, opt="", libpath=$LIBPATH)
  Config::expand(TRY_LINK.dup,
                 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"))
end
log_src(src)

[Source]

# File mkmf.rb, line 236
def log_src(src)
  Logging::message "checked program was:\n/* begin */\n%s/* end */\n\n", src
end
macro_defined?(macro, src, opt = "", &b)

[Source]

# File mkmf.rb, line 468
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
map_dir(dir, map = nil)

[Source]

# File mkmf.rb, line 107
def map_dir(dir, map = nil)
  map ||= INSTALL_DIRS
  map.inject(dir) {|dir, (orig, new)| dir.gsub(orig, new)}
end
merge_libs(*libs)

[Source]

# File mkmf.rb, line 150
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
message(*s)

[Source]

# File mkmf.rb, line 535
def message(*s)
  unless $extmk and not $VERBOSE
    printf(*s)
    $stdout.flush
  end
end
mkmf_failed(path)

[Source]

# File mkmf.rb, line 1325
def mkmf_failed(path)
  unless $makefile_created or File.exist?("Makefile")
    opts = $arg_config.collect {|t, n| "\t#{t}#{"=#{n}" if n}\n"}
    abort "*** #{path} failed ***\n" + FailedMessage + opts.join
  end
end
modified?(target, times)

[Source]

# File mkmf.rb, line 144
def modified?(target, times)
  (t = File.mtime(target)) rescue return nil
  Array === times or times = [times]
  t if times.all? {|n| n <= t}
end
pkg_config(pkg)

[Source]

# File mkmf.rb, line 893
def pkg_config(pkg)
  unless defined?($PKGCONFIG)
    if pkgconfig = with_config("pkg-config", !CROSS_COMPILING && "pkg-config")
      find_executable0(pkgconfig) or pkgconfig = nil
    end
    $PKGCONFIG = pkgconfig
  end
  if $PKGCONFIG and system("#{$PKGCONFIG} --exists #{pkg}")
    cflags = `#{$PKGCONFIG} --cflags #{pkg}`.chomp
    ldflags = `#{$PKGCONFIG} --libs #{pkg}`.chomp
    libs = `#{$PKGCONFIG} --libs-only-l #{pkg}`.chomp
    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]
  end
end
rm_f(*files)

[Source]

# File mkmf.rb, line 140
def rm_f(*files)
  FileUtils.rm_f(Dir[files.join("\0")])
end
scalar_ptr_type?(type, member = nil, headers = nil, &b)

[Source]

# File mkmf.rb, line 718
def 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?(type, member = nil, headers = nil, &b)

[Source]

# File mkmf.rb, line 730
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
try_compile(src, opt="", &b)

[Source]

# File mkmf.rb, line 304
def try_compile(src, opt="", &b)
  try_do(src, cc_command(opt), &b)
ensure
  rm_f "conftest*"
end
try_constant(const, headers = nil, opt = "", &b)

[Source]

# File mkmf.rb, line 360
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
    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
    unless upper == lower
      if try_static_assert("#{const} == #{lower}", headers, opt)
        upper = lower
      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_cpp(src, opt="", &b)

[Source]

# File mkmf.rb, line 310
def try_cpp(src, opt="", &b)
  try_do(src, cpp_command(CPPOUTFILE, opt), &b)
ensure
  rm_f "conftest*"
end
try_do(src, command, &b)

[Source]

# File mkmf.rb, line 255
def try_do(src, command, &b)
  src = create_tmpsrc(src, &b)
  xsystem(command)
ensure
  log_src(src)
end
try_func(func, libs, headers = nil, &b)

[Source]

# File mkmf.rb, line 412
def try_func(func, libs, headers = nil, &b)
  headers = cpp_include(headers)
  try_link("\#{headers}\n/*top*/\nint main() { return 0; }\nint t() { \#{func}(); return 0; }\n", libs, &b) or 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)
end
try_link(src, opt="", &b)

[Source]

# File mkmf.rb, line 298
def try_link(src, opt="", &b)
  try_link0(src, opt, &b)
ensure
  rm_f "conftest*", "c0x32*"
end
try_link0(src, opt="", &b)

[Source]

# File mkmf.rb, line 294
def try_link0(src, opt="", &b)
  try_do(src, link_command("", opt), &b)
end
try_run(src, opt = "", &b)

[Source]

# File mkmf.rb, line 480
def try_run(src, opt = "", &b)
  if try_link0(src, opt, &b)
    xsystem("./conftest")
  else
    nil
  end
ensure
  rm_f "conftest*"
end
try_static_assert(expr, headers = nil, opt = "", &b)

[Source]

# File mkmf.rb, line 349
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_var(var, headers = nil, &b)

[Source]

# File mkmf.rb, line 430
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() { void *volatile p; p = (void *)&\#{var}; return 0; }\n", &b)
end
what_type?(type, member = nil, headers = nil, &b)

[Source]

# File mkmf.rb, line 742
def what_type?(type, member = nil, headers = nil, &b)
  m = "#{type}"
  name = type
  if member
    m << "." << member
    name = "(((#{type} *)0)->#{member})"
  end
  m << " in #{headers.inspect}" if headers
  fmt = "seems %s"
  def fmt.%(x)
    x ? super : "unknown"
  end
  checking_for m, 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
winsep(s)

[Source]

# File mkmf.rb, line 919
def winsep(s)
  s.tr('/', '\\')
end
with_cflags(flags) {|| ...}

[Source]

# File mkmf.rb, line 333
def with_cflags(flags)
  cflags = $CFLAGS
  $CFLAGS = flags
  ret = yield
ensure
  $CFLAGS = cflags unless ret
end
with_config(config, *defaults) {|config, *defaults| ...}

[Source]

# File mkmf.rb, line 807
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
with_cppflags(flags) {|| ...}

[Source]

# File mkmf.rb, line 325
def with_cppflags(flags)
  cppflags = $CPPFLAGS
  $CPPFLAGS = flags
  ret = yield
ensure
  $CPPFLAGS = cppflags unless ret
end
with_destdir(dir)

[Source]

# File mkmf.rb, line 915
def with_destdir(dir)
  /^\$[\(\{]/ =~ dir ? dir : "$(DESTDIR)"+dir
end
with_ldflags(flags) {|| ...}

[Source]

# File mkmf.rb, line 341
def with_ldflags(flags)
  ldflags = $LDFLAGS
  $LDFLAGS = flags
  ret = yield
ensure
  $LDFLAGS = ldflags unless ret
end
xpopen(command, *mode, &block)

[Source]

# File mkmf.rb, line 224
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
xsystem(command)

[Source]

# File mkmf.rb, line 217
def xsystem command
  Logging::open do
    puts command.quote
    system(command)
  end
end


Class: Array

Class | Array
In: | mkmf.rb
Parent: | Object

Methods

quote

Public Instance methods

quote()

[Source]

# File mkmf.rb, line 135
  def quote
    map {|s| s.quote}
  end


Module: Logging

Module | Logging
In: | mkmf.rb

Methods

logfile message open postpone

Public Class methods

logfile(file)

[Source]

# File mkmf.rb, line 190
  def self::logfile file
    @logfile = file
    if @log and not @log.closed?
      @log.flush
      @log.close
      @log = nil
    end
  end
message(*s)

[Source]

# File mkmf.rb, line 184
  def self::message(*s)
    @log ||= File::open(@logfile, 'w')
    @log.sync = true
    @log.printf(*s)
  end
open() {|| ...}

[Source]

# File mkmf.rb, line 173
  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
postpone() {|| ...}

[Source]

# File mkmf.rb, line 199
  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


Class: String

Class | String
In: | mkmf.rb
Parent: | Object

Methods

quote

Public Instance methods

quote()

[Source]

# File mkmf.rb, line 130
  def quote
    /\s/ =~ self ? "\"#{self}\"" : self
  end


Module: MonitorMixin

Module | MonitorMixin
In: | 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)

[Source]

# File monitor.rb, line 173
  def self.extend_object(obj)
    super(obj)
    obj.instance_eval {mon_initialize()}
  end
new(*args)

[Source]

# File monitor.rb, line 245
  def initialize(*args)
    super
    mon_initialize
  end

Public Instance methods

mon_enter()

Enters exclusive section.

[Source]

# File monitor.rb, line 200
  def mon_enter
    Thread.critical = true
    mon_acquire(@mon_entering_queue)
    @mon_count += 1
    Thread.critical = false
  end
mon_exit()

Leaves exclusive section.

[Source]

# File monitor.rb, line 210
  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() {|| ...}

Enters exclusive section and executes the block. Leaves the exclusive section automatically when the block exits. See example under MonitorMixin.

[Source]

# File monitor.rb, line 226
  def mon_synchronize
    mon_enter
    begin
      yield
    ensure
      mon_exit
    end
  end
mon_try_enter()

Attempts to enter exclusive section. Returns false if lock fails.

[Source]

# File monitor.rb, line 181
  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
new_cond()

FIXME: This isn’t documented in Nutshell.

[Source]

# File monitor.rb, line 239
  def new_cond
    return ConditionVariable.new(self)
  end
synchronize()

Alias for mon_synchronize

try_mon_enter()

Alias for mon_try_enter


Class: Monitor

Class | Monitor
In: | monitor.rb
Parent: | Object

Included Modules

MonitorMixin

External Aliases

try_mon_enter | -> | try_enter
mon_enter | -> | enter
mon_exit | -> | exit


Class: MonitorMixin::ConditionVariable

Class | MonitorMixin::ConditionVariable
In: | 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)

[Source]

# File monitor.rb, line 153
    def initialize(monitor)
      @monitor = monitor
      @waiters = []
    end

Public Instance methods

broadcast()

[Source]

# File monitor.rb, line 136
    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()

[Source]

# File monitor.rb, line 147
    def count_waiters
      return @waiters.length
    end
signal()

[Source]

# File monitor.rb, line 127
    def signal
      @monitor.instance_eval {mon_check_owner()}
      Thread.critical = true
      t = @waiters.shift
      t.wakeup if t
      Thread.critical = false
      Thread.pass
    end
wait(timeout = nil)

[Source]

# File monitor.rb, line 89
    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
        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)}
        Thread.critical = false
      end
    end
wait_until()

[Source]

# File monitor.rb, line 121
    def wait_until
      until yield
        wait
      end
    end
wait_while()

[Source]

# File monitor.rb, line 115
    def wait_while
      while yield
        wait
      end
    end


Class: MonitorMixin::ConditionVariable::Timeout

Class | MonitorMixin::ConditionVariable::Timeout
In: | monitor.rb
Parent: | Exception


File: monitor.rb

monitor.rb

Path: | monitor.rb
Last Update: | Sat Oct 15 23:44:27 AUS Eastern Standard Time 2005


Module: Mutex_m

Module | Mutex_m
In: | mutex_m.rb
  mutex_m.rb -
      $Release Version: 3.0$
      $Revision: 1.7 $
      $Date: 1998/02/27 04:28:57 $
      Original from mutex.rb
      by Keiju ISHITSUKA(keiju@ishitsuka.com)
      modified by matz
      patched by akira yamada

—

  Usage:
      require "mutex_m.rb"
      obj = Object.new
      obj.extend Mutex_m
      ...
      extended object can be handled like Mutex
      or
      class Foo
        include Mutex_m
        ...
      end
      obj = Foo.new
      this obj can be handled like Mutex

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)

[Source]

# File mutex_m.rb, line 38
  def Mutex_m.append_features(cl)
    super
    define_aliases(cl) unless cl.instance_of?(Module)
  end
define_aliases(cl)

[Source]

# File mutex_m.rb, line 28
  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
extend_object(obj)

[Source]

# File mutex_m.rb, line 43
  def Mutex_m.extend_object(obj)
    super
    obj.mu_extended
  end
new(*args)

[Source]

# File mutex_m.rb, line 114
  def initialize(*args)
    mu_initialize
    super
  end

Public Instance methods

mu_extended()

[Source]

# File mutex_m.rb, line 48
  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_lock()

[Source]

# File mutex_m.rb, line 84
  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_locked?()

[Source]

# File mutex_m.rb, line 69
  def mu_locked?
    @mu_locked
  end
mu_synchronize() {|| ...}

locking

[Source]

# File mutex_m.rb, line 60
  def mu_synchronize
    begin
      mu_lock
      yield
    ensure
      mu_unlock
    end
  end
mu_try_lock()

[Source]

# File mutex_m.rb, line 73
  def mu_try_lock
    result = false
    Thread.critical = true
    unless @mu_locked
      @mu_locked = true
      result = true
    end
    Thread.critical = false
    result
  end
mu_unlock()

[Source]

# File mutex_m.rb, line 94
  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


File: mutex_m.rb

mutex_m.rb

Path: | mutex_m.rb
Last Update: | Thu Jun 07 00:19:33 AUS Eastern Standard Time 2001
  mutex_m.rb -
      $Release Version: 3.0$
      $Revision: 1.7 $
      $Date: 1998/02/27 04:28:57 $
      Original from mutex.rb
      by Keiju ISHITSUKA(keiju@ishitsuka.com)
      modified by matz
      patched by akira yamada

—

  Usage:
      require "mutex_m.rb"
      obj = Object.new
      obj.extend Mutex_m
      ...
      extended object can be handled like Mutex
      or
      class Foo
        include Mutex_m
        ...
      end
      obj = Foo.new
      this obj can be handled like Mutex


Class: Net::FTP

Class | Net::FTP
In: | 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.

[Source]

# File 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
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.

[Source]

# File 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

Public Instance methods

abort()

Aborts the previous command (ABOR command).

[Source]

# File 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
acct(account)

Sends the ACCT command. TODO: more info.

[Source]

# File net/ftp.rb, line 595
    def acct(account)
      cmd = "ACCT " + account
      voidcmd(cmd)
    end
chdir(dirname)

Changes the (remote) directory.

[Source]

# File 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
close()

Closes the connection. Further operations are impossible until you open a new connection with connect.

[Source]

# File net/ftp.rb, line 810
    def close
      @sock.close if @sock and not @sock.closed?
    end
closed?()

Returns true iff the connection is closed.

[Source]

# File net/ftp.rb, line 817
    def closed?
      @sock == nil or @sock.closed?
    end
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.

[Source]

# File 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
delete(filename)

Deletes a file on the server.

[Source]

# File 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
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.

[Source]

# File 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
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.

[Source]

# File 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
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.

[Source]

# File 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
help(arg = nil)

Issues the HELP command.

[Source]

# File net/ftp.rb, line 776
    def help(arg = nil)
      cmd = "HELP"
      if arg
        cmd = cmd + " " + arg
      end
      sendcmd(cmd)
    end
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.

[Source]

# File 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
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).

[Source]

# File 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
ls(*args)

Alias for list

mdtm(filename)

Issues the MDTM command. TODO: more info.

[Source]

# File net/ftp.rb, line 766
    def mdtm(filename)
      resp = sendcmd("MDTM " + filename)
      if resp[0, 3] == "213"
        return resp[3 .. -1].strip
      end
    end
mkdir(dirname)

Creates a remote directory.

[Source]

# File net/ftp.rb, line 707
    def mkdir(dirname)
      resp = sendcmd("MKD " + dirname)
      return parse257(resp)
    end
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.

[Source]

# File 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
nlst(dir = nil)

Returns an array of filenames in the remote directory.

[Source]

# File 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
noop()

Issues a NOOP command.

[Source]

# File net/ftp.rb, line 794
    def noop
      voidcmd("NOOP")
    end
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.

[Source]

# File 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
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.

[Source]

# File 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(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.

[Source]

# File 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
pwd()

Returns the current remote directory.

[Source]

# File net/ftp.rb, line 722
    def pwd
      resp = sendcmd("PWD")
      return parse257(resp)
    end
quit()

Exits the FTP session.

[Source]

# File net/ftp.rb, line 787
    def quit
      voidcmd("QUIT")
    end
rename(fromname, toname)

Renames a file on the server.

[Source]

# File 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
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").

[Source]

# File 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(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").

[Source]

# File 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
return_code()

Obsolete

[Source]

# File 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=(s)

Obsolete

[Source]

# File net/ftp.rb, line 150
    def return_code=(s)
      $stderr.puts("warning: Net::FTP#return_code= is obsolete and do nothing")
    end
rmdir(dirname)

Removes a remote directory.

[Source]

# File net/ftp.rb, line 715
    def rmdir(dirname)
      voidcmd("RMD " + dirname)
    end
sendcmd(cmd)

Sends a command and returns the response.

[Source]

# File net/ftp.rb, line 261
    def sendcmd(cmd)
      synchronize do
        putline(cmd)
        return getresp
      end
    end
set_socket(sock, get_greeting = true)

WRITEME or make private

[Source]

# File net/ftp.rb, line 183
    def set_socket(sock, get_greeting = true)
      synchronize do
        @sock = sock
        if get_greeting
          voidresp
        end
      end
    end
site(arg)

Issues a SITE command.

[Source]

# File net/ftp.rb, line 801
    def site(arg)
      cmd = "SITE " + arg
      voidcmd(cmd)
    end
size(filename)

Returns the size of the given (remote) filename.

[Source]

# File 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
status()

Returns the status (STAT command).

[Source]

# File 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
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.

[Source]

# File 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(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.

[Source]

# File 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
system()

Returns system information.

[Source]

# File net/ftp.rb, line 731
    def system
      resp = sendcmd("SYST")
      if resp[0, 3] != "215"
        raise FTPReplyError, resp
      end
      return resp[4 .. -1]
    end
voidcmd(cmd)

Sends a command and expect a response beginning with ‘2’.

[Source]

# File net/ftp.rb, line 271
    def voidcmd(cmd)
      synchronize do
        putline(cmd)
        voidresp
      end
    end


Module: Net

Module | Net
In: | net/ftp.rb

Classes and Modules

Class Net::FTP


File: ftp.rb

ftp.rb

Path: | net/ftp.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

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


Class: Net::HTTP

Class | Net::HTTP
In: | net/http.rb
Parent: | Protocol

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.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 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 start start started? trace unlock 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] |
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
                    :
    }

[Source]

# File net/http.rb, line 640
    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
default_port()

The default port to use for HTTP requests; defaults to 80.

[Source]

# File net/http.rb, line 414
    def HTTP.default_port
      http_default_port()
    end
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')

[Source]

# File 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_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'

[Source]

# File 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_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

[Source]

# File 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
http_default_port()

The default port to use for HTTP requests; defaults to 80.

[Source]

# File net/http.rb, line 419
    def HTTP.http_default_port
      80
    end
https_default_port()

The default port to use for HTTPS requests; defaults to 443.

[Source]

# File net/http.rb, line 424
    def HTTP.https_default_port
      443
    end
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.

[Source]

# File 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(address, port = nil)

Creates a new Net::HTTP object for the specified address. This method does not open the TCP connection.

[Source]

# File 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
    end
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" }

[Source]

# File 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
proxy_class?()

returns true if self is a class which was created by HTTP::Proxy.

[Source]

# File net/http.rb, line 658
      def proxy_class?
        @is_proxy_class
      end
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.

[Source]

# File 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
version_1_1()

Turns on net/http 1.1 (ruby 1.6) features. Defaults to OFF in ruby 1.8.

[Source]

# File net/http.rb, line 300
    def HTTP.version_1_1
      @newimpl = false
    end
version_1_1?()

true if net/http is in version 1.1 compatible mode. Defaults to true.

[Source]

# File net/http.rb, line 312
    def HTTP.version_1_1?
      not @newimpl
    end
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

[Source]

# File net/http.rb, line 294
    def HTTP.version_1_2
      @newimpl = true
    end
version_1_2?()

true if net/http is in version 1.2 mode. Defaults to true.

[Source]

# File net/http.rb, line 306
    def HTTP.version_1_2?
      @newimpl
    end

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.

[Source]

# File net/http.rb, line 902
    def copy(path, initheader = nil)
      request(Copy.new(path, initheader))
    end
delete(path, initheader = {'Depth' => 'Infinity'})

Sends a DELETE request to the path and gets a response, as an HTTPResponse object.

[Source]

# File net/http.rb, line 890
    def delete(path, initheader = {'Depth' => 'Infinity'})
      request(Delete.new(path, initheader))
    end
finish()

Finishes HTTP session and closes TCP connection. Raises IOError if not started.

[Source]

# File net/http.rb, line 600
    def finish
      raise IOError, 'HTTP session not yet started' unless started?
      do_finish
    end
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
    }

[Source]

# File net/http.rb, line 769
    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
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']

[Source]

# File net/http.rb, line 799
    def head(path, initheader = nil)
      res = request(Head.new(path, initheader))
      res.value unless @newimpl
      res
    end
head2(path, initheader = nil, &block)

Alias for request_head

inspect()

[Source]

# File net/http.rb, line 475
    def inspect
      "#<#{self.class} #{@address}:#{@port} open=#{started?}>"
    end
lock(path, body, initheader = nil)

Sends a LOCK request to the path and gets a response, as an HTTPResponse object.

[Source]

# File net/http.rb, line 866
    def lock(path, body, initheader = nil)
      request(Lock.new(path, initheader), body)
    end
mkcol(path, body = nil, initheader = nil)

Sends a MKCOL request to the path and gets a response, as an HTTPResponse object.

[Source]

# File net/http.rb, line 908
    def mkcol(path, body = nil, initheader = nil)
      request(Mkcol.new(path, initheader), body)
    end
move(path, initheader = nil)

Sends a MOVE request to the path and gets a response, as an HTTPResponse object.

[Source]

# File net/http.rb, line 896
    def move(path, initheader = nil)
      request(Move.new(path, initheader))
    end
options(path, initheader = nil)

Sends a OPTIONS request to the path and gets a response, as an HTTPResponse object.

[Source]

# File net/http.rb, line 878
    def options(path, initheader = nil)
      request(Options.new(path, initheader))
    end
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
    }

[Source]

# File net/http.rb, line 838
    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
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.

[Source]

# File net/http.rb, line 884
    def propfind(path, body = nil, initheader = {'Depth' => '0'})
      request(Propfind.new(path, initheader), body)
    end
proppatch(path, body, initheader = nil)

Sends a PROPPATCH request to the path and gets a response, as an HTTPResponse object.

[Source]

# File net/http.rb, line 860
    def proppatch(path, body, initheader = nil)
      request(Proppatch.new(path, initheader), body)
    end
proxy?()

True if self is a HTTP proxy class.

[Source]

# File net/http.rb, line 669
    def proxy?
      self.class.proxy_class?
    end
proxy_address()

Address of proxy host. If self does not use a proxy, nil.

[Source]

# File net/http.rb, line 674
    def proxy_address
      self.class.proxy_address
    end
proxy_pass()

User password for accessing proxy. If self does not use a proxy, nil.

[Source]

# File net/http.rb, line 689
    def proxy_pass
      self.class.proxy_pass
    end
proxy_port()

Port number of proxy host. If self does not use a proxy, nil.

[Source]

# File net/http.rb, line 679
    def proxy_port
      self.class.proxy_port
    end
proxy_user()

User name for accessing proxy. If self does not use a proxy, nil.

[Source]

# File net/http.rb, line 684
    def proxy_user
      self.class.proxy_user
    end
proxyaddr()

Alias for proxy_address

proxyport()

Alias for proxy_port

read_timeout=(sec)

Setter for the read_timeout attribute.

[Source]

# File net/http.rb, line 510
    def read_timeout=(sec)
      @socket.read_timeout = sec if @socket
      @read_timeout = sec
    end
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.

[Source]

# File net/http.rb, line 1029
    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
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
    }

[Source]

# File net/http.rb, line 943
    def request_get(path, initheader = nil, &block) # :yield: +response+
      request(Get.new(path, initheader), &block)
    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']

[Source]

# File net/http.rb, line 957
    def request_head(path, initheader = nil, &block)
      request(Head.new(path, initheader), &block)
    end
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
    }

[Source]

# File net/http.rb, line 987
    def request_post(path, data, initheader = nil, &block) # :yield: +response+
      request Post.new(path, initheader), data, &block
    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

[Source]

# File net/http.rb, line 1011
    def send_request(name, path, data = nil, header = nil)
      r = HTTPGenericRequest.new(name,(data ? true : false),true,path,header)
      request r, data
    end
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 { .... }

[Source]

# File net/http.rb, line 488
    def set_debug_output(output)
      warn 'Net::HTTP#set_debug_output called after HTTP started' if started?
      @debug_output = output
    end
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.

[Source]

# File net/http.rb, line 540
    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
started?()

returns true if the HTTP session is started.

[Source]

# File net/http.rb, line 516
    def started?
      @started
    end
trace(path, initheader = nil)

Sends a TRACE request to the path and gets a response, as an HTTPResponse object.

[Source]

# File net/http.rb, line 914
    def trace(path, initheader = nil)
      request(Trace.new(path, initheader))
    end
unlock(path, body, initheader = nil)

Sends a UNLOCK request to the path and gets a response, as an HTTPResponse object.

[Source]

# File net/http.rb, line 872
    def unlock(path, body, initheader = nil)
      request(Unlock.new(path, initheader), body)
    end
use_ssl()

Alias for use_ssl?

use_ssl?()

returns true if use SSL/TLS with HTTP.

[Source]

# File net/http.rb, line 525
    def use_ssl?
      @use_ssl
    end


Module: Net

Module | Net
In: | net/http.rb

Classes and Modules

Module Net::HTTPExceptions
Module Net::HTTPHeader
Class Net::HTTP
Class Net::HTTPError
Class Net::HTTPFatalError
Class Net::HTTPGenericRequest
Class Net::HTTPRequest
Class Net::HTTPResponse
Class Net::HTTPRetriableError
Class Net::HTTPServerException

Constants

HTTPSession = HTTP


Class: Net::HTTP::Copy

Class | Net::HTTP::Copy
In: | 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: | 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: | 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: | 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: | 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: | 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: | 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: | 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: | 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: | 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: | 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: | 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: | 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: | net/http.rb
Parent: | HTTPRequest

Constants

METHOD | = | 'UNLOCK'
REQUEST_HAS_BODY | = | true
RESPONSE_HAS_BODY | = | true


Class: Net::HTTPError

Class | Net::HTTPError
In: | net/http.rb
Parent: | ProtocolError

Included Modules

HTTPExceptions


Module: Net::HTTPExceptions

Module | Net::HTTPExceptions
In: | 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: | net/http.rb
Parent: | ProtoFatalError

Included Modules

HTTPExceptions


Class: Net::HTTPGenericRequest

Class | Net::HTTPGenericRequest
In: | 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)

[Source]

# File net/http.rb, line 1437
    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

Public Instance methods

body=(str)

[Source]

# File net/http.rb, line 1471
    def body=(str)
      @body = str
      @body_stream = nil
      str
    end
body_exist?()

[Source]

# File net/http.rb, line 1464
    def body_exist?
      warn "Net::HTTPRequest#body_exist? is obsolete; use response_body_permitted?" if $VERBOSE
      response_body_permitted?
    end
body_stream=(input)

[Source]

# File net/http.rb, line 1479
    def body_stream=(input)
      @body = nil
      @body_stream = input
      input
    end
inspect()

[Source]

# File net/http.rb, line 1452
    def inspect
      "\#<#{self.class} #{@method}>"
    end
request_body_permitted?()

[Source]

# File net/http.rb, line 1456
    def request_body_permitted?
      @request_has_body
    end
response_body_permitted?()

[Source]

# File net/http.rb, line 1460
    def response_body_permitted?
      @response_has_body
    end


Module: Net::HTTPHeader

Module | Net::HTTPHeader
In: | 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"

[Source]

# File net/http.rb, line 1150
    def [](key)
      a = @header[key.downcase] or return nil
      a.join(', ')
    end
[]=(key, val)

Sets the header field corresponding to the case-insensitive key.

[Source]

# File net/http.rb, line 1156
    def []=(key, val)
      unless val
        @header.delete key.downcase
        return val
      end
      @header[key.downcase] = Array(val).map {|s| s.to_str }
    end
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"]

[Source]

# File net/http.rb, line 1179
    def add_field(key, val)
      if @header.key?(key.downcase)
        @header[key.downcase].concat Array(val)
      else
        @header[key.downcase] = Array(val).dup
      end
    end
basic_auth(account, password)

Set the Authorization: header for "Basic" authorization.

[Source]

# File net/http.rb, line 1410
    def basic_auth(account, password)
      @header['authorization'] = [basic_encode(account, password)]
    end
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.

[Source]

# File net/http.rb, line 1346
    def chunked?
      return false unless @header['transfer-encoding']
      field = self['Transfer-Encoding']
      (/(?:\A|[^\-\w])chunked(?![\-\w])/i =~ field) ? true : false
    end
content_length()

Returns an Integer object which represents the Content-Length: header field or nil if that field is not provided.

[Source]

# File net/http.rb, line 1327
    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=(len)

[Source]

# File net/http.rb, line 1334
    def content_length=(len)
      unless len
        @header.delete 'content-length'
        return nil
      end
      @header['content-length'] = [len.to_i.to_s]
    end
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.

[Source]

# File net/http.rb, line 1355
    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
content_type()

[Source]

# File net/http.rb, line 1368
    def content_type
      "#{main_type()}/#{sub_type()}"
    end
content_type=(type, params = {})

Alias for set_content_type

delete(key)

Removes a header field.

[Source]

# File net/http.rb, line 1242
    def delete(key)
      @header.delete(key.downcase)
    end
each(

Alias for each_header

each_capitalized() {|capitalize(k), v.join(', ')| ...}

As for each_header, except the keys are provided in capitalized form.

[Source]

# File net/http.rb, line 1257
    def each_capitalized
      @header.each do |k,v|
        yield capitalize(k), v.join(', ')
      end
    end
each_capitalized_name() {|+key+| ...}

Iterates for each capitalized header names.

[Source]

# File net/http.rb, line 1228
    def each_capitalized_name(&block)   #:yield: +key+
      @header.each_key do |k|
        yield capitalize(k)
      end
    end
each_header( {|+key+, +value+| ...}

Iterates for each header names and values.

[Source]

# File net/http.rb, line 1212
    def each_header   #:yield: +key+, +value+
      @header.each do |k,va|
        yield k, va.join(', ')
      end
    end
each_key()

Alias for each_name

each_name() {|+key+| ...}

Iterates for each header names.

[Source]

# File net/http.rb, line 1221
    def each_name(&block)   #:yield: +key+
      @header.each_key(&block)
    end
each_value( {|+value+| ...}

Iterates for each header values.

[Source]

# File net/http.rb, line 1235
    def each_value   #:yield: +value+
      @header.each_value do |va|
        yield va.join(', ')
      end
    end
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

[Source]

# File net/http.rb, line 1206
    def fetch(key, *args, &block)   #:yield: +key+
      a = @header.fetch(key.downcase, *args, &block)
      a.join(', ')
    end
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"

[Source]

# File net/http.rb, line 1198
    def get_fields(key)
      return nil unless @header[key.downcase]
      @header[key.downcase].dup
    end
initialize_http_header(initheader)

[Source]

# File net/http.rb, line 1133
    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
key?(key)

true if key header exists.

[Source]

# File net/http.rb, line 1247
    def key?(key)
      @header.key?(key.downcase)
    end
main_type()

[Source]

# File net/http.rb, line 1372
    def main_type
      return nil unless @header['content-type']
      self['Content-Type'].split(';').first.to_s.split('/')[0].to_s.strip
    end
proxy_basic_auth(account, password)

Set Proxy-Authorization: header for "Basic" authorization.

[Source]

# File net/http.rb, line 1415
    def proxy_basic_auth(account, password)
      @header['proxy-authorization'] = [basic_encode(account, password)]
    end
range()

Returns an Array of Range objects which represents Range: header field, or nil if there is no such header.

[Source]

# File net/http.rb, line 1272
    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
range=(r, e = nil)

Alias for set_range

range_length()

The length of the range represented in Content-Range: header.

[Source]

# File net/http.rb, line 1363
    def range_length
      r = content_range() or return nil
      r.end - r.begin
    end
set_content_type(type, params = {})

[Source]

# File net/http.rb, line 1391
    def set_content_type(type, params = {})
      @header['content-type'] = [type + params.map{|k,v|"; #{k}=#{v}"}.join('')]
    end
set_form_data(params, sep = '&')

[Source]

# File net/http.rb, line 1397
    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
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

[Source]

# File net/http.rb, line 1294
    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
sub_type()

[Source]

# File net/http.rb, line 1377
    def sub_type
      return nil unless @header['content-type']
      self['Content-Type'].split(';').first.to_s.split('/')[1].to_s.strip
    end
to_hash()

Returns a Hash consist of header names and values.

[Source]

# File net/http.rb, line 1252
    def to_hash
      @header.dup
    end
type_params()

[Source]

# File net/http.rb, line 1382
    def type_params
      result = {}
      self['Content-Type'].to_s.split(';')[1..-1].each do |param|
        k, v = *param.split('=', 2)
        result[k.strip] = v.strip
      end
      result
    end


Class: Net::HTTPRequest

Class | Net::HTTPRequest
In: | 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.

[Source]

# File net/http.rb, line 1555
    def initialize(path, initheader = nil)
      super self.class::METHOD,
            self.class::REQUEST_HAS_BODY,
            self.class::RESPONSE_HAS_BODY,
            path, initheader
    end


Class: Net::HTTPResponse

Class | Net::HTTPResponse
In: | 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, '501' => 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.

[Source]

# File net/http.rb, line 1752
    def HTTPResponse.body_permitted?
      self::HAS_BODY
    end

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
  }

[Source]

# File net/http.rb, line 2165
    def body
      read_body()
    end
entity()

Alias for body

inspect()

[Source]

# File net/http.rb, line 2038
    def inspect
      "#<#{self.class} #{@code} #{@message} readbody=#{@read}>"
    end
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
  }

[Source]

# File net/http.rb, line 2133
    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
to_ary()

For backward compatibility. To allow Net::HTTP 1.1 style assignment e.g.

   response, body = Net::HTTP.get(....)

[Source]

# File net/http.rb, line 2047
    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()

Raises HTTP error if the response is not 2xx.

[Source]

# File net/http.rb, line 2073
    def value
      error! unless self.kind_of?(HTTPSuccess)
    end


Class: Net::HTTPRetriableError

Class | Net::HTTPRetriableError
In: | net/http.rb
Parent: | ProtoRetriableError

Included Modules

HTTPExceptions


Class: Net::HTTPServerException

Class | Net::HTTPServerException
In: | net/http.rb
Parent: | ProtoServerError

Included Modules

HTTPExceptions


File: http.rb

http.rb

Path: | net/http.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

net/http.rb

Copyright © 1999-2005 Yukihiro Matsumoto Copyright © 1999-2005 Minero Aoki Copyright © 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


Class: Net::IMAP

Class | Net::IMAP
In: | 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.

[Source]

# File net/imap.rb, line 281
    def self.add_authenticator(auth_type, authenticator)
      @@authenticators[auth_type] = authenticator
    end
debug()

Returns the debug mode.

[Source]

# File net/imap.rb, line 263
    def self.debug
      return @@debug
    end
debug=(val)

Sets the debug mode.

[Source]

# File net/imap.rb, line 268
    def self.debug=(val)
      return @@debug = val
    end
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.

[Source]

# File net/imap.rb, line 821
    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(s)

Encode a string from UTF-8 format to modified UTF-7.

[Source]

# File net/imap.rb, line 837
    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(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.

[Source]

# File net/imap.rb, line 875
    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 = []
      @tagged_response_arrival = new_cond
      @continuation_request_arrival = new_cond
      @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

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
  }

[Source]

# File net/imap.rb, line 781
    def add_response_handler(handler = Proc.new)
      @response_handlers.push(handler)
    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.

[Source]

# File net/imap.rb, line 600
    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
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.

[Source]

# File net/imap.rb, line 350
    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
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.

[Source]

# File net/imap.rb, line 307
    def capability
      synchronize do
        send_command("CAPABILITY")
        return @responses.delete("CAPABILITY")[-1]
      end
    end
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.

[Source]

# File net/imap.rb, line 614
    def check
      send_command("CHECK")
    end
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.

[Source]

# File net/imap.rb, line 621
    def close
      send_command("CLOSE")
    end
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.

[Source]

# File net/imap.rb, line 742
    def copy(set, mailbox)
      copy_internal("COPY", set, mailbox)
    end
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.

[Source]

# File net/imap.rb, line 413
    def create(mailbox)
      send_command("CREATE", mailbox)
    end
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.

[Source]

# File net/imap.rb, line 422
    def delete(mailbox)
      send_command("DELETE", mailbox)
    end
disconnect()

Disconnects from the server.

[Source]

# File net/imap.rb, line 286
    def disconnect
      @sock.shutdown unless @usessl
      @receiver_thread.join
      @sock.close
    end
disconnected?()

Returns true if disconnected from the server.

[Source]

# File net/imap.rb, line 293
    def disconnected?
      return @sock.closed?
    end
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.

[Source]

# File net/imap.rb, line 402
    def examine(mailbox)
      synchronize do
        @responses.clear
        send_command("EXAMINE", mailbox)
      end
    end
expunge()

Sends a EXPUNGE command to permanently remove from the currently selected mailbox all messages that have the \Deleted flag set.

[Source]

# File net/imap.rb, line 627
    def expunge
      synchronize do
        send_command("EXPUNGE")
        return @responses.delete("EXPUNGE")
      end
    end
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

[Source]

# File net/imap.rb, line 706
    def fetch(set, attr)
      return fetch_internal("FETCH", set, attr)
    end
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.

[Source]

# File net/imap.rb, line 540
    def getacl(mailbox)
      synchronize do
        send_command("GETACL", mailbox)
        return @responses.delete("ACL")[-1]
      end
    end
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.

[Source]

# File net/imap.rb, line 504
    def getquota(mailbox)
      synchronize do
        send_command("GETQUOTA", mailbox)
        return @responses.delete("QUOTA")
      end
    end
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.

[Source]

# File net/imap.rb, line 490
    def getquotaroot(mailbox)
      synchronize do
        send_command("GETQUOTAROOT", mailbox)
        result = []
        result.concat(@responses.delete("QUOTAROOT"))
        result.concat(@responses.delete("QUOTA"))
        return result
      end
    end
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">]

[Source]

# File net/imap.rb, line 479
    def list(refname, mailbox)
      synchronize do
        send_command("LIST", refname, mailbox)
        return @responses.delete("LIST")
      end
    end
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.

[Source]

# File net/imap.rb, line 373
    def login(user, password)
      send_command("LOGIN", user, password)
    end
logout()

Sends a LOGOUT command to inform the server that the client is done with the connection.

[Source]

# File net/imap.rb, line 321
    def logout
      send_command("LOGOUT")
    end
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+.

[Source]

# File net/imap.rb, line 552
    def lsub(refname, mailbox)
      synchronize do
        send_command("LSUB", refname, mailbox)
        return @responses.delete("LSUB")
      end
    end
noop()

Sends a NOOP command to the server. It does nothing.

[Source]

# File net/imap.rb, line 315
    def noop
      send_command("NOOP")
    end
remove_response_handler(handler)

Removes the response handler.

[Source]

# File net/imap.rb, line 786
    def remove_response_handler(handler)
      @response_handlers.delete(handler)
    end
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.

[Source]

# File net/imap.rb, line 433
    def rename(mailbox, newname)
      send_command("RENAME", mailbox, newname)
    end
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]

[Source]

# File net/imap.rb, line 674
    def search(keys, charset = nil)
      return search_internal("SEARCH", keys, charset)
    end
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.

[Source]

# File net/imap.rb, line 389
    def select(mailbox)
      synchronize do
        @responses.clear
        send_command("SELECT", mailbox)
      end
    end
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].

[Source]

# File net/imap.rb, line 529
    def setacl(mailbox, user, rights)
      if rights.nil?
        send_command("SETACL", mailbox, user, "")
      else
        send_command("SETACL", mailbox, user, rights)
      end
    end
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].

[Source]

# File net/imap.rb, line 516
    def setquota(mailbox, quota)
      if quota.nil?
        data = '()'
      else
        data = '(STORAGE ' + quota.to_s + ')'
      end
      send_command("SETQUOTA", mailbox, RawData.new(data))
    end
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.

[Source]

# File net/imap.rb, line 760
    def sort(sort_keys, search_keys, charset)
      return sort_internal("SORT", sort_keys, search_keys, charset)
    end
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.

[Source]

# File net/imap.rb, line 575
    def status(mailbox, attr)
      synchronize do
        send_command("STATUS", mailbox, attr)
        return @responses.delete("STATUS")[-1].attr
      end
    end
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]}>]

[Source]

# File net/imap.rb, line 729
    def store(set, attr, flags)
      return store_internal("STORE", set, attr, flags)
    end
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.

[Source]

# File net/imap.rb, line 443
    def subscribe(mailbox)
      send_command("SUBSCRIBE", mailbox)
    end
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.

[Source]

# File net/imap.rb, line 803
    def thread(algorithm, search_keys, charset)
      return thread_internal("THREAD", algorithm, search_keys, charset)
    end
uid_copy(set, mailbox)

As for copy(), but set contains unique identifiers.

[Source]

# File net/imap.rb, line 747
    def uid_copy(set, mailbox)
      copy_internal("UID COPY", set, mailbox)
    end
uid_fetch(set, attr)

As for fetch(), but set contains unique identifiers.

[Source]

# File net/imap.rb, line 711
    def uid_fetch(set, attr)
      return fetch_internal("UID FETCH", set, attr)
    end
uid_search(keys, charset = nil)

As for search(), but returns unique identifiers.

[Source]

# File net/imap.rb, line 679
    def uid_search(keys, charset = nil)
      return search_internal("UID SEARCH", keys, charset)
    end
uid_sort(sort_keys, search_keys, charset)

As for sort(), but returns an array of unique identifiers.

[Source]

# File net/imap.rb, line 765
    def uid_sort(sort_keys, search_keys, charset)
      return sort_internal("UID SORT", sort_keys, search_keys, charset)
    end
uid_store(set, attr, flags)

As for store(), but set contains unique identifiers.

[Source]

# File net/imap.rb, line 734
    def uid_store(set, attr, flags)
      return store_internal("UID STORE", set, attr, flags)
    end
uid_thread(algorithm, search_keys, charset)

As for thread(), but returns unique identifiers instead of message sequence numbers.

[Source]

# File net/imap.rb, line 809
    def uid_thread(algorithm, search_keys, charset)
      return thread_internal("UID THREAD", algorithm, search_keys, charset)
    end
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.

[Source]

# File net/imap.rb, line 453
    def unsubscribe(mailbox)
      send_command("UNSUBSCRIBE", mailbox)
    end


Module: Net

Module | Net
In: | net/imap.rb

Classes and Modules

Class Net::IMAP


Class: Net::IMAP::BadResponseError

Class | Net::IMAP::BadResponseError
In: | 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: | 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.

[Source]

# File net/imap.rb, line 1744
      def media_subtype
        $stderr.printf("warning: media_subtype is obsolete.\n")
        $stderr.printf("         use subtype instead.\n")
        return subtype
      end
multipart?()

[Source]

# File net/imap.rb, line 1737
      def multipart?
        return false
      end


Class: Net::IMAP::BodyTypeMessage

Class | Net::IMAP::BodyTypeMessage
In: | 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.

[Source]

# File net/imap.rb, line 1802
      def media_subtype
        $stderr.printf("warning: media_subtype is obsolete.\n")
        $stderr.printf("         use subtype instead.\n")
        return subtype
      end
multipart?()

[Source]

# File net/imap.rb, line 1795
      def multipart?
        return false
      end


Class: Net::IMAP::BodyTypeMultipart

Class | Net::IMAP::BodyTypeMultipart
In: | 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.

[Source]

# File net/imap.rb, line 1843
      def media_subtype
        $stderr.printf("warning: media_subtype is obsolete.\n")
        $stderr.printf("         use subtype instead.\n")
        return subtype
      end
multipart?()

[Source]

# File net/imap.rb, line 1836
      def multipart?
        return true
      end


Class: Net::IMAP::BodyTypeText

Class | Net::IMAP::BodyTypeText
In: | 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.

[Source]

# File net/imap.rb, line 1772
      def media_subtype
        $stderr.printf("warning: media_subtype is obsolete.\n")
        $stderr.printf("         use subtype instead.\n")
        return subtype
      end
multipart?()

[Source]

# File net/imap.rb, line 1765
      def multipart?
        return false
      end


Class: Net::IMAP::ByeResponseError

Class | Net::IMAP::ByeResponseError
In: | 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: | net/imap.rb
Parent: | Object

Authenticator for the "CRAM-MD5" authentication type. See authenticate().

Methods

new process

Public Class methods

new(user, password)

[Source]

# File net/imap.rb, line 3144
      def initialize(user, password)
        @user = user
        @password = password
      end

Public Instance methods

process(challenge)

[Source]

# File net/imap.rb, line 3137
      def process(challenge)
        digest = hmac_md5(challenge, @password)
        return @user + " " + digest
      end


Class: Net::IMAP::DataFormatError

Class | Net::IMAP::DataFormatError
In: | net/imap.rb
Parent: | Error

Error raised when data is in the incorrect format.


Class: Net::IMAP::Error

Class | Net::IMAP::Error
In: | net/imap.rb
Parent: | StandardError

Superclass of IMAP errors.


Class: Net::IMAP::LoginAuthenticator

Class | Net::IMAP::LoginAuthenticator
In: | 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)

[Source]

# File net/imap.rb, line 3126
      def initialize(user, password)
        @user = user
        @password = password
        @state = STATE_USER
      end

Public Instance methods

process(data)

[Source]

# File net/imap.rb, line 3111
      def process(data)
        case @state
        when STATE_USER
          @state = STATE_PASSWORD
          return @user
        when STATE_PASSWORD
          return @password
        end
      end


Class: Net::IMAP::NoResponseError

Class | Net::IMAP::NoResponseError
In: | 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: | 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: | net/imap.rb
Parent: | Error

Error raised when a response from the server is non-parseable.


File: imap.rb

imap.rb

Path: | net/imap.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

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


Class: Net::POP3

Class | Net::POP3
In: | 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: 1.62.2.4 $.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

[Source]

# File net/pop.rb, line 223
    def POP3.APOP( isapop )
      isapop ? APOP : POP3
    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)

[Source]

# File 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
default_port()

The default port for POP3 connections, port 110

[Source]

# File net/pop.rb, line 200
    def POP3.default_port
      110
    end
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

[Source]

# File 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
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

[Source]

# File 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
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.

[Source]

# File 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
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

[Source]

# File 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

Public Instance methods

active?()

Alias for started?

apop?()

Does this instance use APOP authentication?

[Source]

# File net/pop.rb, line 360
    def apop?
      @apop
    end
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.

[Source]

# File net/pop.rb, line 299
    def auth_only( account, password )
      raise IOError, 'opening previously opened POP session' if started?
      start(account, password) {
        ;
      }
    end
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.

[Source]

# File 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
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.

[Source]

# File net/pop.rb, line 527
    def each_mail( &block )  # :yield: message
      mails().each(&block)
    end
finish()

Finishes a POP3 session and closes TCP connection.

[Source]

# File net/pop.rb, line 458
    def finish
      raise IOError, 'POP session not yet started' unless started?
      do_finish
    end
inspect()

Provide human-readable stringification of class state.

[Source]

# File net/pop.rb, line 365
    def inspect
      "#<#{self.class} #{@address}:#{@port} open=#{@started}>"
    end
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.

[Source]

# File 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
n_bytes()

Returns the total size in bytes of all the messages on the POP server.

[Source]

# File net/pop.rb, line 493
    def n_bytes
      return @n_bytes if @n_bytes
      @n_mails, @n_bytes = command().stat
      @n_bytes
    end
n_mails()

Returns the number of messages on the POP server.

[Source]

# File net/pop.rb, line 486
    def n_mails
      return @n_mails if @n_mails
      @n_mails, @n_bytes = command().stat
      @n_mails
    end
read_timeout=( sec )

Set the read timeout.

[Source]

# File net/pop.rb, line 403
    def read_timeout=( sec )
      @command.socket.read_timeout = sec if @command
      @read_timeout = sec
    end
reset()

Resets the session. This clears all "deleted" marks from messages.

This method raises a POPError if an error occurs.

[Source]

# File net/pop.rb, line 559
    def reset
      command().rset
      mails().each do |m|
        m.instance_eval {
          @deleted = false
        }
      end
    end
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

[Source]

# File net/pop.rb, line 382
    def set_debug_output( arg )
      @debug_output = arg
    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.

[Source]

# File 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
started?()

true if the POP3 session has started.

[Source]

# File net/pop.rb, line 409
    def started?
      @started
    end


Module: Net

Module | Net
In: | net/pop.rb

Classes and Modules

Class Net::APOP
Class Net::POP3
Class Net::POPAuthenticationError
Class Net::POPBadResponse
Class Net::POPError
Class Net::POPMail

Constants

POP | = | POP3 | class aliases
POPSession | = | POP3
POP3Session | = | POP3
APOPSession | = | APOP | class aliases


Class: Net::APOP

Class | Net::APOP
In: | 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.

[Source]

# File net/pop.rb, line 586
    def apop?
      true
    end


Class: Net::POPAuthenticationError

Class | Net::POPAuthenticationError
In: | net/pop.rb
Parent: | ProtoAuthError

POP3 authentication error.


Class: Net::POPBadResponse

Class | Net::POPBadResponse
In: | net/pop.rb
Parent: | POPError

Unexpected response from the server.


Class: Net::POPError

Class | Net::POPError
In: | net/pop.rb
Parent: | ProtocolError

Non-authentication POP3 protocol error (reply code "-ERR", except authentication).


Class: Net::POPMail

Class | Net::POPMail
In: | 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

[Source]

# File net/pop.rb, line 716
    def delete
      @command.dele @number
      @deleted = true
    end
delete!()

Alias for delete

deleted?()

True if the mail has been deleted.

[Source]

# File net/pop.rb, line 724
    def deleted?
      @deleted
    end
header( dest = '' )

Fetches the message header.

The optional dest argument is obsolete.

This method raises a POPError if an error occurs.

[Source]

# File net/pop.rb, line 692
    def header( dest = '' )
      top(0, dest)
    end
inspect()

Provide human-readable stringification of class state.

[Source]

# File net/pop.rb, line 618
    def inspect
      "#<#{self.class} #{@number}#{@deleted ? ' deleted' : ''}>"
    end
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.

[Source]

# File 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( 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.

[Source]

# File net/pop.rb, line 680
    def top( lines, dest = '' )
      @command.top(@number, lines) do |chunk|
        dest << chunk
      end
      dest
    end
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.

[Source]

# File net/pop.rb, line 732
    def unique_id
      return @uid if @uid
      @pop.set_all_uids
      @uid
    end


File: pop.rb

pop.rb

Path: | net/pop.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

net/pop.rb

Copyright © 1999-2003 Yukihiro Matsumoto.

Copyright © 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,v 1.62.2.4 2005/09/13 07:27:18 aamine Exp $

See Net::POP3 for documentation.

Required files

net/protocol digest/md5


Class: Net::SMTP

Class | Net::SMTP
In: | 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: 1.69.2.3 $.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.

[Source]

# File net/smtp.rb, line 169
    def SMTP.default_port
      25
    end
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.

[Source]

# File 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
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

[Source]

# File 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

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).

[Source]

# File net/smtp.rb, line 213
    def esmtp=( bool )
      @esmtp = bool
    end
esmtp?()

true if the SMTP object uses ESMTP (which it does by default).

[Source]

# File net/smtp.rb, line 202
    def esmtp?
      @esmtp
    end
finish()

Finishes the SMTP session and closes TCP connection. Raises IOError if not started.

[Source]

# File net/smtp.rb, line 420
    def finish
      raise IOError, 'not yet started' unless started?
      do_finish
    end
inspect()

Provide human-readable stringification of class state.

[Source]

# File net/smtp.rb, line 197
    def inspect
      "#<#{self.class} #{@address}:#{@port} started=#{@started}>"
    end
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

[Source]

# File 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
read_timeout=( sec )

Set the number of seconds to wait until timing-out a read(2) call.

[Source]

# File net/smtp.rb, line 237
    def read_timeout=( sec )
      @socket.read_timeout = sec if @socket
      @read_timeout = sec
    end
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

[Source]

# File net/smtp.rb, line 471
    def send_message( msgstr, from_addr, *to_addrs )
      send0(from_addr, to_addrs.flatten) {
        @socket.write_message msgstr
      }
    end
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

[Source]

# File net/smtp.rb, line 256
    def set_debug_output( arg )
      @debug_output = arg
    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

[Source]

# File 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
started?()

true if the SMTP session has been started.

[Source]

# File net/smtp.rb, line 320
    def started?
      @started
    end


Module: Net

Module | Net
In: | net/smtp.rb

Classes and Modules

Module Net::SMTPError
Class Net::SMTP
Class Net::SMTPAuthenticationError
Class Net::SMTPFatalError
Class Net::SMTPServerBusy
Class Net::SMTPSyntaxError
Class Net::SMTPUnknownError

Constants

SMTPSession = SMTP


Class: Net::SMTPAuthenticationError

Class | Net::SMTPAuthenticationError
In: | net/smtp.rb
Parent: | ProtoAuthError

Represents an SMTP authentication error.

Included Modules

SMTPError


Module: Net::SMTPError

Module | Net::SMTPError
In: | net/smtp.rb

Module mixed in to all SMTP error classes


Class: Net::SMTPFatalError

Class | Net::SMTPFatalError
In: | 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: | 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: | net/smtp.rb
Parent: | ProtoSyntaxError

Represents an SMTP command syntax error (error code 500)

Included Modules

SMTPError


Class: Net::SMTPUnknownError

Class | Net::SMTPUnknownError
In: | net/smtp.rb
Parent: | ProtoUnknownError

Unexpected reply code returned from server.

Included Modules

SMTPError


File: smtp.rb

smtp.rb

Path: | net/smtp.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

net/smtp.rb

Copyright © 1999-2003 Yukihiro Matsumoto.

Copyright © 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,v 1.69.2.3 2005/09/13 07:27:18 aamine Exp $

See Net::SMTP for documentation.

Required files

net/protocol digest/md5


Class: Net::Telnet

Class | Net::Telnet
In: | 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.

[Source]

# File 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

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).

[Source]

# File 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=(mode)

Turn newline conversion on (false) or off (true).

[Source]

# File 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
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.

[Source]

# File 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(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.

[Source]

# File 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
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.

[Source]

# File 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
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.

[Source]

# File 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(string)

Sends a string to the host.

Same as print(), but appends a newline to the string.

[Source]

# File net/telnet.rb, line 633
    def puts(string)
      self.print(string + "\n")
    end
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.

[Source]

# File 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=(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.

[Source]

# File 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
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.

[Source]

# File 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(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.

[Source]

# File 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


Module: Net

Module | Net
In: | net/telnet.rb

Classes and Modules

Class Net::Telnet


File: telnet.rb

telnet.rb

Path: | net/telnet.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

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


Module: NKF

Module | NKF
In: | nkf/nkf.c

Initialize NKF Module

Methods

guess guess1 guess2 nkf

Public Instance methods

guess(p1)

NKF.guess2

Guess Encoding By NKF2.0 Routine

[Source]

/*
 * NKF.guess2
 *
 * Guess Encoding By NKF2.0 Routine
 */

static VALUE
rb_nkf_guess2(obj, src)
  VALUE obj, src;
{
  int code = _BINARY;

  reinit();

  input_ctr = 0;
  StringValue(src);
  input = 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 );
}
guess1(p1)

NKF.guess1

Character code detection - Algorithm described in: Ken Lunde. `Understanding Japanese Information Processing’ Sebastopol, CA: O’Reilly & Associates.

[Source]

/*
 * NKF.guess1
 *
 * Character code detection - Algorithm described in:
 * Ken Lunde. `Understanding Japanese Information Processing'
 * Sebastopol, CA: O'Reilly & Associates.
 */

static VALUE
rb_nkf_guess1(obj, src)
  VALUE obj, src;
{
  unsigned char *p;
  unsigned char *pend;
  int sequence_counter = 0;

  StringValue(src);
  p = 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(p1)

NKF.guess2

Guess Encoding By NKF2.0 Routine

[Source]

/*
 * NKF.guess2
 *
 * Guess Encoding By NKF2.0 Routine
 */

static VALUE
rb_nkf_guess2(obj, src)
  VALUE obj, src;
{
  int code = _BINARY;

  reinit();

  input_ctr = 0;
  StringValue(src);
  input = 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 );
}
nkf(p1, p2)


Module: Kconv

Module | Kconv
In: | nkf/lib/kconv.rb

Methods

guess guess_old iseuc issjis isutf8 kconv toeuc tojis tosjis toutf16 toutf8

Constants

AUTO = ::NKF::AUTO Constant of Encoding
JIS = ::NKF::JIS
EUC = ::NKF::EUC
SJIS = ::NKF::SJIS
BINARY = ::NKF::BINARY
NOCONV = ::NKF::NOCONV
ASCII = ::NKF::ASCII
UTF8 = ::NKF::UTF8
UTF16 = ::NKF::UTF16
UTF32 = ::NKF::UTF32
UNKNOWN = ::NKF::UNKNOWN
Iconv_Shift_JIS = /\A(?: [\x00-\x7f\xa1-\xdf] | \x81[\x40-\x7e\x80-\xac\xb8-\xbf\xc8-\xce\xda-\xe8\xf0-\xf7\xfc] | \x82[\x4f-\x58\x60-\x79\x81-\x9a\x9f-\xf1] | \x83[\x40-\x7e\x80-\x96\x9f-\xb6\xbf-\xd6\x40-\x60] | \x84[\x40-\x60\x70-\x7e\x80-\x91\x9f-\xbe\x9f-\xfc] | [\x89-\x8f\x90-\x97\x99-\x9f\xe0-\xea][\x40-\x7e] | [\x89-\x97\x99-\x9f\xe0-\xe9][\x80-\xfc] | \x98[\x40-\x72\x9f-\xfc] | \xea[\x80-\xa4] )*\z/nx Regexp of Encoding
Iconv_EUC_JP = /\A(?: [\x00-\x7f] | \x8e [\xa1-\xdf] | \x8f [\xa1-\xdf] [\xa1-\xdf] | [\xa1\xb0-\xbce\xd0-\xf3][\xa1-\xfe] | \xa2[\xa1-\xae\xba-\xc1\xca-\xd0\xdc-\xea\xf2-\xf9\xfe] | \xa3[\xb0-\xb9\xc1-\xda\xe1-\xfa] | \xa4[\xa1-\xf3] | \xa5[\xa1-\xf6] | \xa6[\xa1-\xb8\xc1-\xd8] | \xa7[\xa1-\xc1\xd1-\xf1] | \xa8[\xa1-\xc0] | \xcf[\xa1-\xd3] | \xf4[\xa1-\xa6] )*\z/nx
Iconv_UTF8 = /\A(?:\xef\xbb\xbf)?(?: [\x00-\x7f] | \xc2[\x80-\x8d\x90-\x9f\xa1\xaa\xac\xae-\xb1\xb4\xb6\xb8\xba\xbf] | \xc3[\x80-\xbf] | \xc4[\x80-\x93\x96-\xa2\xa4-\xab\xae-\xbf] | \xc5[\x80-\x8d\x90-\xbe] | \xc7[\x8d-\x9c\xb5] | \xcb[\x87\x98-\x9b\x9d] | \xce[\x84-\x86\x88-\x8a\x8c\x8e-\xa1\xa3-\xbf] | \xcf[\x80-\x8e] | \xd0[\x81-\x8c\x8e-\xbf] | \xd1[\x80-\x8f\x91-\x9f] | \xe2\x84[\x83\x96\xa2\xab] | \xe2\x86[\x83\x91-\x93\x96\xa2\xab] | \xe2\x87[\x83\x91-\x94\x96\xa2\xab] | \xe2\x88[\x82-\x83\x87-\x88\x8b\x91-\x94\x96\x9a\x9d-\x9e\xa0\xa2\xa7-\xac\xb4-\xb5\xbd] | \xe2\x89[\x82-\x83\x87-\x88\x8b\x91-\x94\x96\x9a\x9d-\x9e\xa0-\xa2\xa6-\xac\xb4-\xb5\xbd] | \xe2[\x8a\x8c][\x82-\x83\x86-\x88\x8b\x91-\x94\x96\x9a\x9d-\x9e\xa0-\xa2\xa5-\xac\xb4-\xb5\xbd] | \xe2[\x94-\x99][\x81-\x83\x86-\x88\x8b-\x8c\x8f-\x94\x96-\x98\x9a-\x9e\xa0-\xac\xaf-\xb0\xb3-\xb5\xb7-\xb8\xbb-\xbd\xbf] | \xe3\x80[\x81-\x83\x85-\x98\x9a-\x9e\xa0-\xad\xaf-\xb0\xb2-\xb5\xb7-\xb8\xbb-\xbd\xbf] | \xe3[\x81-\x83\xb8-\xbf][\x81-\xbf] | [\xe5-\xe7][\x80-\xbf][\x81-\xbf] | \xe8[\x80-\xae\xb0-\xbf][\x81-\xbf] | \xe9[\x80-\x92\x95-\xb1\xb3-\xbe][\x81-\xbf] | \xef[\xbc-\xbe][\x81-\xbf] | )*\z/nx
RegexpShiftjis = /\A(?: [\x00-\x7f\xa1-\xdf] | [\x81-\x9f\xe0-\xfc][\x40-\x7e\x80-\xfc] )*\z/nx
RegexpEucjp = /\A(?: [\x00-\x7f] | \x8e [\xa1-\xdf] | \x8f [\xa1-\xdf] [\xa1-\xfe] | [\xa1-\xdf] [\xa1-\xfe] )*\z/nx
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

Public Instance methods

guess(str)

guess

[Source]

# File nkf/lib/kconv.rb, line 163
  def guess(str)
    ::NKF::guess(str)
  end
guess_old(str)

[Source]

# File nkf/lib/kconv.rb, line 168
  def guess_old(str)
    ::NKF::guess1(str)
  end
iseuc(str)

isEncoding

[Source]

# File nkf/lib/kconv.rb, line 177
  def iseuc(str)
    RegexpEucjp.match( str )
  end
issjis(str)

[Source]

# File nkf/lib/kconv.rb, line 182
  def issjis(str)
    RegexpShiftjis.match( str )
  end
isutf8(str)

[Source]

# File nkf/lib/kconv.rb, line 187
  def isutf8(str)
    RegexpUtf8.match( str )
  end
kconv(str, out_code, in_code = AUTO)

kconv

[Source]

# File nkf/lib/kconv.rb, line 94
  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
toeuc(str)

[Source]

# File nkf/lib/kconv.rb, line 139
  def toeuc(str)
    ::NKF::nkf('-e', str)
  end
tojis(str)

Encode to

[Source]

# File nkf/lib/kconv.rb, line 134
  def tojis(str)
    ::NKF::nkf('-j', str)
  end
tosjis(str)

[Source]

# File nkf/lib/kconv.rb, line 144
  def tosjis(str)
    ::NKF::nkf('-s', str)
  end
toutf16(str)

[Source]

# File nkf/lib/kconv.rb, line 154
  def toutf16(str)
    ::NKF::nkf('-w16', str)
  end
toutf8(str)

[Source]

# File nkf/lib/kconv.rb, line 149
  def toutf8(str)
    ::NKF::nkf('-w', str)
  end


Class: String

Class | String
In: | nkf/lib/kconv.rb
Parent: | Object

Methods

iseuc issjis isutf8 kconv toeuc tojis tosjis toutf16 toutf8

Public Instance methods

iseuc()

is Encoding

[Source]

# File nkf/lib/kconv.rb, line 217
  def iseuc
    Kconv.iseuc( self )
  end
issjis()

[Source]

# File nkf/lib/kconv.rb, line 221
  def issjis
    Kconv.issjis( self )
  end
isutf8()

[Source]

# File nkf/lib/kconv.rb, line 225
  def isutf8
    Kconv.isutf8( self )
  end
kconv(out_code, in_code=Kconv::AUTO)

[Source]

# File nkf/lib/kconv.rb, line 195
  def kconv(out_code, in_code=Kconv::AUTO)
    Kconv::kconv(self, out_code, in_code)
  end
toeuc()

[Source]

# File nkf/lib/kconv.rb, line 203
  def toeuc
    ::NKF::nkf('-e', self)
  end
tojis()

to Encoding

[Source]

# File nkf/lib/kconv.rb, line 200
  def tojis
    ::NKF::nkf('-j', self)
  end
tosjis()

[Source]

# File nkf/lib/kconv.rb, line 206
  def tosjis
    ::NKF::nkf('-s', self)
  end
toutf16()

[Source]

# File nkf/lib/kconv.rb, line 212
  def toutf16
    ::NKF::nkf('-w16', self)
  end
toutf8()

[Source]

# File nkf/lib/kconv.rb, line 209
  def toutf8
    ::NKF::nkf('-w', self)
  end


File: kconv.rb

kconv.rb

Path: | nkf/lib/kconv.rb
Last Update: | Sat Oct 15 23:43:53 AUS Eastern Standard Time 2005

Required files

nkf


File: nkf.c

nkf.c

Path: | nkf/nkf-utf8/nkf.c
Last Update: | Sat Oct 15 23:43:53 AUS Eastern Standard Time 2005


File: utf8tbl.c

utf8tbl.c

Path: | nkf/nkf-utf8/utf8tbl.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: nkf.c

nkf.c

Path: | nkf/nkf.c
Last Update: | Sat Oct 15 23:43:53 AUS Eastern Standard Time 2005


File: test.rb

test.rb

Path: | nkf/test.rb
Last Update: | Sat Oct 15 23:43:53 AUS Eastern Standard Time 2005

nkf test program for nkf-2

$Id: test.rb,v 1.2.8.3 2004/12/03 18:01:05 naruse Exp $

   Shinji KONO <kono@ie.u-ryukyu.ac.jp>

Sun Aug 18 12:25:40 JST 1996 Sun Nov 8 00:16:06 JST 1998

This is useful when you add new patch on nkf. Since this test is too strict, faileurs may not mean wrong conversion.

nkf 1.5 differs on MIME decoding nkf 1.4 passes Basic Conversion tests nkf PDS version passes Basic Conversion tests using "nkf -iB -oB "

Required files

nkf

Methods

result test

Included Modules

NKF

Public Instance methods

result(result, message = nil)

[Source]

# File nkf/test.rb, line 21
def result(result, message = nil)
  $counter += 1
  printf("%s %d%s\n",
         result ? 'ok' : 'no',
         $counter,
         message ? ' ... ' + message : '')
end
test(opt, input, expects)

[Source]

# File nkf/test.rb, line 71
def test(opt, input, expects)
  print "\nINPUT:\n", input if $detail
  print "\nEXPECT:\n", expects.to_s if $detail
  result = nkf(opt, input)
  result.delete!(' ') if opt.include?('-m')
  print "\nGOT:\n", result if $detail

  expects.each do |e|
    e.delete!(' ') if opt.include?('-m')
    if result == e then
      puts "Ok"
      return result
    end
  end
  puts "Fail"
  puts result.unpack('H*').first
  puts expects.map{|x|x.unpack('H*').first}.join("\n\n")
end


File: observer.rb

observer.rb

Path: | observer.rb
Last Update: | Sat Oct 15 23:44:27 AUS Eastern Standard Time 2005

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


Module: Observable

Module | Observable
In: | 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.

[Source]

# File 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
changed(state=true)

Set the changed state of this object. Notifications will be sent only if the changed state is true.

[Source]

# File observer.rb, line 161
  def changed(state=true)
    @observer_state = state
  end
changed?()

Query the changed state of this object.

[Source]

# File observer.rb, line 168
  def changed?
    if defined? @observer_state and @observer_state
      true
    else
      false
    end
  end
count_observers()

Return the number of observers associated with this object.

[Source]

# File observer.rb, line 149
  def count_observers
    if defined? @observer_peers
      @observer_peers.size
    else
      0
    end
  end
delete_observer(observer)

Delete observer as an observer on this object. It will no longer receive notifications.

[Source]

# File observer.rb, line 135
  def delete_observer(observer)
    @observer_peers.delete observer if defined? @observer_peers
  end
delete_observers()

Delete all observers associated with this object.

[Source]

# File observer.rb, line 142
  def delete_observers
    @observer_peers.clear if defined? @observer_peers
  end
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.

[Source]

# File 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


File: open-uri.rb

open-uri.rb

Path: | open-uri.rb
Last Update: | Sat Oct 15 23:44:27 AUS Eastern Standard Time 2005

open-uri.rb

open-uri.rb is easy-to-use wrapper for net/http, net/https and net/ftp.

Example

It is possible to open http/https/ftp URL as usual 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 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>

Required files

uri stringio time net/http net/https tempfile socket net/ftp


Module: Kernel

Module | Kernel
In: | open-uri.rb

Methods

open

External Aliases

open -> open_uri_original_open

Private Instance methods

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.

[Source]

# File open-uri.rb, line 80
  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


Module: OpenURI

Module | OpenURI
In: | open-uri.rb

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: | open-uri.rb
Parent: | StandardError

Methods

new

Attributes

io [R]

Public Class methods

new(message, io)

[Source]

# File open-uri.rb, line 295
    def initialize(message, io)
      super(message)
      @io = io
    end


Module: OpenURI::Meta

Module | OpenURI::Meta
In: | 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.

[Source]

# File open-uri.rb, line 410
    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()

returns a list of encodings in Content-Encoding field as an Array of String. The encodings are downcased for canonicalization.

[Source]

# File open-uri.rb, line 427
    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
content_type()

returns "type/subtype" which is MIME Content-Type. It is downcased for canonicalization. Content-Type parameters are stripped.

[Source]

# File open-uri.rb, line 395
    def content_type
      type, *parameters = content_type_parse
      type || 'application/octet-stream'
    end
last_modified()

returns a Time which represents Last-Modified field.

[Source]

# File open-uri.rb, line 362
    def last_modified
      if v = @meta['last-modified']
        Time.httpdate(v)
      else
        nil
      end
    end


Module: OpenURI::OpenRead

Module | OpenURI::OpenRead
In: | 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.

[Source]

# File open-uri.rb, line 530
    def open(*rest, &block)
      OpenURI.open_uri(self, *rest, &block)
    end
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.

[Source]

# File open-uri.rb, line 538
    def read(options={})
      self.open(options) {|f|
        str = f.read
        Meta.init str, f
        str
      }
    end


Module: URI

Module | URI
In: | open-uri.rb

Classes and Modules

Class URI::FTP
Class URI::Generic
Class URI::HTTP


Class: URI::FTP

Class | URI::FTP
In: | open-uri.rb
Parent: | Object

Included Modules

OpenURI::OpenRead


Class: URI::Generic

Class | URI::Generic
In: | open-uri.rb
Parent: | Object

Methods

find_proxy

Public Instance methods

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.

[Source]

# File open-uri.rb, line 563
    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


Class: URI::HTTP

Class | URI::HTTP
In: | open-uri.rb
Parent: | Object

Included Modules

OpenURI::OpenRead


Module: Open3

Module | Open3
In: | open3.rb

open3.rb: Spawn a program like popen, but with stderr, too. You might also want to use this if you want to bypass the shell. (By passing multiple args, which IO#popen does not allow)

Usage:

      require "open3"

     stdin, stdout, stderr = Open3.popen3('nroff -man')
 or
      include Open3
     stdin, stdout, stderr = popen3('nroff -man')

Methods

popen3

Public Instance methods

popen3(*cmd) {|| ...}
stdin, stdout, stderr
= popen3(command);

[Source]

# File open3.rb, line 15
  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


File: open3.rb

open3.rb

Path: | open3.rb
Last Update: | Sat Oct 15 23:44:27 AUS Eastern Standard Time 2005

open3.rb: Spawn a program like popen, but with stderr, too. You might also want to use this if you want to bypass the shell. (By passing multiple args, which IO#popen does not allow)

Usage:

      require "open3"

     stdin, stdout, stderr = Open3.popen3('nroff -man')
 or
      include Open3
     stdin, stdout, stderr = popen3('nroff -man')


Module: OpenSSL

Module | OpenSSL
In: | openssl/ossl.c openssl/lib/openssl/x509.rb openssl/lib/openssl/ssl.rb openssl/lib/openssl/digest.rb openssl/lib/openssl/cipher.rb openssl/lib/openssl/bn.rb
 Should we care what if somebody require this file directly?

require ‘openssl’

Methods

debug debug= errors

Classes and Modules

Module OpenSSL::Cipher
Module OpenSSL::Digest
Module OpenSSL::SSL
Module OpenSSL::X509
Class OpenSSL::BN
Class OpenSSL::OpenSSLError

Public Instance methods

debug()
debug=(p1)
errors()


Module: Buffering

Module | Buffering
In: | openssl/lib/openssl/buffering.rb

Methods

<< close each each_byte each_line eof eof? flush getc gets new print printf puts read readchar readline readlines readpartial ungetc write

Included Modules

Enumerable

Constants

BLOCK_SIZE = 1024*16

Attributes

sync [RW]

Public Class methods

new(*args)

[Source]

# File openssl/lib/openssl/buffering.rb, line 22
  def initialize(*args)
    @eof = false
    @rbuffer = ""
    @sync = @io.sync
  end

Public Instance methods

<<(s)

[Source]

# File openssl/lib/openssl/buffering.rb, line 196
  def << (s)
    do_write(s)
    self
  end
close()

[Source]

# File openssl/lib/openssl/buffering.rb, line 235
  def close
    flush rescue nil
    sysclose
  end
each(eol=$/) {|line| ...}

[Source]

# File openssl/lib/openssl/buffering.rb, line 117
  def each(eol=$/)
    while line = self.gets(eol)
      yield line
    end
  end
each_byte() {|c| ...}

[Source]

# File openssl/lib/openssl/buffering.rb, line 142
  def each_byte
    while c = getc
      yield(c)
    end
  end
each_line(eol=$/)

Alias for each

eof()

Alias for eof?

eof?()

[Source]

# File openssl/lib/openssl/buffering.rb, line 157
  def eof?
    fill_rbuff if !@eof && @rbuffer.empty?
    @eof && @rbuffer.empty?
  end
flush()

[Source]

# File openssl/lib/openssl/buffering.rb, line 228
  def flush
    osync = @sync
    @sync = true
    do_write ""
    @sync = osync
  end
getc()

[Source]

# File openssl/lib/openssl/buffering.rb, line 137
  def getc
    c = read(1)
    c ? c[0] : nil
  end
gets(eol=$/)

[Source]

# File openssl/lib/openssl/buffering.rb, line 102
  def gets(eol=$/)
    idx = @rbuffer.index(eol)
    until @eof
      break if idx
      fill_rbuff
      idx = @rbuffer.index(eol)
    end
    if eol.is_a?(Regexp)
      size = idx ? idx+$&.size : nil
    else
      size = idx ? idx+eol.size : nil
    end
    consume_rbuff(size)
  end
print(*args)

[Source]

# File openssl/lib/openssl/buffering.rb, line 216
  def print(*args)
    s = ""
    args.each{ |arg| s << arg.to_s }
    do_write(s)
    nil
  end
printf(s, *args)

[Source]

# File openssl/lib/openssl/buffering.rb, line 223
  def printf(s, *args)
    do_write(s % args)
    nil
  end
puts(*args)

[Source]

# File openssl/lib/openssl/buffering.rb, line 201
  def puts(*args)
    s = ""
    if args.empty?
      s << "\n"
    end
    args.each{|arg|
      s << arg.to_s
      if $/ && /\n\z/ !~ s
        s << "\n"
      end
    }
    do_write(s)
    nil
  end
read(size=nil, buf=nil)

[Source]

# File openssl/lib/openssl/buffering.rb, line 56
  def read(size=nil, buf=nil)
    if size == 0
      if buf
        buf.clear
      else
        buf = ""
      end
      return @eof ? nil : buf
    end
    until @eof
      break if size && size <= @rbuffer.size
      fill_rbuff
    end
    ret = consume_rbuff(size) || ""
    if buf
      buf.replace(ret)
      ret = buf
    end
    (size && ret.empty?) ? nil : ret
  end
readchar()

[Source]

# File openssl/lib/openssl/buffering.rb, line 148
  def readchar
    raise EOFError if eof?
    getc
  end
readline(eol=$/)

[Source]

# File openssl/lib/openssl/buffering.rb, line 132
  def readline(eol=$/)
    raise EOFError if eof?
    gets(eol)
  end
readlines(eol=$/)

[Source]

# File openssl/lib/openssl/buffering.rb, line 124
  def readlines(eol=$/)
    ary = []
    while line = self.gets(eol)
      ary << line
    end
    ary
  end
readpartial(maxlen, buf=nil)

[Source]

# File openssl/lib/openssl/buffering.rb, line 77
  def readpartial(maxlen, buf=nil)
    if maxlen == 0
      if buf
        buf.clear
      else
        buf = ""
      end
      return @eof ? nil : buf
    end
    if @rbuffer.empty?
      begin
        return sysread(maxlen, buf)
      rescue Errno::EAGAIN
        retry
      end
    end
    ret = consume_rbuff(maxlen)
    if buf
      buf.replace(ret)
      ret = buf
    end
    raise EOFError if ret.empty?
    ret
  end
ungetc(c)

[Source]

# File openssl/lib/openssl/buffering.rb, line 153
  def ungetc(c)
    @rbuffer[0,0] = c.chr
  end
write(s)

[Source]

# File openssl/lib/openssl/buffering.rb, line 191
  def write(s)
    do_write(s)
    s.length
  end


Class: Integer

Class | Integer
In: | openssl/lib/openssl/bn.rb
Parent: | Object

Add double dispatch to Integer

Methods

to_bn

Public Instance methods

to_bn()

[Source]

# File openssl/lib/openssl/bn.rb, line 31
  def to_bn
    OpenSSL::BN::new(self)
  end


Module: Net

Module | Net
In: | openssl/lib/net/telnets.rb openssl/lib/net/ftptls.rb

Classes and Modules

Class Net::FTPTLS
Class Net::Telnet


Class: Net::FTPTLS

Class | Net::FTPTLS
In: | openssl/lib/net/ftptls.rb
Parent: | FTP

Methods

login

Public Instance methods

login(user = "anonymous", passwd = nil, acct = nil)

[Source]

# File openssl/lib/net/ftptls.rb, line 32
    def login(user = "anonymous", passwd = nil, acct = nil)
       ctx = OpenSSL::SSL::SSLContext.new('SSLv23')
       ctx.key = nil
       ctx.cert = nil
       voidcmd("AUTH TLS")
       @sock = OpenSSL::SSL::SSLSocket.new(@sock, ctx)
       @sock.connect
       super(user, passwd, acct)
       voidcmd("PBSZ 0")
    end


Class: Net::Telnet

Class | Net::Telnet
In: | openssl/lib/net/telnets.rb
Parent: | Object

Methods

preprocess ssl? waitfor

Constants

OPT_STARTTLS | = | 46.chr # "\056" # "\x2e" # Start TLS
TLS_FOLLOWS | = | 1.chr # "\001" # "\x01" # FOLLOWS (for STARTTLS)

External Aliases

preprocess | -> | preprocess_orig
waitfor | -> | waitfor_org

Attributes

ssl [R]

Public Instance methods

preprocess(string)

[Source]

# File openssl/lib/net/telnets.rb, line 70
    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_EXOPL}]|
                   #{SB}[#{OPT_BINARY}-#{OPT_EXOPL}]
                     (#{IAC}#{IAC}|[^#{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)
          elsif OPT_STARTTLS[0] == $1[1]
            self.write(IAC + WILL + OPT_STARTTLS)
            self.write(IAC + SB + OPT_STARTTLS + TLS_FOLLOWS + IAC + SE)
          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
          ''
        elsif SB[0] == $1[0]    # respond to "IAC SB xxx IAC SE"
          if    OPT_STARTTLS[0] == $1[1] && TLS_FOLLOWS[0] == $2[0]
            @sock = OpenSSL::SSL::SSLSocket.new(@sock)
            @sock.cert            = @options['Cert'] unless @sock.cert
            @sock.key             = @options['Key'] unless @sock.key
            @sock.ca_cert         = @options['CACert']
            @sock.ca_file         = @options['CAFile']
            @sock.ca_path         = @options['CAPath']
            @sock.timeout         = @options['Timeout']
            @sock.verify_mode     = @options['VerifyMode']
            @sock.verify_callback = @options['VerifyCallback']
            @sock.verify_depth    = @options['VerifyDepth']
            @sock.connect
            @ssl = true
          end
          ''
        else
          ''
        end
      end
    end
ssl?()

[Source]

# File openssl/lib/net/telnets.rb, line 68
    def ssl?; @ssl; end
waitfor(options) {|buf if block_given?| ...}

[Source]

# File openssl/lib/net/telnets.rb, line 148
    def waitfor(options)
      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 = '' unless @rest

      until(prompt === line and not IO::select([@sock], nil, nil, waittime))
        unless IO::select([@sock], nil, nil, time_out)
          raise TimeoutError, "timed-out; wait for the next data"
        end
        begin
          c = @rest + @sock.sysread(1024 * 1024)
          @dumplog.log_dump('<', c) if @options.has_key?("Dump_log")
          if @options["Telnetmode"]
            pos = 0
            catch(:next){
              while true
                case c[pos]
                when IAC[0]
                  case c[pos+1]
                  when DO[0], DONT[0], WILL[0], WONT[0]
                    throw :next unless c[pos+2]
                    pos += 3
                  when SB[0]
                    ret = detect_sub_negotiation(c, pos)
                    throw :next unless ret
                    pos = ret
                  when nil
                    throw :next
                  else
                    pos += 2
                  end
                when nil
                  throw :next
                else
                  pos += 1
                end
              end
            }

            buf = preprocess(c[0...pos])
            @rest = c[pos..-1]
          end
          @log.print(buf) if @options.has_key?("Output_log")
          line.concat(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


Class: OpenSSL::BN

Class | OpenSSL::BN
In: | openssl/lib/openssl/bn.rb
Parent: | Object

Included Modules

Comparable


Module: OpenSSL::Cipher

Module | OpenSSL::Cipher
In: | openssl/lib/openssl/cipher.rb

Classes and Modules

Class OpenSSL::Cipher::Cipher


Class: OpenSSL::Cipher::Cipher

Class | OpenSSL::Cipher::Cipher
In: | openssl/lib/openssl/cipher.rb
Parent: | Object

Methods

random_iv random_key

Public Instance methods

random_iv()

[Source]

# File openssl/lib/openssl/cipher.rb, line 46
      def random_iv
        str = OpenSSL::Random.random_bytes(self.iv_len)
        self.iv = str
        return str
      end
random_key()

[Source]

# File openssl/lib/openssl/cipher.rb, line 40
      def random_key
        str = OpenSSL::Random.random_bytes(self.key_len)
        self.key = str
        return str
      end


Module: OpenSSL::Digest

Module | OpenSSL::Digest
In: | openssl/lib/openssl/digest.rb


Class: OpenSSL::OpenSSLError

Class | OpenSSL::OpenSSLError
In: | openssl/ossl.c
Parent: | StandardError


Module: OpenSSL::SSL

Module | OpenSSL::SSL
In: | openssl/lib/openssl/ssl.rb

Classes and Modules

Module OpenSSL::SSL::Nonblock
Module OpenSSL::SSL::SocketForwarder
Class OpenSSL::SSL::SSLServer
Class OpenSSL::SSL::SSLSocket


Module: OpenSSL::SSL::Nonblock

Module | OpenSSL::SSL::Nonblock
In: | openssl/lib/openssl/ssl.rb

Methods

new

Public Class methods

new(*args)

[Source]

# File openssl/lib/openssl/ssl.rb, line 54
      def initialize(*args)
        flag = File::NONBLOCK
        flag |= @io.fcntl(Fcntl::F_GETFL) if defined?(Fcntl::F_GETFL)
        @io.fcntl(Fcntl::F_SETFL, flag)
        super
      end


Class: OpenSSL::SSL::SSLServer

Class | OpenSSL::SSL::SSLServer
In: | openssl/lib/openssl/ssl.rb
Parent: | Object

Methods

accept close listen new to_io

Included Modules

SocketForwarder

Attributes

start_immediately [RW]

Public Class methods

new(svr, ctx)

[Source]

# File openssl/lib/openssl/ssl.rb, line 98
      def initialize(svr, ctx)
        @svr = svr
        @ctx = ctx
        unless ctx.session_id_context
          session_id = OpenSSL::Digest::MD5.hexdigest($0)
          @ctx.session_id_context = session_id
        end
        @start_immediately = true
      end

Public Instance methods

accept()

[Source]

# File openssl/lib/openssl/ssl.rb, line 116
      def accept
        sock = @svr.accept
        begin
          ssl = OpenSSL::SSL::SSLSocket.new(sock, @ctx)
          ssl.sync_close = true
          ssl.accept if @start_immediately
          ssl
        rescue SSLError => ex
          sock.close
          raise ex
        end
      end
close()

[Source]

# File openssl/lib/openssl/ssl.rb, line 129
      def close
        @svr.close
      end
listen(backlog=5)

[Source]

# File openssl/lib/openssl/ssl.rb, line 112
      def listen(backlog=5)
        @svr.listen(backlog)
      end
to_io()

[Source]

# File openssl/lib/openssl/ssl.rb, line 108
      def to_io
        @svr
      end


Class: OpenSSL::SSL::SSLSocket

Class | OpenSSL::SSL::SSLSocket
In: | openssl/lib/openssl/ssl.rb
Parent: | Object

Methods

post_connection_check

Included Modules

Buffering SocketForwarder Nonblock

Public Instance methods

post_connection_check(hostname)

[Source]

# File openssl/lib/openssl/ssl.rb, line 67
      def post_connection_check(hostname)
        check_common_name = true
        cert = peer_cert
        cert.extensions.each{|ext|
          next if ext.oid != "subjectAltName"
          ext.value.split(/,\s+/).each{|general_name|
            if /\ADNS:(.*)/ =~ general_name
              check_common_name = false
              reg = Regexp.escape($1).gsub(/\\\*/, "[^.]+")
              return true if /\A#{reg}\z/i =~ hostname
            elsif /\AIP Address:(.*)/ =~ general_name
              check_common_name = false
              return true if $1 == hostname
            end
          }
        }
        if check_common_name
          cert.subject.to_a.each{|oid, value|
            if oid == "CN" && value.casecmp(hostname) == 0
              return true
            end
          }
        end
        raise SSLError, "hostname not match"
      end


Module: OpenSSL::SSL::SocketForwarder

Module | OpenSSL::SSL::SocketForwarder
In: | openssl/lib/openssl/ssl.rb

Methods

addr closed? do_not_reverse_lookup= fcntl getsockopt peeraddr setsockopt

Public Instance methods

addr()

[Source]

# File openssl/lib/openssl/ssl.rb, line 24
      def addr
        to_io.addr
      end
closed?()

[Source]

# File openssl/lib/openssl/ssl.rb, line 44
      def closed?
        to_io.closed?
      end
do_not_reverse_lookup=(flag)

[Source]

# File openssl/lib/openssl/ssl.rb, line 48
      def do_not_reverse_lookup=(flag)
        to_io.do_not_reverse_lookup = flag
      end
fcntl(*args)

[Source]

# File openssl/lib/openssl/ssl.rb, line 40
      def fcntl(*args)
        to_io.fcntl(*args)
      end
getsockopt(level, optname, optval)

[Source]

# File openssl/lib/openssl/ssl.rb, line 32
      def getsockopt(level, optname, optval)
        to_io.setsockopt(level, optname, optval)
      end
peeraddr()

[Source]

# File openssl/lib/openssl/ssl.rb, line 28
      def peeraddr
        to_io.peeraddr
      end
setsockopt(level, optname)

[Source]

# File openssl/lib/openssl/ssl.rb, line 36
      def setsockopt(level, optname)
        to_io.setsockopt(level, optname)
      end


Module: OpenSSL::X509

Module | OpenSSL::X509
In: | openssl/lib/openssl/x509.rb

Classes and Modules

Class OpenSSL::X509::Extension
Class OpenSSL::X509::ExtensionFactory
Class OpenSSL::X509::Name


Class: OpenSSL::X509::Extension

Class | OpenSSL::X509::Extension
In: | openssl/lib/openssl/x509.rb
Parent: | Object

Methods

to_a to_h to_s

Public Instance methods

to_a()

[Source]

# File openssl/lib/openssl/x509.rb, line 59
      def to_a
        [ self.oid, self.value, self.critical? ]
      end
to_h(

[Source]

# File openssl/lib/openssl/x509.rb, line 55
      def to_h # {"oid"=>sn|ln, "value"=>value, "critical"=>true|false}
        {"oid"=>self.oid,"value"=>self.value,"critical"=>self.critical?}
      end
to_s(

[Source]

# File openssl/lib/openssl/x509.rb, line 48
      def to_s # "oid = critical, value"
        str = self.oid
        str << " = "
        str << "critical, " if self.critical?
        str << self.value.gsub(/\n/, ", ")
      end


Class: OpenSSL::X509::ExtensionFactory

Class | OpenSSL::X509::ExtensionFactory
In: | openssl/lib/openssl/x509.rb
Parent: | Object

Methods

create_ext_from_array create_ext_from_hash create_ext_from_string create_extension

Public Instance methods

create_ext_from_array(ary)

[Source]

# File openssl/lib/openssl/x509.rb, line 30
      def create_ext_from_array(ary)
        raise ExtensionError, "unexpected array form" if ary.size > 3
        create_ext(ary[0], ary[1], ary[2])
      end
create_ext_from_hash(hash)

[Source]

# File openssl/lib/openssl/x509.rb, line 42
      def create_ext_from_hash(hash)
        create_ext(hash["oid"], hash["value"], hash["critical"])
      end
create_ext_from_string(str)

[Source]

# File openssl/lib/openssl/x509.rb, line 35
      def create_ext_from_string(str) # "oid = critical, value"
        oid, value = str.split(/=/, 2)
        oid.strip!
        value.strip!
        create_ext(oid, value)
      end
create_extension(*arg)

[Source]

# File openssl/lib/openssl/x509.rb, line 22
      def create_extension(*arg)
        if arg.size > 1
          create_ext(*arg)
        else
          send("create_ext_from_"+arg[0].class.name.downcase, arg[0])
        end
      end


Class: OpenSSL::X509::Name

Class | OpenSSL::X509::Name
In: | openssl/lib/openssl/x509.rb
Parent: | Object

Methods

parse_openssl parse_rfc2253

Classes and Modules

Module OpenSSL::X509::Name::RFC2253DN

External Aliases

parse_openssl -> parse

Public Class methods

parse_openssl(str, template=OBJECT_TYPE_TEMPLATE)

[Source]

# File openssl/lib/openssl/x509.rb, line 145
        def parse_openssl(str, template=OBJECT_TYPE_TEMPLATE)
          ary = str.scan(/\s*([^\/,]+)\s*/).collect{|i| i[0].split("=", 2) }
          self.new(ary, template)
        end
parse_rfc2253(str, template=OBJECT_TYPE_TEMPLATE)

[Source]

# File openssl/lib/openssl/x509.rb, line 140
        def parse_rfc2253(str, template=OBJECT_TYPE_TEMPLATE)
          ary = OpenSSL::X509::Name::RFC2253DN.scan(str)
          self.new(ary, template)
        end


Module: OpenSSL::X509::Name::RFC2253DN

Module | OpenSSL::X509::Name::RFC2253DN
In: | openssl/lib/openssl/x509.rb

Methods

expand_hexstring expand_pair expand_value scan

Constants

Special | = | ',=+<>#;'
HexChar | = | /[0-9a-fA-F]/
HexPair | = | /#{HexChar}#{HexChar}/
HexString | = | /#{HexPair}+/
Pair | = | /\\(?:[#{Special}]|\\|"|#{HexPair})/
StringChar | = | /[^#{Special}\\"]/
QuoteChar | = | /[^\\"]/
AttributeType | = | /[a-zA-Z][0-9a-zA-Z]*|[0-9]+(?:\.[0-9]+)*/
AttributeValue | = | / (?!["#])((?:#{StringChar}|#{Pair})*)| \#(#{HexString})| "((?:#{QuoteChar}|#{Pair})*)" /x
TypeAndValue | = | /\A(#{AttributeType})=#{AttributeValue}/

Public Instance methods

expand_hexstring(str)

[Source]

# File openssl/lib/openssl/x509.rb, line 94
        def expand_hexstring(str)
          return nil unless str
          der = str.gsub(HexPair){|hex| Integer("0x#{hex}").chr }
          a1 = OpenSSL::ASN1.decode(der)
          return a1.value, a1.tag
        end
expand_pair(str)

[Source]

# File openssl/lib/openssl/x509.rb, line 83
        def expand_pair(str)
          return nil unless str
          return str.gsub(Pair){|pair|
            case pair.size
            when 2 then pair[1,1]
            when 3 then Integer("0x#{pair[1,2]}").chr
            else raise OpenSSL::X509::NameError, "invalid pair: #{str}"
            end
          }
        end
expand_value(str1, str2, str3)

[Source]

# File openssl/lib/openssl/x509.rb, line 101
        def expand_value(str1, str2, str3)
          value = expand_pair(str1)
          value, tag = expand_hexstring(str2) unless value
          value = expand_pair(str3) unless value
          return value, tag
        end
scan(dn)

[Source]

# File openssl/lib/openssl/x509.rb, line 108
        def scan(dn)
          str = dn
          ary = []
          while true
            if md = TypeAndValue.match(str)
              matched = md.to_s
              remain = md.post_match
              type = md[1]
              value, tag = expand_value(md[2], md[3], md[4]) rescue nil
              if value
                type_and_value = [type, value]
                type_and_value.push(tag) if tag
                ary.unshift(type_and_value)
                if remain.length > 2 && remain[0] == ?,
                  str = remain[1..-1]
                  next
                elsif remain.length > 2 && remain[0] == ?+
                  raise OpenSSL::X509::NameError,
                    "multi-valued RDN is not supported: #{dn}"
                elsif remain.empty?
                  break
                end
              end
            end
            msg_dn = dn[0, dn.length - str.length] + " =>" + str
            raise OpenSSL::X509::NameError, "malformed RDN: #{msg_dn}"
          end
          return ary
        end


Class: cASN1ObjectId

Class | cASN1ObjectId
In: |

External Aliases

sn | -> | short_name
ln | -> | long_name


Class: cBN

Class | cBN
In: |

External Aliases

cmp | -> | <=>
eql? | -> | ==
eql? | -> | ===
to_i | -> | to_int


Class: cDH

Class | cDH
In: |

External Aliases

export | -> | to_pem
export | -> | to_s


Class: cDSA

Class | cDSA
In: |

External Aliases

export | -> | to_pem
export | -> | to_s


Class: cDigest

Class | cDigest
In: |

External Aliases

hexdigest | -> | inspect
hexdigest | -> | to_s
update | -> | <<


Class: cHMAC

Class | cHMAC
In: |

External Aliases

update | -> | <<
hexdigest | -> | inspect
hexdigest | -> | to_s


Class: cPKCS7

Class | cPKCS7
In: |

External Aliases

add_data | -> | data=
to_pem | -> | to_s


Class: cPKCS7Signer

Class | cPKCS7Signer
In: |

External Aliases

issuer -> name


Class: cRSA

Class | cRSA
In: |

External Aliases

export | -> | to_pem
export | -> | to_s


Class: cSPKI

Class | cSPKI
In: |

External Aliases

to_pem -> to_s


Class: cSSLSocket

Class | cSSLSocket
In: |

External Aliases

io -> to_io


Class: cX509CRL

Class | cX509CRL
In: |

External Aliases

to_pem -> to_s


Class: cX509Cert

Class | cX509Cert
In: |

External Aliases

to_pem -> to_s


Class: cX509Name

Class | cX509Name
In: |

External Aliases

cmp -> <=>


Class: cX509Req

Class | cX509Req
In: |

External Aliases

to_pem -> to_s


File: ftptls.rb

ftptls.rb

Path: | openssl/lib/net/ftptls.rb
Last Update: | Thu Jul 24 02:11:30 AUS Eastern Standard Time 2003

Required files

socket openssl net/ftp


File: telnets.rb

telnets.rb

Path: | openssl/lib/net/telnets.rb
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005

Required files

net/telnet openssl


File: openssl.rb

openssl.rb

Path: | openssl/lib/openssl.rb
Last Update: | Thu Jul 24 02:11:29 AUS Eastern Standard Time 2003

Required files

openssl.so openssl/bn openssl/cipher openssl/digest openssl/ssl openssl/x509


File: bn.rb

bn.rb

Path: | openssl/lib/openssl/bn.rb
Last Update: | Thu Jul 24 02:11:30 AUS Eastern Standard Time 2003


File: buffering.rb

buffering.rb

Path: | openssl/lib/openssl/buffering.rb
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: cipher.rb

cipher.rb

Path: | openssl/lib/openssl/cipher.rb
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: digest.rb

digest.rb

Path: | openssl/lib/openssl/digest.rb
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: ssl.rb

ssl.rb

Path: | openssl/lib/openssl/ssl.rb
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005

Required files

openssl openssl/buffering fcntl


File: x509.rb

x509.rb

Path: | openssl/lib/openssl/x509.rb
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005

Required files

openssl


File: openssl_missing.c

openssl_missing.c

Path: | openssl/openssl_missing.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: ossl.c

ossl.c

Path: | openssl/ossl.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: ossl_asn1.c

ossl_asn1.c

Path: | openssl/ossl_asn1.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: ossl_bio.c

ossl_bio.c

Path: | openssl/ossl_bio.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: ossl_bn.c

ossl_bn.c

Path: | openssl/ossl_bn.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: ossl_cipher.c

ossl_cipher.c

Path: | openssl/ossl_cipher.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: ossl_config.c

ossl_config.c

Path: | openssl/ossl_config.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: ossl_digest.c

ossl_digest.c

Path: | openssl/ossl_digest.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: ossl_engine.c

ossl_engine.c

Path: | openssl/ossl_engine.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: ossl_hmac.c

ossl_hmac.c

Path: | openssl/ossl_hmac.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: ossl_ns_spki.c

ossl_ns_spki.c

Path: | openssl/ossl_ns_spki.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: ossl_ocsp.c

ossl_ocsp.c

Path: | openssl/ossl_ocsp.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: ossl_pkcs12.c

ossl_pkcs12.c

Path: | openssl/ossl_pkcs12.c
Last Update: | Mon Dec 15 10:30:12 AUS Eastern Daylight Time 2003


File: ossl_pkcs7.c

ossl_pkcs7.c

Path: | openssl/ossl_pkcs7.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: ossl_pkey.c

ossl_pkey.c

Path: | openssl/ossl_pkey.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: ossl_pkey_dh.c

ossl_pkey_dh.c

Path: | openssl/ossl_pkey_dh.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: ossl_pkey_dsa.c

ossl_pkey_dsa.c

Path: | openssl/ossl_pkey_dsa.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: ossl_pkey_rsa.c

ossl_pkey_rsa.c

Path: | openssl/ossl_pkey_rsa.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: ossl_rand.c

ossl_rand.c

Path: | openssl/ossl_rand.c
Last Update: | Wed Sep 17 19:05:02 AUS Eastern Standard Time 2003


File: ossl_ssl.c

ossl_ssl.c

Path: | openssl/ossl_ssl.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: ossl_x509.c

ossl_x509.c

Path: | openssl/ossl_x509.c
Last Update: | Mon Sep 08 20:31:38 AUS Eastern Standard Time 2003


File: ossl_x509attr.c

ossl_x509attr.c

Path: | openssl/ossl_x509attr.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: ossl_x509cert.c

ossl_x509cert.c

Path: | openssl/ossl_x509cert.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: ossl_x509crl.c

ossl_x509crl.c

Path: | openssl/ossl_x509crl.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: ossl_x509ext.c

ossl_x509ext.c

Path: | openssl/ossl_x509ext.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: ossl_x509name.c

ossl_x509name.c

Path: | openssl/ossl_x509name.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: ossl_x509req.c

ossl_x509req.c

Path: | openssl/ossl_x509req.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: ossl_x509revoked.c

ossl_x509revoked.c

Path: | openssl/ossl_x509revoked.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: ossl_x509store.c

ossl_x509store.c

Path: | openssl/ossl_x509store.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


Class: OptionParser

Class | OptionParser
In: | optparse.rb
Parent: | Object

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 example below.

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

Note: some bugs were fixed between 1.8.0 and 1.8.1. If you experience trouble with the above code, keep this in mind.

Further documentation

The methods are not individually documented at this stage. The above example 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

abort accept accept add_officious banner base def_head_option def_option def_tail_option define define_head define_tail each_const environment 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 search_const separator show_version summarize terminate terminate to_a to_s top top ver version warn with

Classes and Modules

Module OptionParser::Acceptables
Module OptionParser::Arguable
Module OptionParser::Completion
Class OptionParser::AmbiguousArgument
Class OptionParser::AmbiguousOption
Class OptionParser::CompletingHash
Class OptionParser::InvalidArgument
Class OptionParser::InvalidOption
Class OptionParser::List
Class OptionParser::MissingArgument
Class OptionParser::NeedlessArgument
Class OptionParser::OptionMap
Class OptionParser::ParseError
Class OptionParser::Switch

Constants

DecimalInteger | = | /\A[-+]?#{decimal}/io
OctalInteger | = | /\A[-+]?(?:[0-7]+(?:_[0-7]+)*|0(?:#{binary}|#{hex}))/io
DecimalNumeric | = | floatpat # decimal integer is allowed as float also.

External Aliases

banner= | -> | set_banner
 | for experimental cascading :-)
program_name= | -> | set_program_name
summary_width= | -> | set_summary_width
summary_indent= | -> | set_summary_indent

Attributes

banner | [W]
default_argv | [RW]
program_name | [W]
release | [W]
summary_indent | [RW]
summary_width | [RW]
version | [W]

Public Class methods

accept(*args, &blk)

[Source]

# File optparse.rb, line 857
  def self.accept(*args, &blk) top.accept(*args, &blk) end
each_const(path, klass = ::Object)

[Source]

# File optparse/version.rb, line 49
  def each_const(path, klass = ::Object)
    path.split(/::|\//).inject(klass) do |klass, name|
      raise NameError, path unless Module === klass
      klass.constants.grep(/#{name}/i) do |c|
        klass.const_defined?(c) or next
        c = klass.const_get(c)
      end
    end
  end
inc(arg, default = nil)

[Source]

# File optparse.rb, line 782
  def self.inc(arg, default = nil)
    case arg
    when Integer
      arg.nonzero?
    when nil
      default.to_i + 1
    end
  end
new(banner = nil, width = 32, indent = ' ' * 4) {|self if block_given?| ...}

[Source]

# File optparse.rb, line 807
  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
reject(*args, &blk)

[Source]

# File optparse.rb, line 868
  def self.reject(*args, &blk) top.reject(*args, &blk) end
search_const(klass, name) {|klass, cname, const if name === cname| ...}

[Source]

# File optparse/version.rb, line 59
  def search_const(klass, name)
    klasses = [klass]
    while klass = klasses.shift
      klass.constants.each do |cname|
        klass.const_defined?(cname) or next
        const = klass.const_get(cname)
        yield klass, cname, const if name === cname
        klasses << const if Module === const and const != ::Object
      end
    end
  end
show_version(*pkg)

[Source]

# File optparse/version.rb, line 4
  def show_version(*pkg)
    progname = ARGV.options.program_name
    result = false
    show = proc do |klass, cname, version|
      str = "#{progname}"
      unless klass == ::Object and cname == :VERSION
        version = version.join(".") if Array === version
        str << ": #{klass}" unless klass == Object
        str << " version #{version}"
      end
      [:Release, :RELEASE].find do |rel|
        if klass.const_defined?(rel)
          str << " (#{klass.const_get(rel)})"
        end
      end
      puts str
      result = true
    end
    if pkg.size == 1 and pkg[0] == "all"
      self.search_const(::Object, /\AV(?:ERSION|ersion)\z/) do |klass, cname, version|
        unless cname[1] == ?e and klass.const_defined?(:Version)
          show.call(klass, cname.intern, version)
        end
      end
    else
      pkg.each do |pkg|
        begin
          pkg = pkg.split(/::|\//).inject(::Object) {|m, c| m.const_get(c)}
          v = case
              when pkg.const_defined?(:Version)
                pkg.const_get(n = :Version)
              when pkg.const_defined?(:VERSION)
                pkg.const_get(n = :VERSION)
              else
                n = nil
                "unknown"
              end
          show.call(pkg, n, v)
        rescue NameError
        end
      end
    end
    result
  end
terminate(arg = nil)

[Source]

# File optparse.rb, line 837
  def self.terminate(arg = nil)
    throw :terminate, arg
  end
top()

[Source]

# File optparse.rb, line 842
  def self.top() DefaultList end
with(*args, &block)

[Source]

# File optparse.rb, line 771
  def self.with(*args, &block)
    opts = new(*args)
    opts.instance_eval(&block)
    opts
  end

Public Instance methods

abort(mesg = $!)

[Source]

# File optparse.rb, line 944
  def abort(mesg = $!)
    super("#{program_name}: #{mesg}")
  end
accept(*args, &blk)

[Source]

# File optparse.rb, line 856
  def accept(*args, &blk) top.accept(*args, &blk) end
add_officious()

:nodoc:

[Source]

# File optparse.rb, line 819
  def add_officious
    list = base()
    Officious.each_pair do |opt, block|
      list.long[opt] ||= block.call(self)
    end
  end
banner()

[Source]

# File optparse.rb, line 897
  def banner
    @banner ||= "Usage: #{program_name} [options]"
  end
base()

[Source]

# File optparse.rb, line 960
  def base
    @stack[1]
  end
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)

[Source]

# File optparse.rb, line 1211
  def define(*opts, &block)
    top.append(*(sw = make_switch(*opts, &block)))
    sw[0]
  end
define_head(*opts, &block)

[Source]

# File optparse.rb, line 1221
  def define_head(*opts, &block)
    top.prepend(*(sw = make_switch(*opts, &block)))
    sw[0]
  end
define_tail(*opts, &block)

[Source]

# File optparse.rb, line 1231
  def define_tail(*opts, &block)
    base.append(*(sw = make_switch(*opts, &block)))
    sw[0]
  end
environment(env = File.basename($0, '.*'))

[Source]

# File optparse.rb, line 1481
  def environment(env = File.basename($0, '.*'))
    env = ENV[env] || ENV[env.upcase] or return
    parse(*Shellwords.shellwords(env))
  end
help()

[Source]

# File optparse.rb, line 1011
  def help; summarize(banner.to_s.sub(/\n?\z/, "\n")) end
inc(*args)

[Source]

# File optparse.rb, line 790
  def inc(*args)
    self.class.inc(*args)
  end
load(filename = nil)

[Source]

# File optparse.rb, line 1459
  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
make_switch(*opts, &block)

[Source]

# File optparse.rb, line 1083
  def make_switch(*opts, &block)
    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
    s = if short.empty? and long.empty?
          raise ArgumentError, "no switch given" if style or pattern or block
          desc
        else
          (style || default_style).new(pattern || default_pattern,
                                       conv, sdesc, ldesc, 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
new() {|self| ...}

[Source]

# File optparse.rb, line 968
  def new
    @stack.push(List.new)
    if block_given?
      yield self
    else
      self
    end
  end
on(*opts, &block)

[Source]

# File optparse.rb, line 1215
  def on(*opts, &block)
    define(*opts, &block)
    self
  end
on_head(*opts, &block)

[Source]

# File optparse.rb, line 1225
  def on_head(*opts, &block)
    define_head(*opts, &block)
    self
  end
on_tail(*opts, &block)

[Source]

# File optparse.rb, line 1235
  def on_tail(*opts, &block)
    define_tail(*opts, &block)
    self
  end
order(*argv, &block)

[Source]

# File optparse.rb, line 1263
  def order(*argv, &block)
    argv = argv[0].dup if argv.size == 1 and Array === argv[0]
    order!(argv, &block)
  end
order!(argv = default_argv, &nonopt)

[Source]

# File optparse.rb, line 1268
  def order!(argv = default_argv, &nonopt)
    opt, arg, sw, val, rest = nil
    nonopt ||= proc {|arg| throw :terminate, arg}
    argv.unshift(arg) if arg = catch(:terminate) {
      while arg = argv.shift
        case arg
        # long option
        when /\A--([^=]*)(?:=(.*))?/
          opt, rest = $1, $2
          begin
            sw, = complete(:long, opt, true)
          rescue ParseError
            raise $!.set_option(arg, true)
          end
          begin
            opt, sw, val = sw.parse(rest, argv) {|*exc| raise(*exc)}
            sw.call(val) if sw
          rescue ParseError
            raise $!.set_option(arg, rest)
          end

        # short option
        when /\A-(.)((=).*|.+)?/
          opt, has_arg, eq, val, rest = $1, $3, $3, $2, $2
          begin
            unless sw = search(:short, opt)
              begin
                sw, = complete(:short, opt)
                # short option matched.
                val = arg.sub(/\A-/, '')
                has_arg = true
              rescue InvalidOption
                # if no short options match, try completion with long
                # options.
                sw, = complete(:long, opt)
                eq ||= !rest
              end
            end
          rescue ParseError
            raise $!.set_option(arg, true)
          end
          begin
            opt, sw, val = sw.parse(val, argv) {|*exc| raise(*exc) if eq}
            raise InvalidOption, arg if has_arg and !eq and arg == "-#{opt}"
            argv.unshift(opt) if opt and (opt = opt.sub(/\A-*/, '-')) != '-'
            sw.call(val) if sw
          rescue ParseError
            raise $!.set_option(arg, arg.length > 2)
          end

        # non-option argument
        else
          nonopt.call(arg)
        end
      end

      nil
    }

    argv
  end
parse(*argv)

[Source]

# File optparse.rb, line 1369
  def parse(*argv)
    argv = argv[0].dup if argv.size == 1 and Array === argv[0]
    parse!(argv)
  end
parse!(argv = default_argv)

[Source]

# File optparse.rb, line 1374
  def parse!(argv = default_argv)
    if ENV.include?('POSIXLY_CORRECT')
      order!(argv)
    else
      permute!(argv)
    end
  end
permute(*argv)

[Source]

# File optparse.rb, line 1343
  def permute(*argv)
    argv = argv[0].dup if argv.size == 1 and Array === argv[0]
    permute!(argv)
  end
permute!(argv = default_argv)

[Source]

# File optparse.rb, line 1348
  def permute!(argv = default_argv)
    nonopts = []
    arg = nil
    order!(argv) {|arg| nonopts << arg}
    argv[0, 0] = nonopts
    argv
  end
program_name()

[Source]

# File optparse.rb, line 901
  def program_name
    @program_name || File.basename($0, '.*')
  end
reject(*args, &blk)

[Source]

# File optparse.rb, line 867
  def reject(*args, &blk) top.reject(*args, &blk) end
release()

[Source]

# File optparse.rb, line 928
  def release
    @release || (defined?(::Release) && ::Release) || (defined?(::RELEASE) && ::RELEASE)
  end
remove()

[Source]

# File optparse.rb, line 981
  def remove
    @stack.pop
  end
separator(string)

[Source]

# File optparse.rb, line 1241
  def separator(string)
    top.append(string, nil, nil)
  end
summarize(to = [], width = @summary_width, max = width - 1, indent = @summary_indent, &blk)

[Source]

# File optparse.rb, line 1001
  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
terminate(arg = nil)

[Source]

# File optparse.rb, line 834
  def terminate(arg = nil)
    self.class.terminate(arg)
  end
to_a()

[Source]

# File optparse.rb, line 1018
  def to_a; summarize(banner.to_a.dup) end
to_s()

Alias for help

top()

[Source]

# File optparse.rb, line 952
  def top
    @stack[-1]
  end
ver()

[Source]

# File optparse.rb, line 932
  def ver
    if v = version
      str = "#{program_name} #{[v].join('.')}"
      str << " (#{v})" if v = release
      str
    end
  end
version()

[Source]

# File optparse.rb, line 924
  def version
    @version || (defined?(::Version) && ::Version)
  end
warn(mesg = $!)

[Source]

# File optparse.rb, line 940
  def warn(mesg = $!)
    super("#{program_name}: #{mesg}")
  end


Module: OptionParser::Acceptables

Module | OptionParser::Acceptables
In: | optparse.rb


Class: OptionParser::AmbiguousArgument

Class | OptionParser::AmbiguousArgument
In: | optparse.rb
Parent: | InvalidArgument


Class: OptionParser::AmbiguousOption

Class | OptionParser::AmbiguousOption
In: | optparse.rb
Parent: | ParseError


Module: OptionParser::Arguable

Module | OptionParser::Arguable
In: | optparse.rb

Methods

extend_object new options options= order! parse! permute!

Public Class methods

extend_object(obj)

[Source]

# File optparse.rb, line 1792
    def self.extend_object(obj)
      super
      obj.instance_eval {@optparse = nil}
    end
new(*args)

[Source]

# File optparse.rb, line 1796
    def initialize(*args)
      super
      @optparse = nil
    end

Public Instance methods

options() {|@optparse| ...}

[Source]

# File optparse.rb, line 1766
    def options
      @optparse ||= OptionParser.new
      @optparse.default_argv = self
      block_given? or return @optparse
      begin
        yield @optparse
      rescue ParseError
        @optparse.warn $!
        nil
      end
    end
options=(opt)

[Source]

# File optparse.rb, line 1742
    def options=(opt)
      unless @optparse = opt
        class << self
          undef_method(:options)
          undef_method(:options=)
        end
      end
    end
order!(&blk)

[Source]

# File optparse.rb, line 1785
    def order!(&blk) options.order!(self, &blk) end
parse!()

[Source]

# File optparse.rb, line 1787
    def parse!() options.parse!(self) end
permute!()

[Source]

# File optparse.rb, line 1786
    def permute!() options.permute!(self) end


Class: OptionParser::CompletingHash

Class | OptionParser::CompletingHash
In: | optparse.rb
Parent: | Hash

Hash with completion search feature. See Completion module.

Methods

match

Included Modules

Completion

Public Instance methods

match(key)

OptionParser::CompletingHash#match(key)

Completion for hash key.

[Source]

# File optparse.rb, line 672
    def match(key)
      return key, *fetch(key) {
        raise AmbiguousArgument, catch(:ambiguous) {return complete(key)}
      }
    end


Module: OptionParser::Completion

Module | OptionParser::Completion
In: | 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| ...}

[Source]

# File optparse.rb, line 210
    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(opt = nil, val = nil, *)

[Source]

# File optparse.rb, line 250
    def convert(opt = nil, val = nil, *)
      val
    end


Class: OptionParser::InvalidArgument

Class | OptionParser::InvalidArgument
In: | optparse.rb
Parent: | ParseError


Class: OptionParser::InvalidOption

Class | OptionParser::InvalidOption
In: | optparse.rb
Parent: | ParseError


Class: OptionParser::List

Class | OptionParser::List
In: | 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 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.

[Source]

# File optparse.rb, line 514
    def initialize
      @atype = {}
      @short = OptionMap.new
      @long = OptionMap.new
      @list = []
    end

Public Instance methods

accept(t, pat = /.*/, &block)

See OptionParser.accept.

[Source]

# File optparse.rb, line 524
    def accept(t, pat = /.*/, &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
append(*args)

OptionParser::List#append(switch, short_opts, long_opts, nolong_opts)

Appends ((|switch|)) at tail of the list, and associates short, long and negated long options.

 :Parameters:
   : ((|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.

[Source]

# File optparse.rb, line 592
    def append(*args)
      update(*args)
      @list.push(args[0])
    end
complete(id, opt, icase = false, *pat, &block)

OptionParser::List#complete(id, opt, *pat, &block)

Searches list ((|id|)) for ((|opt|)) and ((|*pat|)).

 :Parameters:
   : ((|id|))
     searching list.
   : ((|opt|))
     searching key.
   : ((|icase|))
     search case insensitive if true.
   : ((|*pat|))
     optional pattern for completion.
   : (({block}))
     yielded with the found value when succeeded.

[Source]

# File optparse.rb, line 633
    def complete(id, opt, icase = false, *pat, &block)
      __send__(id).complete(opt, icase, *pat, &block)
    end
prepend(*args)

OptionParser::List#prepend(switch, short_opts, long_opts, nolong_opts)

Inserts ((|switch|)) at head of the list, and associates short, long and negated long options.

[Source]

# File optparse.rb, line 573
    def prepend(*args)
      update(*args)
      @list.unshift(args[0])
    end
reject(t)

See OptionParser.reject.

[Source]

# File optparse.rb, line 539
    def reject(t)
      @atype.delete(t)
    end
search(id, key) {|val| ...}

OptionParser::List#search(id, key) [{block}]

Searches ((|key|)) in ((|id|)) list.

 :Parameters:
   : ((|id|))
     searching list.
   : ((|k|))
     searching key.
   : (({block}))
     yielded with the found value when succeeded.

[Source]

# File optparse.rb, line 609
    def search(id, key)
      if list = __send__(id)
        val = list.fetch(key) {return nil}
        return val unless block_given?
        yield(val)
      end
    end
summarize(*args) {|""| ...}

OptionParser::List#summarize(*args) {…}

Making summary table, yields the (({block})) with each lines. Each elements of (({@list})) should be able to (({summarize})).

 :Parameters:
   : ((|args|))
     passed to elements#summarize through.
   : (({block}))
     to be passed each lines(without newline).

[Source]

# File optparse.rb, line 648
    def summarize(*args, &block)
      list.each do |opt|
        if opt.respond_to?(:summarize) # perhaps OptionParser::Switch
          opt.summarize(*args, &block)
        elsif opt.empty?
          yield("")
        else
          opt.each(&block)
        end
      end
    end


Class: OptionParser::MissingArgument

Class | OptionParser::MissingArgument
In: | optparse.rb
Parent: | ParseError


Class: OptionParser::NeedlessArgument

Class | OptionParser::NeedlessArgument
In: | optparse.rb
Parent: | ParseError


Class: OptionParser::OptionMap

Class | OptionParser::OptionMap
In: | optparse.rb
Parent: | Hash

Map from option/keyword string to object with completion.

Included Modules

Completion


Class: OptionParser::ParseError

Class | OptionParser::ParseError
In: | optparse.rb
Parent: | RuntimeError

Methods

inspect message new reason recover set_option to_s to_str

Constants

Reason = 'parse error'.freeze

Attributes

args | [R]
reason | [W]

Public Class methods

new(*args)

[Source]

# File optparse.rb, line 1625
    def initialize(*args)
      @args = args
      @reason = nil
    end

Public Instance methods

inspect()

[Source]

# File optparse.rb, line 1651
    def inspect
      "#<#{self.class.to_s}: #{args.join(' ')}>"
    end
message()

[Source]

# File optparse.rb, line 1655
    def message
      reason + ': ' + args.join(' ')
    end
reason()

[Source]

# File optparse.rb, line 1647
    def reason
      @reason || self.class::Reason
    end
recover(argv)

[Source]

# File optparse.rb, line 1633
    def recover(argv)
      argv[0, 0] = @args
      argv
    end
set_option(opt, eq)

[Source]

# File optparse.rb, line 1638
    def set_option(opt, eq)
      if eq
        @args[0] = opt
      else
        @args.unshift(opt)
      end
      self
    end
to_s()

Alias for message

to_str()

Alias for message


Class: OptionParser::Switch

Class | OptionParser::Switch
In: | 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

Classes and Modules

Class OptionParser::Switch::NoArgument
Class OptionParser::Switch::OptionalArgument
Class OptionParser::Switch::PlacedArgument
Class OptionParser::Switch::RequiredArgument

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.).

[Source]

# File optparse.rb, line 277
    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(arg, t)

[Source]

# File optparse.rb, line 292
    def self.incompatible_argument_styles(arg, t)
      raise ArgumentError, "#{arg}: incompatible argument styles\n  #{self}, #{t}"
    end
new(pattern = nil, conv = nil, short = nil, long = nil, arg = nil, desc = ([] if short or long), block = Proc.new)

[Source]

# File optparse.rb, line 300
    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
pattern()

[Source]

# File optparse.rb, line 296
    def self.pattern
      NilClass
    end

Public Instance methods

summarize(sdone = [], ldone = [], width = 1, max = width - 1, indent = "") {|indent + l| ...}

OptionParser::Switch#summarize(sdone, ldone, width, max, indent)

Makes summary strings.

 :Parameters:
   : ((|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 word, right side,
     description part strings start at ((|width|)) column.
   : ((|max|))
     maximum width of left side, options are filled within ((|max|)) columns.
   : ((|indent|))
     prefix string indents each summarized lines.
   : (({block}))
     to be passed each lines(without newline).

[Source]

# File optparse.rb, line 388
    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 (l = left.shift; r = right.shift; l or r)
        l = l.to_s.ljust(width) + ' ' + r if r and !r.empty?
        yield(indent + l)
      end

      self
    end


Class: OptionParser::Switch::NoArgument

Class | OptionParser::Switch::NoArgument
In: | optparse.rb
Parent: | self

Switch that takes no arguments.

Methods

incompatible_argument_styles parse pattern

Public Class methods

incompatible_argument_styles(*)

[Source]

# File optparse.rb, line 430
      def self.incompatible_argument_styles(*)
      end
pattern()

[Source]

# File optparse.rb, line 432
      def self.pattern
        Object
      end

Public Instance methods

parse(arg, argv) {|NeedlessArgument, arg| ...}

Raises an exception if any arguments given.

[Source]

# File optparse.rb, line 426
      def parse(arg, argv, &error)
        yield(NeedlessArgument, arg) if arg
        conv_arg(arg)
      end


Class: OptionParser::Switch::OptionalArgument

Class | OptionParser::Switch::OptionalArgument
In: | 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.

[Source]

# File optparse.rb, line 460
      def parse(arg, argv, &error)
        if arg
          conv_arg(*parse_arg(arg, &error))
        else
          conv_arg(arg)
        end
      end


Class: OptionParser::Switch::PlacedArgument

Class | OptionParser::Switch::PlacedArgument
In: | 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 ’-’.

[Source]

# File optparse.rb, line 476
      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


Class: OptionParser::Switch::RequiredArgument

Class | OptionParser::Switch::RequiredArgument
In: | 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.

[Source]

# File optparse.rb, line 444
      def parse(arg, argv)
        unless arg
          raise MissingArgument if argv.empty?
          arg = argv.shift
        end
        conv_arg(*parse_arg(arg) {|*exc| raise(*exc)})
      end


File: optparse.rb

optparse.rb

Path: | optparse.rb
Last Update: | Sat Oct 15 23:44:27 AUS Eastern Standard Time 2005

optparse.rb - command-line option analysis with the OptionParser class.

Author: | Nobu Nakada
Documentation: | Nobu Nakada and Gavin Sinclair.

See OptionParser for documentation.

Required files

optparse/version

Constants

Version = OptionParser::Version


File: date.rb

date.rb

Path: | optparse/date.rb
Last Update: | Fri Sep 05 12:32:24 AUS Eastern Standard Time 2003

Required files

optparse date


File: shellwords.rb

shellwords.rb

Path: | optparse/shellwords.rb
Last Update: | Wed May 21 14:27:06 AUS Eastern Standard Time 2003

-*- ruby -*-

Required files

shellwords optparse


File: time.rb

time.rb

Path: | optparse/time.rb
Last Update: | Wed May 21 14:27:06 AUS Eastern Standard Time 2003

Required files

optparse time


File: uri.rb

uri.rb

Path: | optparse/uri.rb
Last Update: | Wed May 21 14:27:06 AUS Eastern Standard Time 2003

-*- ruby -*-

Required files

optparse uri


File: version.rb

version.rb

Path: | optparse/version.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

OptionParser internal utility


Class: OpenStruct

Class | OpenStruct
In: | 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.

[Source]

# File 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

Public Instance methods

==(other)

Compare this object and other for equality.

[Source]

# File ostruct.rb, line 142
  def ==(other)
    return false unless(other.kind_of?(OpenStruct))
    return @table == other.table
  end
delete_field(name)

Remove the named field from the object.

[Source]

# File ostruct.rb, line 102
  def delete_field(name)
    @table.delete name.to_sym
  end
initialize_copy(orig)

Duplicate an OpenStruct object members.

[Source]

# File ostruct.rb, line 57
  def initialize_copy(orig)
    super
    @table = @table.dup
  end
inspect()

Returns a string containing a detailed summary of the keys and values.

[Source]

# File 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
marshal_dump()

[Source]

# File ostruct.rb, line 62
  def marshal_dump
    @table
  end
marshal_load(x)

[Source]

# File ostruct.rb, line 65
  def marshal_load(x)
    @table = x
    @table.each_key{|key| new_ostruct_member(key)}
  end
new_ostruct_member(name)

[Source]

# File 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
to_s()

Alias for inspect


File: ostruct.rb

ostruct.rb

Path: | ostruct.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

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.


Module: ParseDate

Module | ParseDate
In: | parsedate.rb

Methods

parsedate

Public Instance methods

parsedate(str, comp=false)

[Source]

# File parsedate.rb, line 8
  def parsedate(str, comp=false)
    Date._parse(str, comp).
      values_at(:year, :mon, :mday, :hour, :min, :sec, :zone, :wday)
  end


File: parsedate.rb

parsedate.rb

Path: | parsedate.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

parsedate.rb: Written by Tadayoshi Funaba 2001, 2002 $Id: parsedate.rb,v 2.6 2002-05-14 07:43:18+09 tadf Exp $

Required files

date/format


Class: Pathname

Class | Pathname
In: | pathname.rb
Parent: | Object

Pathname

Pathname represents a pathname which locates a file in a filesystem. It supports only Unix style pathnames. 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?
  • readable_real?
  • setgid?
  • setuid?
  • size
  • size?
  • socket?
  • sticky?
  • symlink?
  • 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

+ <=> == === absolute? atime basename blockdev? chardev? chdir children chmod chown chroot cleanpath ctime delete 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? symlink symlink? sysopen taint to_s to_str truncate unlink untaint utime writable? writable_real? zero?

External Aliases

getwd -> pwd

Public Class methods

getwd()

See Dir.getwd. Returns the current working directory as a Pathname.

[Source]

# File pathname.rb, line 771
  def Pathname.getwd() Pathname.new(Dir.getwd) end
glob(*args) {|p| ...}

See Dir.glob. Returns or yields Pathname objects.

[Source]

# File pathname.rb, line 762
  def Pathname.glob(*args) # :yield: p
    if block_given?
      Dir.glob(*args) {|f| yield Pathname.new(f) }
    else
      Dir.glob(*args).map {|f| Pathname.new(f) }
    end
  end
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.

[Source]

# File pathname.rb, line 187
  def initialize(path)
    path = path.to_str if path.respond_to? :to_str
    @path = path.dup

    if /\0/ =~ @path
      raise ArgumentError, "pathname contains \\0: #{@path.inspect}"
    end

    self.taint if @path.tainted?
  end

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.

[Source]

# File pathname.rb, line 433
  def +(other)
    other = Pathname.new(other) unless Pathname === other

    return other if other.absolute?

    path1 = @path
    path2 = other.to_s
    while m2 = %r{\A\.\.(?:/+|\z)}.match(path2) and
          m1 = %r{(\A|/+)([^/]+)\z}.match(path1) and
          %r{\A(?:\.|\.\.)\z} !~ m1[2]
      path1 = m1[1].empty? ? '.' : '/' if (path1 = m1.pre_match).empty?
      path2 = '.' if (path2 = m2.post_match).empty?
    end
    if %r{\A/+\z} =~ path1
      while m2 = %r{\A\.\.(?:/+|\z)}.match(path2)
        path2 = '.' if (path2 = m2.post_match).empty?
      end
    end

    return Pathname.new(path2) if path1 == '.'
    return Pathname.new(path1) if path2 == '.'

    if %r{/\z} =~ path1
      Pathname.new(path1 + path2)
    else
      Pathname.new(path1 + '/' + path2)
    end
  end
<=>(other)

Provides for comparing pathnames, case-sensitively.

[Source]

# File pathname.rb, line 215
  def <=>(other)
    return nil unless Pathname === other
    @path.tr('/', "\0") <=> other.to_s.tr('/', "\0")
  end
==(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.

[Source]

# File pathname.rb, line 207
  def ==(other)
    return false unless Pathname === other
    other.to_s == @path
  end
===(other)

Alias for #==

absolute?()

Predicate method for testing whether a path is absolute. It returns true if the pathname begins with a slash.

[Source]

# File pathname.rb, line 404
  def absolute?
    %r{\A/} =~ @path ? true : false
  end
atime()

See File.atime. Returns last access time.

[Source]

# File pathname.rb, line 598
  def atime() File.atime(@path) end
basename(*args)

See File.basename. Returns the last component of the path.

[Source]

# File pathname.rb, line 659
  def basename(*args) Pathname.new(File.basename(@path, *args)) end
blockdev?()

See FileTest.blockdev?.

[Source]

# File pathname.rb, line 693
  def blockdev?() FileTest.blockdev?(@path) end
chardev?()

See FileTest.chardev?.

[Source]

# File pathname.rb, line 696
  def chardev?() FileTest.chardev?(@path) end
chdir(&block)

Pathname#chdir is obsoleted at 1.8.1.

[Source]

# File pathname.rb, line 775
  def chdir(&block)
    warn "Pathname#chdir is obsoleted.  Use Dir.chdir."
    Dir.chdir(@path, &block)
  end
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.

[Source]

# File pathname.rb, line 502
  def children(with_directory=true)
    with_directory = false if @path == '.'
    result = []
    Dir.foreach(@path) {|e|
      next if e == '.' || e == '..'
      if with_directory
        result << Pathname.new(File.join(@path, e))
      else
        result << Pathname.new(e)
      end
    }
    result
  end
chmod(mode)

See File.chmod. Changes permissions.

[Source]

# File pathname.rb, line 607
  def chmod(mode) File.chmod(mode, @path) end
chown(owner, group)

See File.chown. Change owner and group of file.

[Source]

# File pathname.rb, line 613
  def chown(owner, group) File.chown(owner, group, @path) end
chroot()

Pathname#chroot is obsoleted at 1.8.1.

[Source]

# File pathname.rb, line 781
  def chroot
    warn "Pathname#chroot is obsoleted.  Use Dir.chroot."
    Dir.chroot(@path)
  end
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.

[Source]

# File pathname.rb, line 245
  def cleanpath(consider_symlink=false)
    if consider_symlink
      cleanpath_conservative
    else
      cleanpath_aggressive
    end
  end
ctime()

See File.ctime. Returns last (directory entry, not file) change time.

[Source]

# File pathname.rb, line 601
  def ctime() File.ctime(@path) end
delete()

Alias for unlink

dir_foreach(*args, &block)

Pathname#dir_foreach is obsoleted at 1.8.1.

[Source]

# File pathname.rb, line 799
  def dir_foreach(*args, &block)
    warn "Pathname#dir_foreach is obsoleted.  Use Pathname#each_entry."
    each_entry(*args, &block)
  end
directory?()

See FileTest.directory?.

[Source]

# File pathname.rb, line 711
  def directory?() FileTest.directory?(@path) end
dirname()

See File.dirname. Returns all but the last component of the path.

[Source]

# File pathname.rb, line 662
  def dirname() Pathname.new(File.dirname(@path)) end
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.

[Source]

# File pathname.rb, line 794
  def each_entry(&block) # :yield: p
    Dir.foreach(@path) {|f| yield Pathname.new(f) }
  end
each_filename( {|s| ...}

Iterates over each component of the path.

  Pathname.new("/usr/bin/ruby").each_filename {|filename| ... }
    # yields "usr", "bin", and "ruby".

[Source]

# File pathname.rb, line 419
  def each_filename # :yield: s
    @path.scan(%r{[^/]+}) { yield $& }
  end
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.

[Source]

# File pathname.rb, line 573
  def each_line(*args, &block) # :yield: line
    IO.foreach(@path, *args, &block)
  end
entries()

Return the entries (files and subdirectories) in the directory, each as a Pathname object.

[Source]

# File pathname.rb, line 788
  def entries() Dir.entries(@path).map {|f| Pathname.new(f) } end
eql?(other)

Alias for #==

executable?()

See FileTest.executable?.

[Source]

# File pathname.rb, line 699
  def executable?() FileTest.executable?(@path) end
executable_real?()

See FileTest.executable_real?.

[Source]

# File pathname.rb, line 702
  def executable_real?() FileTest.executable_real?(@path) end
exist?()

See FileTest.exist?.

[Source]

# File pathname.rb, line 705
  def exist?() FileTest.exist?(@path) end
expand_path(*args)

See File.expand_path.

[Source]

# File pathname.rb, line 668
  def expand_path(*args) Pathname.new(File.expand_path(@path, *args)) end
extname()

See File.extname. Returns the file’s extension.

[Source]

# File pathname.rb, line 665
  def extname() File.extname(@path) end
file?()

See FileTest.file?.

[Source]

# File pathname.rb, line 714
  def file?() FileTest.file?(@path) end
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 ./.

[Source]

# File pathname.rb, line 828
  def find(&block) # :yield: p
    require 'find'
    if @path == '.'
      Find.find(@path) {|f| yield Pathname.new(f.sub(%r{\A\./}, '')) }
    else
      Find.find(@path) {|f| yield Pathname.new(f) }
    end
  end
fnmatch(pattern, *args)

See File.fnmatch. Return true if the receiver matches the given pattern.

[Source]

# File pathname.rb, line 620
  def fnmatch(pattern, *args) File.fnmatch(pattern, @path, *args) end
fnmatch?(pattern, *args)

See File.fnmatch? (same as fnmatch).

[Source]

# File pathname.rb, line 623
  def fnmatch?(pattern, *args) File.fnmatch?(pattern, @path, *args) end
foreach(*args, &block)

This method is obsoleted at 1.8.1. Use each_line or each_entry.

[Source]

# File pathname.rb, line 872
  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
foreachline(*args, &block)

Pathname#foreachline is obsoleted at 1.8.1. Use each_line.

[Source]

# File pathname.rb, line 578
  def foreachline(*args, &block)
    warn "Pathname#foreachline is obsoleted.  Use Pathname#each_line."
    each_line(*args, &block)
  end
freeze()

[Source]

# File pathname.rb, line 198
  def freeze() super; @path.freeze; self end
ftype()

See File.ftype. Returns "type" of file ("file", "directory", etc).

[Source]

# File pathname.rb, line 627
  def ftype() File.ftype(@path) end
grpowned?()

See FileTest.grpowned?.

[Source]

# File pathname.rb, line 708
  def grpowned?() FileTest.grpowned?(@path) end
join(*args)

Pathname#join joins pathnames.

path0.join(path1, …, pathN) is the same as path0 + path1 + … + pathN.

[Source]

# File pathname.rb, line 468
  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
lchmod(mode)

See File.lchmod.

[Source]

# File pathname.rb, line 610
  def lchmod(mode) File.lchmod(mode, @path) end
lchown(owner, group)

See File.lchown.

[Source]

# File pathname.rb, line 616
  def lchown(owner, group) File.lchown(owner, group, @path) end
link(old)

Pathname#link is confusing and obsoleted because the receiver/argument order is inverted to corresponding system call.

[Source]

# File pathname.rb, line 676
  def link(old)
    warn 'Pathname#link is obsoleted.  Use Pathname#make_link.'
    File.link(old, @path)
  end
lstat()

See File.lstat.

[Source]

# File pathname.rb, line 647
  def lstat() File.lstat(@path) end
make_link(old)

See File.link. Creates a hard link.

[Source]

# File pathname.rb, line 630
  def make_link(old) File.link(old, @path) end
make_symlink(old)

See File.symlink. Creates a symbolic link.

[Source]

# File pathname.rb, line 650
  def make_symlink(old) File.symlink(old, @path) end
mkdir(*args)

See Dir.mkdir. Create the referenced directory.

[Source]

# File pathname.rb, line 805
  def mkdir(*args) Dir.mkdir(@path, *args) end
mkpath()

See FileUtils.mkpath. Creates a full path, including any intermediate directories that don’t yet exist.

[Source]

# File pathname.rb, line 842
  def mkpath
    require 'fileutils'
    FileUtils.mkpath(@path)
    nil
  end
mountpoint?()

mountpoint? returns true if self points to a mountpoint.

[Source]

# File pathname.rb, line 380
  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
mtime()

See File.mtime. Returns last modification time.

[Source]

# File pathname.rb, line 604
  def mtime() File.mtime(@path) end
open(*args) {|file| ...}

See File.open. Opens the file for reading or writing.

[Source]

# File pathname.rb, line 633
  def open(*args, &block) # :yield: file
    File.open(@path, *args, &block)
  end
opendir() {|dir| ...}

See Dir.open.

[Source]

# File pathname.rb, line 811
  def opendir(&block) # :yield: dir
    Dir.open(@path, &block)
  end
owned?()

See FileTest.owned?.

[Source]

# File pathname.rb, line 723
  def owned?() FileTest.owned?(@path) end
parent()

parent returns the parent directory.

This is same as self + ’..’.

[Source]

# File pathname.rb, line 375
  def parent
    self + '..'
  end
pipe?()

See FileTest.pipe?.

[Source]

# File pathname.rb, line 717
  def pipe?() FileTest.pipe?(@path) end
read(*args)

See IO.read. Returns all the bytes from the file, or the first N if specified.

[Source]

# File pathname.rb, line 585
  def read(*args) IO.read(@path, *args) end
readable?()

See FileTest.readable?.

[Source]

# File pathname.rb, line 726
  def readable?() FileTest.readable?(@path) end
readable_real?()

See FileTest.readable_real?.

[Source]

# File pathname.rb, line 729
  def readable_real?() FileTest.readable_real?(@path) end
readlines(*args)

See IO.readlines. Returns all the lines from the file.

[Source]

# File pathname.rb, line 588
  def readlines(*args) IO.readlines(@path, *args) end
readlink()

See File.readlink. Read symbolic link.

[Source]

# File pathname.rb, line 638
  def readlink() Pathname.new(File.readlink(@path)) end
realpath(*args)

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.

[Source]

# File pathname.rb, line 311
  def realpath(*args)
    unless args.empty?
      warn "The argument for Pathname#realpath is obsoleted."
    end
    force_absolute = args.fetch(0, true)

    if %r{\A/} =~ @path
      top = '/'
      unresolved = @path.scan(%r{[^/]+})
    elsif force_absolute
      # Although POSIX getcwd returns a pathname which contains no symlink,
      # 4.4BSD-Lite2 derived getcwd may return the environment variable $PWD
      # which may contain a symlink.
      # So the return value of Dir.pwd should be examined.
      top = '/'
      unresolved = Dir.pwd.scan(%r{[^/]+}) + @path.scan(%r{[^/]+})
    else
      top = ''
      unresolved = @path.scan(%r{[^/]+})
    end
    resolved = []

    until unresolved.empty?
      case unresolved.last
      when '.'
        unresolved.pop
      when '..'
        resolved.unshift unresolved.pop
      else
        loop_check = {}
        while (stat = File.lstat(path = top + unresolved.join('/'))).symlink?
          symlink_id = "#{stat.dev}:#{stat.ino}"
          raise Errno::ELOOP.new(path) if loop_check[symlink_id]
          loop_check[symlink_id] = true
          if %r{\A/} =~ (link = File.readlink(path))
            top = '/'
            unresolved = link.scan(%r{[^/]+})
          else
            unresolved[-1,1] = link.scan(%r{[^/]+})
          end
        end
        next if (filename = unresolved.pop) == '.'
        if filename != '..' && resolved.first == '..'
          resolved.shift
        else
          resolved.unshift filename
        end
      end
    end

    if top == '/'
      resolved.shift while resolved[0] == '..'
    end

    if resolved.empty?
      Pathname.new(top.empty? ? '.' : '/')
    else
      Pathname.new(top + resolved.join('/'))
    end
  end
relative?()

The opposite of absolute?

[Source]

# File pathname.rb, line 409
  def relative?
    !absolute?
  end
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.

[Source]

# File pathname.rb, line 527
  def relative_path_from(base_directory)
    if self.absolute? != base_directory.absolute?
      raise ArgumentError,
        "relative path between absolute and relative path: #{self.inspect}, #{base_directory.inspect}"
    end

    dest = []
    self.cleanpath.each_filename {|f|
      next if f == '.'
      dest << f
    }

    base = []
    base_directory.cleanpath.each_filename {|f|
      next if f == '.'
      base << f
    }

    while !base.empty? && !dest.empty? && base[0] == dest[0]
      base.shift
      dest.shift
    end

    if base.include? '..'
      raise ArgumentError, "base_directory has ..: #{base_directory.inspect}"
    end

    base.fill '..'
    relpath = base + dest
    if relpath.empty?
      Pathname.new(".")
    else
      Pathname.new(relpath.join('/'))
    end
  end
rename(to)

See File.rename. Rename the file.

[Source]

# File pathname.rb, line 641
  def rename(to) File.rename(@path, to) end
rmdir()

See Dir.rmdir. Remove the referenced directory.

[Source]

# File pathname.rb, line 808
  def rmdir() Dir.rmdir(@path) end
rmtree()

See FileUtils.rm_r. Deletes a directory and all beneath it.

[Source]

# File pathname.rb, line 849
  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
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/...

[Source]

# File pathname.rb, line 398
  def root?
    %r{\A/+\z} =~ @path ? true : false
  end
setgid?()

See FileTest.setgid?.

[Source]

# File pathname.rb, line 735
  def setgid?() FileTest.setgid?(@path) end
setuid?()

See FileTest.setuid?.

[Source]

# File pathname.rb, line 732
  def setuid?() FileTest.setuid?(@path) end
size()

See FileTest.size.

[Source]

# File pathname.rb, line 738
  def size() FileTest.size(@path) end
size?()

See FileTest.size?.

[Source]

# File pathname.rb, line 741
  def size?() FileTest.size?(@path) end
socket?()

See FileTest.socket?.

[Source]

# File pathname.rb, line 720
  def socket?() FileTest.socket?(@path) end
split()

See File.split. Returns the dirname and the basename in an Array.

[Source]

# File pathname.rb, line 672
  def split() File.split(@path).map {|f| Pathname.new(f) } end
stat()

See File.stat. Returns a File::Stat object.

[Source]

# File pathname.rb, line 644
  def stat() File.stat(@path) end
sticky?()

See FileTest.sticky?.

[Source]

# File pathname.rb, line 744
  def sticky?() FileTest.sticky?(@path) end
symlink(old)

Pathname#symlink is confusing and obsoleted because the receiver/argument order is inverted to corresponding system call.

[Source]

# File pathname.rb, line 683
  def symlink(old)
    warn 'Pathname#symlink is obsoleted.  Use Pathname#make_symlink.'
    File.symlink(old, @path)
  end
symlink?()

See FileTest.symlink?.

[Source]

# File pathname.rb, line 747
  def symlink?() FileTest.symlink?(@path) end
sysopen(*args)

See IO.sysopen.

[Source]

# File pathname.rb, line 591
  def sysopen(*args) IO.sysopen(@path, *args) end
taint()

[Source]

# File pathname.rb, line 199
  def taint() super; @path.taint; self end
to_s()

Return the path as a String.

[Source]

# File pathname.rb, line 225
  def to_s
    @path.dup
  end
to_str()

Alias for to_s

truncate(length)

See File.truncate. Truncate the file to length bytes.

[Source]

# File pathname.rb, line 653
  def truncate(length) File.truncate(@path, length) end
unlink()

Removes a file or directory, using File.unlink or Dir.unlink as necessary.

[Source]

# File pathname.rb, line 862
  def unlink()
    begin
      Dir.unlink @path
    rescue Errno::ENOTDIR
      File.unlink @path
    end
  end
untaint()

[Source]

# File pathname.rb, line 200
  def untaint() super; @path.untaint; self end
utime(atime, mtime)

See File.utime. Update the access and modification times.

[Source]

# File pathname.rb, line 656
  def utime(atime, mtime) File.utime(atime, mtime, @path) end
writable?()

See FileTest.writable?.

[Source]

# File pathname.rb, line 750
  def writable?() FileTest.writable?(@path) end
writable_real?()

See FileTest.writable_real?.

[Source]

# File pathname.rb, line 753
  def writable_real?() FileTest.writable_real?(@path) end
zero?()

See FileTest.zero?.

[Source]

# File pathname.rb, line 756
  def zero?() FileTest.zero?(@path) end


File: pathname.rb

pathname.rb

Path: | pathname.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

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 test/unit


File: ping.rb

ping.rb

Path: | ping.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005
 ping.rb -- check a host for upness

SYNOPSIS

   require 'ping'
    print "'jimmy' is alive and kicking\n" if Ping.pingecho('jimmy', 10) ;

DESCRIPTION

 This module contains routines to test for the reachability of remote hosts.
 Currently the only routine implemented is pingecho().

 pingecho() uses a TCP echo (I<not> an ICMP one) to determine if the
 remote host is reachable. This is usually adequate to tell that a remote
 host is available to rsh(1), ftp(1), or telnet(1) onto.

Parameters

  : hostname

    The remote host to check, specified either as a hostname or as an
    IP address.

  : timeout

    The timeout in seconds. If not specified it will default to 5 seconds.

  : service

    The service port to connect.  The default is "echo".

WARNING

 pingecho() uses user-level thread to implement the timeout, so it may block
 for long period if named does not respond for some reason.

end

Required files

timeout socket


Module: Ping

Module | Ping
In: | ping.rb

Methods

pingecho

Public Instance methods

pingecho(host, timeout=5, service="echo")

[Source]

# File 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


File: pp.rb

pp.rb

Path: | pp.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

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)

[Source]

# File pp.rb, line 453
    def pretty_print(q)
      q.text inspect
    end
pretty_print_cycle(q)

[Source]

# File pp.rb, line 445
    def pretty_print_cycle(q)
      q.text inspect
    end


Class: Array

Class | Array
In: | pp.rb
Parent: | Object

Methods

pretty_print pretty_print_cycle

Public Instance methods

pretty_print(q)

[Source]

# File pp.rb, line 287
  def pretty_print(q)
    q.group(1, '[', ']') {
      q.seplist(self) {|v|
        q.pp v
      }
    }
  end
pretty_print_cycle(q)

[Source]

# File pp.rb, line 295
  def pretty_print_cycle(q)
    q.text(empty? ? '[]' : '[...]')
  end


Class: File

Class | File
In: | pp.rb
Parent: | Object

Classes and Modules

Class File::Stat


Class: File::Stat

Class | File::Stat
In: | pp.rb
Parent: | Object

Methods

pretty_print

Public Instance methods

pretty_print(q)

[Source]

# File pp.rb, line 348
    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


Class: Hash

Class | Hash
In: | pp.rb
Parent: | Object

Methods

pretty_print pretty_print_cycle

Public Instance methods

pretty_print(q)

[Source]

# File pp.rb, line 301
  def pretty_print(q)
    q.pp_hash self
  end
pretty_print_cycle(q)

[Source]

# File pp.rb, line 305
  def pretty_print_cycle(q)
    q.text(empty? ? '{}' : '{...}')
  end


Module: Kernel

Module | Kernel
In: | pp.rb


Class: MatchData

Class | MatchData
In: | pp.rb
Parent: | Object

Methods

pretty_print

Public Instance methods

pretty_print(q)

[Source]

# File pp.rb, line 429
  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


Class: Object

Class | Object
In: | pp.rb
Parent: | Object

Included Modules

PP::ObjectMixin


Class: PP

Class | PP
In: | 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.

[Source]

# File pp.rb, line 67
  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(obj, out=$>)

Outputs obj to out like PP.pp but with no indent and newline.

PP.singleline_pp returns out.

[Source]

# File pp.rb, line 79
  def PP.singleline_pp(obj, out=$>)
    q = SingleLine.new(out)
    q.guard_inspect_key {q.pp obj}
    q.flush
    out
  end


Module: PP::ObjectMixin

Module | PP::ObjectMixin
In: | 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.

[Source]

# File pp.rb, line 243
    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(q)

A default pretty printing method for general objects that are detected as part of a cycle.

[Source]

# File pp.rb, line 255
    def pretty_print_cycle(q)
      q.object_address_group(self) {
        q.breakable
        q.text '...'
      }
    end
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.

[Source]

# File pp.rb, line 277
    def pretty_print_inspect
      if /\(PP::ObjectMixin\)#/ =~ method(:pretty_print).inspect
        raise "pretty_print is not overridden."
      end
      PP.singleline_pp(self, '')
    end
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]+.

[Source]

# File pp.rb, line 266
    def pretty_print_instance_variables
      instance_variables.sort
    end


Module: PP::PPMethods

Module | PP::PPMethods
In: | 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

[Source]

# File pp.rb, line 149
    def comma_breakable
      text ','
      breakable
    end
guard_inspect_key() {|| ...}

[Source]

# File pp.rb, line 96
    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
object_address_group(obj, &block)

[Source]

# File pp.rb, line 139
    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
object_group(obj) {|| ...}

A convenience method which is same as follows:

  group(1, '#<' + obj.class.name, '>') { ... }

[Source]

# File pp.rb, line 135
    def object_group(obj, &block) # :yield:
      group(1, '#<' + obj.class.name, '>', &block)
    end
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.

[Source]

# File pp.rb, line 116
    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
pp_hash(obj)

[Source]

# File pp.rb, line 206
    def pp_hash(obj)
      group(1, '{', '}') {
        seplist(obj, nil, :each_pair) {|k, v|
          group {
            pp k
            text '=>'
            group(1) {
              breakable ''
              pp v
            }
          }
        }
      }
    end
pp_object(obj)

[Source]

# File pp.rb, line 191
    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
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

[Source]

# File pp.rb, line 178
    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


Class: PP::SingleLine

Class | PP::SingleLine
In: | pp.rb
Parent: | PrettyPrint::SingleLine

Included Modules

PPMethods


Class: Range

Class | Range
In: | pp.rb
Parent: | Object

Methods

pretty_print

Public Instance methods

pretty_print(q)

[Source]

# File pp.rb, line 337
  def pretty_print(q)
    q.pp self.begin
    q.breakable ''
    q.text(self.exclude_end? ? '...' : '..')
    q.breakable ''
    q.pp self.end
  end


Class: Struct

Class | Struct
In: | pp.rb
Parent: | Object

Methods

pretty_print pretty_print_cycle

Public Instance methods

pretty_print(q)

[Source]

# File pp.rb, line 317
  def pretty_print(q)
    q.group(1, '#<struct ' + self.class.name, '>') {
      q.seplist(self.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(q)

[Source]

# File pp.rb, line 331
  def pretty_print_cycle(q)
    q.text sprintf("#<struct %s:...>", self.class.name)
  end


Class: PrettyPrint

Class | PrettyPrint
In: | prettyprint.rb
Parent: | Object

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| ...}

[Source]

# File prettyprint.rb, line 129
  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
new(output='', maxwidth=79, newline="\n", &genspace)

[Source]

# File prettyprint.rb, line 142
  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
singleline_format(output='', maxwidth=nil, newline=nil, genspace=nil) {|q| ...}

[Source]

# File prettyprint.rb, line 136
  def PrettyPrint.singleline_format(output='', maxwidth=nil, newline=nil, genspace=nil)
    q = SingleLine.new(output)
    yield q
    output
  end

Public Instance methods

break_outmost_groups()

[Source]

# File prettyprint.rb, line 169
  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
breakable(sep=' ', width=sep.length)

[Source]

# File prettyprint.rb, line 205
  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
current_group()

[Source]

# File prettyprint.rb, line 160
  def current_group
    @group_stack.last
  end
fill_breakable(sep=' ', width=sep.length)

[Source]

# File prettyprint.rb, line 201
  def fill_breakable(sep=' ', width=sep.length)
    group { breakable sep, width }
  end
first?()

[Source]

# File prettyprint.rb, line 164
  def first?
    warn "PrettyPrint#first? is obsoleted at 1.8.2."
    current_group.first?
  end
flush()

[Source]

# File prettyprint.rb, line 253
  def flush
    @buffer.each {|data|
      @output_width = data.output(@output, @output_width)
    }
    @buffer.clear
    @buffer_width = 0
  end
group(indent=0, open_obj='', close_obj='', open_width=open_obj.length, close_width=close_obj.length) {|| ...}

[Source]

# File prettyprint.rb, line 220
  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() {|| ...}

[Source]

# File prettyprint.rb, line 230
  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(indent) {|| ...}

[Source]

# File prettyprint.rb, line 244
  def nest(indent)
    @indent += indent
    begin
      yield
    ensure
      @indent -= indent
    end
  end
text(obj, width=obj.length)

[Source]

# File prettyprint.rb, line 185
  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


Class: Fill

Class | Fill
In: | prettyprint.rb
Parent: | Test::Unit::TestCase

Methods

format test_00_06 test_07_10 test_11_14 test_15_18 test_19_22 test_23_26 test_27

Public Instance methods

format(width)

[Source]

# File prettyprint.rb, line 846
    def format(width)
      PrettyPrint.format('', width) {|q|
        q.group {
          q.text 'abc'
          q.fill_breakable
          q.text 'def'
          q.fill_breakable
          q.text 'ghi'
          q.fill_breakable
          q.text 'jkl'
          q.fill_breakable
          q.text 'mno'
          q.fill_breakable
          q.text 'pqr'
          q.fill_breakable
          q.text 'stu'
        }
      }
    end
test_00_06()

[Source]

# File prettyprint.rb, line 866
    def test_00_06
      expected = "abc\ndef\nghi\njkl\nmno\npqr\nstu\n".chomp
      assert_equal(expected, format(0))
      assert_equal(expected, format(6))
    end
test_07_10()

[Source]

# File prettyprint.rb, line 881
    def test_07_10
      expected = "abc def\nghi jkl\nmno pqr\nstu\n".chomp
      assert_equal(expected, format(7))
      assert_equal(expected, format(10))
    end
test_11_14()

[Source]

# File prettyprint.rb, line 893
    def test_11_14
      expected = "abc def ghi\njkl mno pqr\nstu\n".chomp
      assert_equal(expected, format(11))
      assert_equal(expected, format(14))
    end
test_15_18()

[Source]

# File prettyprint.rb, line 904
    def test_15_18
      expected = "abc def ghi jkl\nmno pqr stu\n".chomp
      assert_equal(expected, format(15))
      assert_equal(expected, format(18))
    end
test_19_22()

[Source]

# File prettyprint.rb, line 914
    def test_19_22
      expected = "abc def ghi jkl mno\npqr stu\n".chomp
      assert_equal(expected, format(19))
      assert_equal(expected, format(22))
    end
test_23_26()

[Source]

# File prettyprint.rb, line 924
    def test_23_26
      expected = "abc def ghi jkl mno pqr\nstu\n".chomp
      assert_equal(expected, format(23))
      assert_equal(expected, format(26))
    end
test_27()

[Source]

# File prettyprint.rb, line 934
    def test_27
      expected = "abc def ghi jkl mno pqr stu\n".chomp
      assert_equal(expected, format(27))
    end


Class: NonString

Class | NonString
In: | prettyprint.rb
Parent: | Test::Unit::TestCase

Methods

format test_6 test_7

Public Instance methods

format(width)

[Source]

# File prettyprint.rb, line 827
    def format(width)
      PrettyPrint.format([], width, 'newline', lambda {|n| "#{n} spaces"}) {|q|
        q.text(3, 3)
        q.breakable(1, 1)
        q.text(3, 3)
      }
    end
test_6()

[Source]

# File prettyprint.rb, line 835
    def test_6
      assert_equal([3, "newline", "0 spaces", 3], format(6))
    end
test_7()

[Source]

# File prettyprint.rb, line 839
    def test_7
      assert_equal([3, 1, 3], format(7))
    end


Class: PrettyPrint::Breakable

Class | PrettyPrint::Breakable
In: | prettyprint.rb
Parent: | Object

Methods

new output

Attributes

indent | [R]
obj | [R]
width | [R]

Public Class methods

new(sep, width, q)

[Source]

# File prettyprint.rb, line 280
    def initialize(sep, width, q)
      @obj = sep
      @width = width
      @pp = q
      @indent = q.indent
      @group = q.current_group
      @group.breakables.push self
    end

Public Instance methods

output(out, output_width)

[Source]

# File prettyprint.rb, line 290
    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


Class: PrettyPrint::Group

Class | PrettyPrint::Group
In: | prettyprint.rb
Parent: | Object

Methods

break break? first? new

Attributes

breakables | [R]
depth | [R]

Public Class methods

new(depth)

[Source]

# File prettyprint.rb, line 305
    def initialize(depth)
      @depth = depth
      @breakables = []
      @break = false
    end

Public Instance methods

break()

[Source]

# File prettyprint.rb, line 312
    def break
      @break = true
    end
break?()

[Source]

# File prettyprint.rb, line 316
    def break?
      @break
    end
first?()

[Source]

# File prettyprint.rb, line 320
    def first?
      if defined? @first
        false
      else
        @first = false
        true
      end
    end


Class: PrettyPrint::GroupQueue

Class | PrettyPrint::GroupQueue
In: | prettyprint.rb
Parent: | Object

Methods

delete deq enq new

Public Class methods

new(*groups)

[Source]

# File prettyprint.rb, line 331
    def initialize(*groups)
      @queue = []
      groups.each {|g| enq g}
    end

Public Instance methods

delete(group)

[Source]

# File prettyprint.rb, line 357
    def delete(group)
      @queue[group.depth].delete(group)
    end
deq()

[Source]

# File prettyprint.rb, line 342
    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
enq(group)

[Source]

# File prettyprint.rb, line 336
    def enq(group)
      depth = group.depth
      @queue << [] until depth < @queue.length
      @queue[depth] << group
    end


Class: PrettyPrint::SingleLine

Class | PrettyPrint::SingleLine
In: | prettyprint.rb
Parent: | Object

Methods

breakable first? flush group nest new text

Public Class methods

new(output, maxwidth=nil, newline=nil)

[Source]

# File prettyprint.rb, line 363
    def initialize(output, maxwidth=nil, newline=nil)
      @output = output
      @first = [true]
    end

Public Instance methods

breakable(sep=' ', width=nil)

[Source]

# File prettyprint.rb, line 372
    def breakable(sep=' ', width=nil)
      @output << sep
    end
first?()

[Source]

# File prettyprint.rb, line 391
    def first?
      result = @first[-1]
      @first[-1] = false
      result
    end
flush()

[Source]

# File prettyprint.rb, line 388
    def flush
    end
group(indent=nil, open_obj='', close_obj='', open_width=nil, close_width=nil) {|| ...}

[Source]

# File prettyprint.rb, line 380
    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
nest(indent) {|| ...}

[Source]

# File prettyprint.rb, line 376
    def nest(indent)
      yield
    end
text(obj, width=nil)

[Source]

# File prettyprint.rb, line 368
    def text(obj, width=nil)
      @output << obj
    end


Class: PrettyPrint::Text

Class | PrettyPrint::Text
In: | prettyprint.rb
Parent: | Object

Methods

add new output

Attributes

width [R]

Public Class methods

new()

[Source]

# File prettyprint.rb, line 262
    def initialize
      @objs = []
      @width = 0
    end

Public Instance methods

add(obj, width)

[Source]

# File prettyprint.rb, line 273
    def add(obj, width)
      @objs << obj
      @width += width
    end
output(out, output_width)

[Source]

# File prettyprint.rb, line 268
    def output(out, output_width)
      @objs.each {|obj| out << obj}
      output_width + @width
    end


Class: StrictPrettyExample

Class | StrictPrettyExample
In: | prettyprint.rb
Parent: | Test::Unit::TestCase

Methods

prog test_00_04 test_05 test_06 test_07 test_08 test_09 test_10 test_11_31 test_32

Public Instance methods

prog(width)

[Source]

# File prettyprint.rb, line 653
    def prog(width)
      PrettyPrint.format('', width) {|q|
        q.group {
          q.group {q.nest(2) {
                       q.text "if"; q.breakable;
                       q.group {
                         q.nest(2) {
                           q.group {q.text "a"; q.breakable; q.text "=="}
                           q.breakable; q.text "b"}}}}
          q.breakable
          q.group {q.nest(2) {
                       q.text "then"; q.breakable;
                       q.group {
                         q.nest(2) {
                           q.group {q.text "a"; q.breakable; q.text "<<"}
                           q.breakable; q.text "2"}}}}
          q.breakable
          q.group {q.nest(2) {
                       q.text "else"; q.breakable;
                       q.group {
                         q.nest(2) {
                           q.group {q.text "a"; q.breakable; q.text "+"}
                           q.breakable; q.text "b"}}}}}
      }
    end
test_00_04()

[Source]

# File prettyprint.rb, line 679
    def test_00_04
      expected = "if\n  a\n    ==\n    b\nthen\n  a\n    <<\n    2\nelse\n  a\n    +\n    b\n".chomp
      assert_equal(expected, prog(0))
      assert_equal(expected, prog(4))
    end
test_05()

[Source]

# File prettyprint.rb, line 699
    def test_05
      expected = "if\n  a\n    ==\n    b\nthen\n  a\n    <<\n    2\nelse\n  a +\n    b\n".chomp
      assert_equal(expected, prog(5))
    end
test_06()

[Source]

# File prettyprint.rb, line 717
    def test_06
      expected = "if\n  a ==\n    b\nthen\n  a <<\n    2\nelse\n  a +\n    b\n".chomp
      assert_equal(expected, prog(6))
    end
test_07()

[Source]

# File prettyprint.rb, line 733
    def test_07
      expected = "if\n  a ==\n    b\nthen\n  a <<\n    2\nelse\n  a + b\n".chomp
      assert_equal(expected, prog(7))
    end
test_08()

[Source]

# File prettyprint.rb, line 748
    def test_08
      expected = "if\n  a == b\nthen\n  a << 2\nelse\n  a + b\n".chomp
      assert_equal(expected, prog(8))
    end
test_09()

[Source]

# File prettyprint.rb, line 761
    def test_09
      expected = "if a == b\nthen\n  a << 2\nelse\n  a + b\n".chomp
      assert_equal(expected, prog(9))
    end
test_10()

[Source]

# File prettyprint.rb, line 773
    def test_10
      expected = "if a == b\nthen\n  a << 2\nelse a + b\n".chomp
      assert_equal(expected, prog(10))
    end
test_11_31()

[Source]

# File prettyprint.rb, line 784
    def test_11_31
      expected = "if a == b\nthen a << 2\nelse a + b\n".chomp
      assert_equal(expected, prog(11))
      assert_equal(expected, prog(15))
      assert_equal(expected, prog(31))
    end
test_32()

[Source]

# File prettyprint.rb, line 796
    def test_32
      expected = "if a == b then a << 2 else a + b\n".chomp
      assert_equal(expected, prog(32))
    end


Class: TailGroup

Class | TailGroup
In: | prettyprint.rb
Parent: | Test::Unit::TestCase

Methods

test_1

Public Instance methods

test_1()

[Source]

# File prettyprint.rb, line 807
    def test_1
      out = PrettyPrint.format('', 10) {|q|
        q.group {
          q.group {
            q.text "abc"
            q.breakable
            q.text "def"
          }
          q.group {
            q.text "ghi"
            q.breakable
            q.text "jkl"
          }
        }
      }
      assert_equal("abc defghi\njkl", out)
    end


Class: WadlerExample

Class | WadlerExample
In: | prettyprint.rb
Parent: | Test::Unit::TestCase

Methods

hello setup test_hello_00_06 test_hello_07_08 test_hello_09_10 test_hello_11_12 test_hello_13 test_tree_00_19 test_tree_20_22 test_tree_23_43 test_tree_44 test_tree_alt_00_18 test_tree_alt_19_20 test_tree_alt_20_49 test_tree_alt_50 tree tree_alt

Classes and Modules

Class WadlerExample::Tree

Public Instance methods

hello(width)

[Source]

# File prettyprint.rb, line 412
    def hello(width)
      PrettyPrint.format('', width) {|hello|
        hello.group {
          hello.group {
            hello.group {
              hello.group {
                hello.text 'hello'
                hello.breakable; hello.text 'a'
              }
              hello.breakable; hello.text 'b'
            }
            hello.breakable; hello.text 'c'
          }
          hello.breakable; hello.text 'd'
        }
      }
    end
setup()

[Source]

# File prettyprint.rb, line 403
    def setup
      @tree = Tree.new("aaaa", Tree.new("bbbbb", Tree.new("ccc"),
                                                 Tree.new("dd")),
                               Tree.new("eee"),
                               Tree.new("ffff", Tree.new("gg"),
                                                Tree.new("hhh"),
                                                Tree.new("ii")))
    end
test_hello_00_06()

[Source]

# File prettyprint.rb, line 430
    def test_hello_00_06
      expected = "hello\na\nb\nc\nd\n".chomp
      assert_equal(expected, hello(0))
      assert_equal(expected, hello(6))
    end
test_hello_07_08()

[Source]

# File prettyprint.rb, line 443
    def test_hello_07_08
      expected = "hello a\nb\nc\nd\n".chomp
      assert_equal(expected, hello(7))
      assert_equal(expected, hello(8))
    end
test_hello_09_10()

[Source]

# File prettyprint.rb, line 455
    def test_hello_09_10
      expected = "hello a b\nc\nd\n".chomp
      out = hello(9); assert_equal(expected, out)
      out = hello(10); assert_equal(expected, out)
    end
test_hello_11_12()

[Source]

# File prettyprint.rb, line 466
    def test_hello_11_12
      expected = "hello a b c\nd\n".chomp
      assert_equal(expected, hello(11))
      assert_equal(expected, hello(12))
    end
test_hello_13()

[Source]

# File prettyprint.rb, line 476
    def test_hello_13
      expected = "hello a b c d\n".chomp
      assert_equal(expected, hello(13))
    end
test_tree_00_19()

[Source]

# File prettyprint.rb, line 488
    def test_tree_00_19
      expected = "aaaa[bbbbb[ccc,\n           dd],\n     eee,\n     ffff[gg,\n          hhh,\n          ii]]\n".chomp
      assert_equal(expected, tree(0))
      assert_equal(expected, tree(19))
    end
test_tree_20_22()

[Source]

# File prettyprint.rb, line 502
    def test_tree_20_22
      expected = "aaaa[bbbbb[ccc, dd],\n     eee,\n     ffff[gg,\n          hhh,\n          ii]]\n".chomp
      assert_equal(expected, tree(20))
      assert_equal(expected, tree(22))
    end
test_tree_23_43()

[Source]

# File prettyprint.rb, line 515
    def test_tree_23_43
      expected = "aaaa[bbbbb[ccc, dd],\n     eee,\n     ffff[gg, hhh, ii]]\n".chomp
      assert_equal(expected, tree(23))
      assert_equal(expected, tree(43))
    end
test_tree_44()

[Source]

# File prettyprint.rb, line 526
    def test_tree_44
      assert_equal("aaaa[bbbbb[ccc, dd], eee, ffff[gg, hhh, ii]]\n".chomp, tree(44))
    end
test_tree_alt_00_18()

[Source]

# File prettyprint.rb, line 537
    def test_tree_alt_00_18
      expected = "aaaa[\n  bbbbb[\n    ccc,\n    dd\n  ],\n  eee,\n  ffff[\n    gg,\n    hhh,\n    ii\n  ]\n]\n".chomp
      assert_equal(expected, tree_alt(0))
      assert_equal(expected, tree_alt(18))
    end
test_tree_alt_19_20()

[Source]

# File prettyprint.rb, line 557
    def test_tree_alt_19_20
      expected = "aaaa[\n  bbbbb[ ccc, dd ],\n  eee,\n  ffff[\n    gg,\n    hhh,\n    ii\n  ]\n]\n".chomp
      assert_equal(expected, tree_alt(19))
      assert_equal(expected, tree_alt(20))
    end
test_tree_alt_20_49()

[Source]

# File prettyprint.rb, line 574
    def test_tree_alt_20_49
      expected = "aaaa[\n  bbbbb[ ccc, dd ],\n  eee,\n  ffff[ gg, hhh, ii ]\n]\n".chomp
      assert_equal(expected, tree_alt(21))
      assert_equal(expected, tree_alt(49))
    end
test_tree_alt_50()

[Source]

# File prettyprint.rb, line 587
    def test_tree_alt_50
      expected = "aaaa[ bbbbb[ ccc, dd ], eee, ffff[ gg, hhh, ii ] ]\n".chomp
      assert_equal(expected, tree_alt(50))
    end
tree(width)

[Source]

# File prettyprint.rb, line 484
    def tree(width)
      PrettyPrint.format('', width) {|q| @tree.show(q)}
    end
tree_alt(width)

[Source]

# File prettyprint.rb, line 533
    def tree_alt(width)
      PrettyPrint.format('', width) {|q| @tree.altshow(q)}
    end


Class: WadlerExample::Tree

Class | WadlerExample::Tree
In: | prettyprint.rb
Parent: | Object

Methods

altshow new show

Public Class methods

new(string, *children)

[Source]

# File prettyprint.rb, line 596
      def initialize(string, *children)
        @string = string
        @children = children
      end

Public Instance methods

altshow(q)

[Source]

# File prettyprint.rb, line 625
      def altshow(q)
        q.group {
          q.text @string
          unless @children.empty?
            q.text '['
            q.nest(2) {
              q.breakable
              first = true
              @children.each {|t|
                if first
                  first = false
                else
                  q.text ','
                  q.breakable
                end
                t.altshow(q)
              }
            }
            q.breakable
            q.text ']'
          end
        }
      end
show(q)

[Source]

# File prettyprint.rb, line 601
      def show(q)
        q.group {
          q.text @string
          q.nest(@string.length) {
            unless @children.empty?
              q.text '['
              q.nest(1) {
                first = true
                @children.each {|t|
                  if first
                    first = false
                  else
                    q.text ','
                    q.breakable
                  end
                  t.show(q)
                }
              }
              q.text ']'
            end
          }
        }
      end


File: prettyprint.rb

prettyprint.rb

Path: | prettyprint.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

$Id$

Required files

test/unit


File: profile.rb

profile.rb

Path: | profile.rb
Last Update: | Fri Dec 20 19:00:10 AUS Eastern Daylight Time 2002

Required files

profiler


File: profiler.rb

profiler.rb

Path: | profiler.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

Methods

print_profile start_profile stop_profile

Public Instance methods

print_profile(f)

[Source]

# File 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
start_profile()

[Source]

# File profiler.rb, line 23
  def start_profile
    @@start = Process.times[0]
    @@stack = []
    @@map = {}
    set_trace_func PROFILE_PROC
  end
stop_profile()

[Source]

# File profiler.rb, line 29
  def stop_profile
    set_trace_func nil
  end


Module: Profiler__

Module | Profiler__
In: | profiler.rb

Constants

PROFILE_PROC = proc{|event, file, line, id, binding, klass| case event


Class: PStore

Class | PStore
In: | 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

Public Class methods

new(file)

To construct a PStore object, pass in the file path where you would like the data to be stored.

[Source]

# File pstore.rb, line 89
  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

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.

[Source]

# File pstore.rb, line 123
  def [](name)
    in_transaction
    @table[name]
  end
[]=(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.

[Source]

# File pstore.rb, line 167
  def []=(name, value)
    in_transaction_wr()
    @table[name] = value
  end
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.

[Source]

# File pstore.rb, line 255
  def abort
    in_transaction
    @abort = true
    throw :pstore_abort_transaction
  end
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.

[Source]

# File pstore.rb, line 229
  def commit
    in_transaction
    @abort = false
    throw :pstore_abort_transaction
  end
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.

[Source]

# File pstore.rb, line 177
  def delete(name)
    in_transaction_wr()
    @table.delete name
  end
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.

[Source]

# File pstore.rb, line 137
  def fetch(name, default=PStore::Error)
    unless @table.key? name
      if default==PStore::Error
        raise PStore::Error, format("undefined root name `%s'", name)
      else
        default
      end
    end
    self[name]
  end
path()

Returns the path to the data store file.

[Source]

# File pstore.rb, line 203
  def path
    @filename
  end
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.

[Source]

# File pstore.rb, line 198
  def root?(name)
    in_transaction
    @table.key? name
  end
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.

[Source]

# File pstore.rb, line 188
  def roots
    in_transaction
    @table.keys
  end
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.

[Source]

# File pstore.rb, line 278
  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, File::RDWR | File::CREAT)
        file.binmode
        file.flock(File::LOCK_EX)
        commit_new(file) if FileTest.exist?(new_file)
        content = file.read()
      else
        begin
          file = File.open(@filename, File::RDONLY)
          file.binmode
          file.flock(File::LOCK_SH)
          content = (File.read(new_file) 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, "w") {|t|
              t.binmode
              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


Class: PStore::Error

Class | PStore::Error
In: | pstore.rb
Parent: | StandardError

The error type thrown by all PStore methods.


File: pstore.rb

pstore.rb

Path: | pstore.rb
Last Update: | Sat Oct 29 10:38:09 AUS Eastern Standard Time 2005

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


Module: PTY

Module | PTY
In: | pty/pty.c

Methods

getpty protect_signal reset_signal spawn

Classes and Modules

Class PTY::ChildExited

Public Instance methods

getpty(...)

ruby function: getpty

[Source]

/* ruby function: getpty */
static VALUE
pty_getpty(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    VALUE res;
    struct pty_info info;
    struct pty_info thinfo;
    OpenFile *wfptr,*rfptr;
    VALUE rport = rb_obj_alloc(rb_cFile);
    VALUE wport = rb_obj_alloc(rb_cFile);

    MakeOpenFile(rport, rfptr);
    MakeOpenFile(wport, wfptr);

    establishShell(argc, argv, &info);

    rfptr->mode = rb_io_mode_flags("r");
    rfptr->f = fdopen(info.fd, "r");
    rfptr->path = strdup(SlaveName);

    wfptr->mode = rb_io_mode_flags("w") | FMODE_SYNC;
    wfptr->f = fdopen(dup(info.fd), "w");
    wfptr->path = strdup(SlaveName);

    res = rb_ary_new2(3);
    rb_ary_store(res,0,(VALUE)rport);
    rb_ary_store(res,1,(VALUE)wport);
    rb_ary_store(res,2,INT2FIX(info.child_pid));

    thinfo.thread = rb_thread_create(pty_syswait, (void*)&info);
    thinfo.child_pid = info.child_pid;
    rb_thread_schedule();

    if (rb_block_given_p()) {
    rb_ensure(rb_yield, res, pty_finalize_syswait, (VALUE)&thinfo);
    return Qnil;
    }
    return res;
}
protect_signal()

ruby function: protect_signal - obsolete

[Source]

/* ruby function: protect_signal - obsolete */
static VALUE
pty_protect(self)
    VALUE self;
{
    rb_warn("PTY::protect_signal is no longer needed");
    rb_yield(Qnil);
    return self;
}
reset_signal()

ruby function: reset_signal - obsolete

[Source]

/* ruby function: reset_signal - obsolete */
static VALUE
pty_reset_signal(self)
    VALUE self;
{
    rb_warn("PTY::reset_signal is no longer needed");
    return self;
}
spawn(...)

ruby function: getpty

[Source]

/* ruby function: getpty */
static VALUE
pty_getpty(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    VALUE res;
    struct pty_info info;
    struct pty_info thinfo;
    OpenFile *wfptr,*rfptr;
    VALUE rport = rb_obj_alloc(rb_cFile);
    VALUE wport = rb_obj_alloc(rb_cFile);

    MakeOpenFile(rport, rfptr);
    MakeOpenFile(wport, wfptr);

    establishShell(argc, argv, &info);

    rfptr->mode = rb_io_mode_flags("r");
    rfptr->f = fdopen(info.fd, "r");
    rfptr->path = strdup(SlaveName);

    wfptr->mode = rb_io_mode_flags("w") | FMODE_SYNC;
    wfptr->f = fdopen(dup(info.fd), "w");
    wfptr->path = strdup(SlaveName);

    res = rb_ary_new2(3);
    rb_ary_store(res,0,(VALUE)rport);
    rb_ary_store(res,1,(VALUE)wport);
    rb_ary_store(res,2,INT2FIX(info.child_pid));

    thinfo.thread = rb_thread_create(pty_syswait, (void*)&info);
    thinfo.child_pid = info.child_pid;
    rb_thread_schedule();

    if (rb_block_given_p()) {
    rb_ensure(rb_yield, res, pty_finalize_syswait, (VALUE)&thinfo);
    return Qnil;
    }
    return res;
}


Class: IO

Class | IO
In: | pty/lib/expect.rb
Parent: | Object

Methods

expect

Public Instance methods

expect(pat,timeout=9999999) {|result| ...}

[Source]

# File pty/lib/expect.rb, line 4
  def expect(pat,timeout=9999999)
    buf = ''
    case pat
    when String
      e_pat = Regexp.new(Regexp.quote(pat))
    when Regexp
      e_pat = pat
    end
    while true
      if IO.select([self],nil,nil,timeout).nil? then
        result = nil
        break
      end
      c = getc.chr
      buf << c
      if $expect_verbose
        STDOUT.print c
        STDOUT.flush
      end
      if mat=e_pat.match(buf) then
        result = [buf,*mat.to_a[1..-1]]
        break
      end
    end
    if block_given? then
      yield result
    else
      return result
    end
    nil
  end


Class: PTY::ChildExited

Class | PTY::ChildExited
In: | pty/pty.c
Parent: | RuntimeError

Methods

status

Public Instance methods

status()


File: expect_sample.rb

expect_sample.rb

Path: | pty/expect_sample.rb
Last Update: | Thu Nov 06 17:22:35 AUS Eastern Daylight Time 2003

sample program of expect.rb

 by A. Ito

 This program reports the latest version of ruby interpreter
 by connecting to ftp server at ruby-lang.org.

Required files

pty expect


File: expect.rb

expect.rb

Path: | pty/lib/expect.rb
Last Update: | Tue Aug 13 19:21:18 AUS Eastern Standard Time 2002


File: pty.c

pty.c

Path: | pty/pty.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: script.rb

script.rb

Path: | pty/script.rb
Last Update: | Fri Mar 07 15:59:42 AUS Eastern Daylight Time 2003

Required files

pty


File: shl.rb

shl.rb

Path: | pty/shl.rb
Last Update: | Mon Nov 19 15:02:15 AUS Eastern Daylight Time 2001

old-fashioned ‘shl’ like program by A. Ito

commands:

   c        creates new shell
   C-z      suspends shell
   p        lists all shell
   0,1,...  choose shell
   q        quit

Required files

pty

Methods

writer

Public Instance methods

writer()

[Source]

# File pty/shl.rb, line 20
def writer
  system "stty -echo raw"
  begin
    while true
      c = STDIN.getc
      if c == 26 then # C-z
        $reader.raise(nil)
        return 'Suspend'
      end
      $w_pty.print c.chr
      $w_pty.flush
    end
  rescue
    $reader.raise(nil)
    return 'Exit'
  ensure
    system "stty echo -raw"
  end
end


Module: Racc

Module | Racc
In: | racc/cparse/cparse.c

Classes and Modules

Class Racc::CparseParams
Class Racc::Parser


Class: Racc::CparseParams

Class | Racc::CparseParams
In: | racc/cparse/cparse.c
Parent: | Object


Class: Racc::Parser

Class | Racc::Parser
In: | racc/cparse/cparse.c
Parent: | Object

Methods

_racc_do_parse_c _racc_yyparse_c

Public Instance methods

_racc_do_parse_c(p1, p2)
_racc_yyparse_c(p1, p2, p3, p4)


File: cparse.c

cparse.c

Path: | racc/cparse/cparse.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: parser.rb

parser.rb

Path: | racc/parser.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

parser.rb

Copyright © 1999-2003 Minero Aoki <aamine@loveruby.net>

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.

$raccId: parser.rb,v 1.4 2003/11/03 13:41:47 aamine Exp $

Required files

racc/cparse

Constants

NotImplementedError | = | NotImplementError
ParseError | = | Racc::ParseError


Module: Racc

Module | Racc
In: | racc/parser.rb

Classes and Modules

Class Racc::ParseError
Class Racc::Parser

Constants

Racc_No_Extentions = false


Class: Racc::ParseError

Class | Racc::ParseError
In: | racc/parser.rb
Parent: | StandardError


Class: Racc::Parser

Class | Racc::Parser
In: | racc/parser.rb
Parent: | Object

Methods

racc_runtime_type

Constants

Racc_Runtime_Version | = | '1.4.4'
Racc_Runtime_Revision | = | '$raccRevision: 1.4 $'.split[1]
Racc_Runtime_Core_Version_R | = | '1.4.4'
Racc_Runtime_Core_Revision_R | = | '$raccRevision: 1.4 $'.split[1]
Racc_Runtime_Core_Revision_C | = | Racc_Runtime_Core_Id_C.split[2] | Racc_Runtime_Core_Version_C = (defined in extension)
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()

[Source]

# File racc/parser.rb, line 65
    def Parser.racc_runtime_type
      Racc_Runtime_Type
    end


File: rational.rb

rational.rb

Path: | rational.rb
Last Update: | Tue Oct 25 16:40:52 AUS Eastern Standard Time 2005
  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

[Source]

# File rational.rb, line 31
def Rational(a, b = 1)
  if a.kind_of?(Rational) && b == 1
    a
  else
    Rational.reduce(a, b)
  end
end


Class: Bignum

Class | Bignum
In: | rational.rb
Parent: | Object

Methods

** quo rdiv rpower

External Aliases

** -> power!

Public Instance methods

**(other)

Alias for rpower

quo(other)

If Rational is defined, returns a Rational number instead of a Bignum.

[Source]

# File rational.rb, line 535
  def quo(other)
    Rational.new!(self,1) / other
  end
rdiv(other)

Alias for quo

rpower(other)

Returns a Rational number if the result is in fact rational (i.e. other < 0).

[Source]

# File rational.rb, line 541
  def rpower (other)
    if other >= 0
      self.power!(other)
    else
      Rational.new!(self, 1)**other
    end
  end


Class: Fixnum

Class | Fixnum
In: | rational.rb
Parent: | Object

Methods

** quo rdiv rpower

External Aliases

** -> power!

Public Instance methods

**(other)

Alias for rpower

quo(other)

If Rational is defined, returns a Rational number instead of a Fixnum.

[Source]

# File rational.rb, line 508
  def quo(other)
    Rational.new!(self,1) / other
  end
rdiv(other)

Alias for quo

rpower(other)

Returns a Rational number if the result is in fact rational (i.e. other < 0).

[Source]

# File rational.rb, line 514
  def rpower (other)
    if other >= 0
      self.power!(other)
    else
      Rational.new!(self,1)**other
    end
  end


Class: Integer

Class | Integer
In: | rational.rb
Parent: | Object

Methods

denominator gcd gcd2 gcdlcm lcm numerator to_r

Public Instance methods

denominator()

In an integer, the denominator is 1. Therefore, this method returns 1.

[Source]

# File rational.rb, line 417
  def denominator
    1
  end
gcd(n)

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.

[Source]

# File rational.rb, line 438
  def gcd(n)
    m = self.abs
    n = n.abs

    return n if m == 0
    return m if n == 0

    b = 0
    while n[0] == 0 && m[0] == 0
      b += 1; n >>= 1; m >>= 1
    end
    m >>= 1 while m[0] == 0
    n >>= 1 while n[0] == 0
    while m != n
      m, n = n, m if n > m
      m -= n; m >>= 1 while m[0] == 0
    end
    m << b
  end
gcd2(int)

[Source]

# File rational.rb, line 458
  def gcd2(int)
    a = self.abs
    b = int.abs

    a, b = b, a if a < b

    while b != 0
      void, a = a.divmod(b)
      a, b = b, a
    end
    return a
  end
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]

[Source]

# File rational.rb, line 495
  def gcdlcm(other)
    gcd = self.gcd(other)
    if self.zero? or other.zero?
      [gcd, 0]
    else
      [gcd, (self.div(gcd) * other).abs]
    end
  end
lcm(other)

Returns the lowest common multiple (LCM) of the two arguments (self and other).

Examples:

  6.lcm 7        # -> 42
  6.lcm 9        # -> 18

[Source]

# File rational.rb, line 479
  def lcm(other)
    if self.zero? or other.zero?
      0
    else
      (self.div(self.gcd(other)) * other).abs
    end
  end
numerator()

In an integer, the value is the numerator of its rational equivalent. Therefore, this method returns self.

[Source]

# File rational.rb, line 410
  def numerator
    self
  end
to_r()

Returns a Rational representation of this integer.

[Source]

# File rational.rb, line 424
  def to_r
    Rational(self, 1)
  end


Class: Rational

Class | Rational
In: | rational.rb
Parent: | Numeric

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 new new! reduce to_f to_i to_r to_s

Attributes

denominator | [R]
numerator | [R]

Public Class methods

new(num, den)

This method is actually private.

[Source]

# File 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
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.

[Source]

# File rational.rb, line 93
  def Rational.new!(num, den = 1)
    new(num, den)
  end
reduce(num, den = 1)

Reduces the given numerator and denominator to their lowest terms. Use Rational() instead.

[Source]

# File 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

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

[Source]

# File rational.rb, line 253
  def % (other)
    value = (self / other).to_i
    return self - other * value
  end
*(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)

[Source]

# File 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
**(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

[Source]

# File 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
+(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

[Source]

# File 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
-(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

[Source]

# File 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
/(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)

[Source]

# File 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
<=>(other)

Standard comparison operator.

[Source]

# File 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
==(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!

[Source]

# File 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
abs()

Returns the absolute value.

[Source]

# File rational.rb, line 273
  def abs
    if @numerator > 0
      Rational.new!(@numerator, @denominator)
    else
      Rational.new!(-@numerator, @denominator)
    end
  end
coerce(other)

[Source]

# File 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
divmod(other)

Returns the quotient and remainder.

Examples:

  r = Rational(7,4)        # -> Rational(7,4)
  r.divmod Rational(1,2)   # -> [3, Rational(1,4)]

[Source]

# File rational.rb, line 265
  def divmod(other)
    value = (self / other).to_i
    return value, self - other * value
  end
hash()

Returns a hash code for the object.

[Source]

# File rational.rb, line 395
  def hash
    @numerator.hash ^ @denominator.hash
  end
inspect()

Returns a reconstructable string representation:

  Rational(5,8).inspect     # -> "Rational(5, 8)"

[Source]

# File rational.rb, line 388
  def inspect
    sprintf("Rational(%s, %s)", @numerator.inspect, @denominator.inspect)
  end
to_f()

Converts the rational to a Float.

[Source]

# File rational.rb, line 357
  def to_f
    @numerator.to_f/@denominator.to_f
  end
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

[Source]

# File rational.rb, line 350
  def to_i
    Integer(@numerator.div(@denominator))
  end
to_r()

Returns self.

[Source]

# File rational.rb, line 379
  def to_r
    self
  end
to_s()

Returns a string representation of the rational number.

Example:

  Rational(3,4).to_s          #  "3/4"
  Rational(8).to_s            #  "8"

[Source]

# File rational.rb, line 368
  def to_s
    if @denominator == 1
      @numerator.to_s
    else
      @numerator.to_s+"/"+@denominator.to_s
    end
  end


File: README

README

Path: | rdoc/README
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

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 © 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.

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 :section: 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
       # ----------------------------------------
   # 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 © 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.


Module: DOT

Module | DOT
In: | 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

[Source]

# File rdoc/dot/dot.rb, line 8
    def change_tab( t )
        $tab = t
        $tab2 = t * 2
    end


Class: DOT::DOTDigraph

Class | DOT::DOTDigraph
In: | rdoc/dot/dot.rb
Parent: | DOTSubgraph

this is graph

Methods

new

Public Class methods

new( params = {}, option_list = GRAPH_OPTS )

[Source]

# File rdoc/dot/dot.rb, line 228
        def initialize( params = {}, option_list = GRAPH_OPTS )
            super( params, option_list )
            @dot_string = 'digraph'
        end


Class: DOT::DOTEdge

Class | DOT::DOTEdge
In: | 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 )

[Source]

# File 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

Public Instance methods

to_s( t = '' )

[Source]

# File 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


Class: DOT::DOTElement

Class | DOT::DOTElement
In: | 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 = [] )

[Source]

# File 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

Public Instance methods

each_option() {|i| ...}

[Source]

# File rdoc/dot/dot.rb, line 108
        def each_option
            @options.each{ |i| yield i }
        end
each_option_pair() {|key, val| ...}

[Source]

# File rdoc/dot/dot.rb, line 112
        def each_option_pair
            @options.each_pair{ |key, val| yield key, val }
        end


Class: DOT::DOTNode

Class | DOT::DOTNode
In: | 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 )

[Source]

# File rdoc/dot/dot.rb, line 140
        def initialize( params = {}, option_list = NODE_OPTS )
            super( params, option_list )
            @ports = params['ports'] ? params['ports'] : []
        end

Public Instance methods

<<( thing )

[Source]

# File rdoc/dot/dot.rb, line 149
        def << ( thing )
            @ports << thing
        end
each_port() {|i| ...}

[Source]

# File rdoc/dot/dot.rb, line 145
        def each_port
            @ports.each{ |i| yield i }
        end
pop()

[Source]

# File rdoc/dot/dot.rb, line 157
        def pop
            @ports.pop
        end
push( thing )

[Source]

# File rdoc/dot/dot.rb, line 153
        def push ( thing )
            @ports.push( thing )
        end
to_s( t = '' )

[Source]

# File 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


Class: DOT::DOTPort

Class | DOT::DOTPort
In: | 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 = {} )

[Source]

# File rdoc/dot/dot.rb, line 128
        def initialize( params = {} )
            super( params )
            @name = params['label'] ? params['label'] : ''
        end

Public Instance methods

to_s()

[Source]

# File rdoc/dot/dot.rb, line 132
        def to_s
            ( @name && @name != "" ? "<#{@name}>" : "" ) + "#{@label}"
        end


Class: DOT::DOTSimpleElement

Class | DOT::DOTSimpleElement
In: | 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 = {} )

[Source]

# File rdoc/dot/dot.rb, line 83
        def initialize( params = {} )
            @label = params['name'] ? params['name'] : ''
        end

Public Instance methods

to_s()

[Source]

# File rdoc/dot/dot.rb, line 87
        def to_s
            @name
        end


Class: DOT::DOTSubgraph

Class | DOT::DOTSubgraph
In: | 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 )

[Source]

# File 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

Public Instance methods

<<( thing )

[Source]

# File rdoc/dot/dot.rb, line 198
        def << ( thing )
            @nodes << thing
        end
each_node() {|i| ...}

[Source]

# File rdoc/dot/dot.rb, line 194
        def each_node
            @nodes.each{ |i| yield i }
        end
pop()

[Source]

# File rdoc/dot/dot.rb, line 206
        def pop
            @nodes.pop
        end
push( thing )

[Source]

# File rdoc/dot/dot.rb, line 202
        def push( thing )
            @nodes.push( thing )
        end
to_s( t = '' )

[Source]

# File 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


Class: DefaultDisplay

Class | DefaultDisplay
In: | 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)

[Source]

# File rdoc/ri/ri_display.rb, line 41
  def initialize(options)
    @options = options
    @formatter = @options.formatter.new(@options, "     ")
  end

Public Instance methods

display_class_info(klass, ri_reader)

[Source]

# File 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_class_list(namespaces)

[Source]

# File 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
display_method_info(method)

[Source]

# File 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_method_list(methods)

Display a list of method names

[Source]

# File 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_usage()

[Source]

# File rdoc/ri/ri_display.rb, line 49
  def display_usage
    page do
      RI::Options::OptionList.usage(short_form=true)
    end
  end
list_known_classes(classes)

[Source]

# File 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(names)

[Source]

# File 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


Module: Generators

Module | Generators
In: | rdoc/generators/xml_generator.rb rdoc/generators/ri_generator.rb rdoc/generators/html_generator.rb 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: | 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)

[Source]

# File rdoc/generators/html_generator.rb, line 73
    def AllReferences.[](name)
      @@refs[name]
    end
add(name, html_class)

[Source]

# File rdoc/generators/html_generator.rb, line 69
    def AllReferences.add(name, html_class)
      @@refs[name] = html_class
    end
keys()

[Source]

# File rdoc/generators/html_generator.rb, line 77
    def AllReferences.keys
      @@refs.keys
    end
reset()

[Source]

# File rdoc/generators/html_generator.rb, line 65
    def AllReferences::reset
      @@refs = {}
    end


Class: Generators::CHMGenerator

Class | Generators::CHMGenerator
In: | 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

[Source]

# File rdoc/generators/chm_generator.rb, line 10
    def CHMGenerator.for(options)
      CHMGenerator.new(options)
    end
new(*args)

[Source]

# File rdoc/generators/chm_generator.rb, line 15
    def initialize(*args)
      super
      @op_name = @options.op_name || "rdoc"
      check_for_html_help_workshop
    end

Public Instance methods

check_for_html_help_workshop()

[Source]

# File 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
compile_project()

Invoke the windows help compiler to compiler the project

[Source]

# File rdoc/generators/chm_generator.rb, line 105
    def compile_project
      system("\"#{HHC_PATH}\" #@project_name")
    end
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

[Source]

# File 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
create_help_project()

The project contains the project file, a table of contents and an index

[Source]

# File rdoc/generators/chm_generator.rb, line 45
    def create_help_project
      create_project_file
      create_contents_and_index
      compile_project
    end
create_project_file()

The project file links together all the various files that go to make up the help.

[Source]

# File 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
generate(info)

Generate the html as normal, then wrap it in a help project

[Source]

# File rdoc/generators/chm_generator.rb, line 37
    def generate(info)
      super
      @project_name = @op_name + ".hhp"
      create_help_project
    end


Class: Generators::ContextUser

Class | Generators::ContextUser
In: | 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)

[Source]

# File rdoc/generators/html_generator.rb, line 287
    def initialize(context, options)
      @context = context
      @options = options
    end

Public Instance methods

add_table_of_sections()

create table of contents if we contain sections

[Source]

# File rdoc/generators/html_generator.rb, line 558
    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
aref_to(target)

[Source]

# File rdoc/generators/html_generator.rb, line 527
    def aref_to(target)
      if @options.all_one_file
        "#" + target
      else
        url(target)
      end
    end
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

[Source]

# File rdoc/generators/html_generator.rb, line 301
    def as_href(from_path)
      if @options.all_one_file
        "#" + path
      else
        HTMLGenerator.gen_url(from_path, path)
      end
    end
build_alias_summary_list(section)

Build a list of aliases for which we couldn’t find a corresponding method

[Source]

# File rdoc/generators/html_generator.rb, line 339
    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_class_list(level, from, section, infile=nil)

Build the structured list of classes and modules contained in this context.

[Source]

# File rdoc/generators/html_generator.rb, line 490
    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
build_constants_summary_list(section)

Build a list of constants

[Source]

# File rdoc/generators/html_generator.rb, line 356
    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_include_list(context)

[Source]

# File rdoc/generators/html_generator.rb, line 374
    def build_include_list(context)
      potentially_referenced_list(context.includes)
    end
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

[Source]

# File rdoc/generators/html_generator.rb, line 425
    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_method_summary_list(path_prefix="")

Build a summary list of all the methods in this context

[Source]

# File rdoc/generators/html_generator.rb, line 323
    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_requires_list(context)

[Source]

# File rdoc/generators/html_generator.rb, line 370
    def build_requires_list(context)
      potentially_referenced_list(context.requires) {|fn| [fn + ".rb"] }
    end
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.

[Source]

# File rdoc/generators/html_generator.rb, line 314
    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
diagram_reference(diagram)

[Source]

# File rdoc/generators/html_generator.rb, line 539
    def diagram_reference(diagram)
      res = diagram.gsub(/((?:src|href)=")(.*?)"/) {
        $1 + url($2) + '"'
      }
      res
    end
document_self()

[Source]

# File rdoc/generators/html_generator.rb, line 535
    def document_self
      @context.document_self
    end
find_symbol(symbol, method=nil)

Find a symbol in ourselves or our parent

[Source]

# File rdoc/generators/html_generator.rb, line 548
    def find_symbol(symbol, method=nil)
      res = @context.find_symbol(symbol, method)
      if res
        res = res.viewer
      end
      res
    end
href(link, cls, name)

convenience method to build a hyperlink

[Source]

# File rdoc/generators/html_generator.rb, line 293
    def href(link, cls, name)
      %{<a href="#{link}" class="#{cls}">#{name}</a>} #"
    end
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

[Source]

# File rdoc/generators/html_generator.rb, line 387
    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
url(target)

[Source]

# File rdoc/generators/html_generator.rb, line 523
    def url(target)
      HTMLGenerator.gen_url(path, target)
    end


Class: Generators::HTMLGenerator

Class | Generators::HTMLGenerator
In: | 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

[Source]

# File rdoc/generators/html_generator.rb, line 1153
    def HTMLGenerator.for(options)
      AllReferences::reset
      HtmlMethod::reset

      if options.all_one_file
        HTMLGeneratorInOne.new(options)
      else
        HTMLGenerator.new(options)
      end
    end
gen_url(path, target)

convert a target url to one that is relative to a given path

[Source]

# File rdoc/generators/html_generator.rb, line 1131
    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
new(options)

Set up a new HTML generator. Basically all we do here is load up the correct output temlate

[Source]

# File rdoc/generators/html_generator.rb, line 1171
    def initialize(options) #:not-new:
      @options    = options
      load_html_template
    end

Public Instance methods

generate(toplevels)

Build the initial indices and output objects based on an array of TopLevel objects containing the extracted information.

[Source]

# File rdoc/generators/html_generator.rb, line 1182
    def generate(toplevels)
      @toplevels  = toplevels
      @files      = []
      @classes    = []

      write_style_sheet
      gen_sub_directories()
      build_indices
      generate_html
    end


Class: Generators::HTMLGeneratorInOne

Class | Generators::HTMLGeneratorInOne
In: | 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)

[Source]

# File rdoc/generators/html_generator.rb, line 1393
    def initialize(*args)
      super
    end

Public Instance methods

build_class_list(from, html_file, class_dir)

[Source]

# File rdoc/generators/html_generator.rb, line 1433
    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
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)

[Source]

# File rdoc/generators/html_generator.rb, line 1422
    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
gen_an_index(collection, title)

[Source]

# File rdoc/generators/html_generator.rb, line 1486
    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
gen_class_index()

[Source]

# File rdoc/generators/html_generator.rb, line 1477
    def gen_class_index
      gen_an_index(@classes, 'Classes')
    end
gen_file_index()

[Source]

# File rdoc/generators/html_generator.rb, line 1473
    def gen_file_index
      gen_an_index(@files, 'Files')
    end
gen_into(list)

[Source]

# File rdoc/generators/html_generator.rb, line 1465
    def gen_into(list)
      res = []
      list.each do |item|
        res << item.value_hash
      end
      res
    end
gen_method_index()

[Source]

# File rdoc/generators/html_generator.rb, line 1481
    def gen_method_index
      gen_an_index(HtmlMethod.all_methods, 'Methods')
    end
generate(info)

Build the initial indices and output objects based on an array of TopLevel objects containing the extracted information.

[Source]

# File rdoc/generators/html_generator.rb, line 1402
    def generate(info)
      @toplevels  = info
      @files      = []
      @classes    = []
      @hyperlinks = {}

      build_indices
      generate_xml
    end
generate_xml()

Generate all the HTML. For the one-file case, we generate all the information in to one big hash

[Source]

# File rdoc/generators/html_generator.rb, line 1444
    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


Class: Generators::HtmlClass

Class | Generators::HtmlClass
In: | 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)

[Source]

# File rdoc/generators/html_generator.rb, line 583
    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

Public Instance methods

<=>(other)

[Source]

# File rdoc/generators/html_generator.rb, line 749
    def <=>(other)
      self.name <=> other.name
    end
build_attribute_list(section)

[Source]

# File rdoc/generators/html_generator.rb, line 679
    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()

[Source]

# File rdoc/generators/html_generator.rb, line 699
    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
http_url(full_name, prefix)

return the relative file name to store this class in, which is also its url

[Source]

# File rdoc/generators/html_generator.rb, line 605
    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
index_name()

[Source]

# File rdoc/generators/html_generator.rb, line 622
    def index_name
      name
    end
name()

[Source]

# File rdoc/generators/html_generator.rb, line 614
    def name
      @context.full_name
    end
parent_name()

[Source]

# File rdoc/generators/html_generator.rb, line 618
    def parent_name
      @context.parent.full_name
    end
value_hash()

[Source]

# File rdoc/generators/html_generator.rb, line 634
    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
write_on(f)

[Source]

# File rdoc/generators/html_generator.rb, line 626
    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


Class: Generators::HtmlFile

Class | Generators::HtmlFile
In: | 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)

[Source]

# File rdoc/generators/html_generator.rb, line 767
    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

Public Instance methods

<=>(other)

[Source]

# File rdoc/generators/html_generator.rb, line 884
    def <=>(other)
      self.name <=> other.name
    end
file_attribute_values()

[Source]

# File rdoc/generators/html_generator.rb, line 865
    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
filename_to_label()

[Source]

# File rdoc/generators/html_generator.rb, line 790
    def filename_to_label
      @context.file_relative_name.gsub(/%|\/|\?|\#/) {|s| '%' + ("%x" % s[0]) }
    end
http_url(file_dir)

[Source]

# File rdoc/generators/html_generator.rb, line 785
    def http_url(file_dir)
      File.join(file_dir, @context.file_relative_name.tr('.', '_')) +
        ".html"
    end
index_name()

[Source]

# File rdoc/generators/html_generator.rb, line 794
    def index_name
      name
    end
parent_name()

[Source]

# File rdoc/generators/html_generator.rb, line 798
    def parent_name
      nil
    end
value_hash()

[Source]

# File rdoc/generators/html_generator.rb, line 802
    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(f)

[Source]

# File rdoc/generators/html_generator.rb, line 857
    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


Class: Generators::HtmlMethod

Class | Generators::HtmlMethod
In: | 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()

[Source]

# File rdoc/generators/html_generator.rb, line 1037
    def HtmlMethod.all_methods
      @@all_methods
    end
new(context, html_class, options)

[Source]

# File rdoc/generators/html_generator.rb, line 907
    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
reset()

[Source]

# File rdoc/generators/html_generator.rb, line 903
    def HtmlMethod::reset
      @@all_methods = []
    end

Public Instance methods

<=>(other)

[Source]

# File rdoc/generators/html_generator.rb, line 1041
    def <=>(other)
      @context <=> other.context
    end
add_line_numbers(src)

we rely on the fact that the first line of a source code listing has

   # File xxxxx, line dddd

[Source]

# File rdoc/generators/html_generator.rb, line 1088
    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
aliases()

[Source]

# File rdoc/generators/html_generator.rb, line 1108
    def aliases
      @context.aliases
    end
aref()

[Source]

# File rdoc/generators/html_generator.rb, line 960
    def aref
      @seq
    end
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

[Source]

# File rdoc/generators/html_generator.rb, line 932
    def as_href(from_path)
      if @options.all_one_file
        "#" + path
      else
        HTMLGenerator.gen_url(from_path, path)
      end
    end
call_seq()

[Source]

# File rdoc/generators/html_generator.rb, line 984
    def call_seq
      cs = @context.call_seq
      if cs
        cs.gsub(/\n/, "<br />\n")
      else
        nil
      end
    end
create_source_code_file(code_body)

[Source]

# File rdoc/generators/html_generator.rb, line 1019
    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
description()

[Source]

# File rdoc/generators/html_generator.rb, line 972
    def description
      markup(@context.comment)
    end
document_self()

[Source]

# File rdoc/generators/html_generator.rb, line 1104
    def document_self
      @context.document_self
    end
find_symbol(symbol, method=nil)

[Source]

# File rdoc/generators/html_generator.rb, line 1112
    def find_symbol(symbol, method=nil)
      res = @context.parent.find_symbol(symbol, method)
      if res
        res = res.viewer
      end
      res
    end
index_name()

[Source]

# File rdoc/generators/html_generator.rb, line 948
    def index_name
      "#{@context.name} (#{@html_class.name})"
    end
markup_code(tokens)

Given a sequence of source tokens, mark up the source code to make it look purty.

[Source]

# File rdoc/generators/html_generator.rb, line 1050
    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
name()

[Source]

# File rdoc/generators/html_generator.rb, line 940
    def name
      @context.name
    end
params()

[Source]

# File rdoc/generators/html_generator.rb, line 993
    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
parent_name()

[Source]

# File rdoc/generators/html_generator.rb, line 952
    def parent_name
      if @context.parent.parent
        @context.parent.parent.full_name
      else
        nil
      end
    end
path()

[Source]

# File rdoc/generators/html_generator.rb, line 964
    def path
      if @options.all_one_file
        aref
      else
        @html_class.path + "#" + aref
      end
    end
section()

[Source]

# File rdoc/generators/html_generator.rb, line 944
    def section
      @context.section
    end
singleton()

[Source]

# File rdoc/generators/html_generator.rb, line 980
    def singleton
      @context.singleton
    end
visibility()

[Source]

# File rdoc/generators/html_generator.rb, line 976
    def visibility
      @context.visibility
    end


Class: Generators::HyperlinkHtml

Class | Generators::HyperlinkHtml
In: | 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

[Source]

# File 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

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

[Source]

# File rdoc/generators/html_generator.rb, line 135
    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_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.

[Source]

# File 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

      if /([A-Z].*)[.\#](.*)/ =~ 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
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.

[Source]

# File rdoc/generators/html_generator.rb, line 169
    def handle_special_HYPERLINK(special)
      url = special.text
      gen_url(url, url)
    end
handle_special_TIDYLINK(special)

HEre’s a hypedlink where the label is different to the URL

 <label>[url]

[Source]

# File rdoc/generators/html_generator.rb, line 178
    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


Module: Generators::MarkUp

Module | Generators::MarkUp
In: | 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.

[Source]

# File rdoc/generators/html_generator.rb, line 265
    def cvs_url(url, full_path)
      if /%s/ =~ url
        return sprintf( url, full_path )
      else
        return url + full_path
      end
    end
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.

[Source]

# File rdoc/generators/html_generator.rb, line 204
    def markup(str, remove_para=false)
      return '' unless str
      unless defined? @markup
        @markup = SM::SimpleMarkup.new

        # class names, variable names, file names, or instance variables
        @markup.add_special(/(
                               \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(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.

[Source]

# File rdoc/generators/html_generator.rb, line 251
    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


Class: Generators::RIGenerator

Class | Generators::RIGenerator
In: | 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

[Source]

# File rdoc/generators/ri_generator.rb, line 59
    def RIGenerator.for(options)
      new(options)
    end
new(options)

Set up a new HTML generator. Basically all we do here is load up the correct output temlate

[Source]

# File rdoc/generators/ri_generator.rb, line 70
    def initialize(options) #:not-new:
      @options   = options
      @ri_writer = RI::RiWriter.new(options.op_dir)
      @markup    = SM::SimpleMarkup.new
      @to_flow   = SM::ToFlow.new
    end

Public Instance methods

generate(toplevels)

Build the initial indices and output objects based on an array of TopLevel objects containing the extracted information.

[Source]

# File rdoc/generators/ri_generator.rb, line 83
    def generate(toplevels)
      RDoc::TopLevel.all_classes_and_modules.each do |cls|
        process_class(cls)
      end
    end
generate_class_info(cls)

[Source]

# File 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(cls_desc, method)

[Source]

# File 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
process_class(from_class)

[Source]

# File 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


Class: Generators::XMLGenerator

Class | Generators::XMLGenerator
In: | 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

[Source]

# File rdoc/generators/xml_generator.rb, line 16
    def XMLGenerator.for(options)
      XMLGenerator.new(options)
    end
new(*args)

[Source]

# File rdoc/generators/xml_generator.rb, line 21
    def initialize(*args)
      super
    end

Public Instance methods

build_class_list(from, html_file, class_dir)

[Source]

# File 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
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)

[Source]

# File 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
gen_an_index(collection, title)

[Source]

# File 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
gen_class_index()

[Source]

# File rdoc/generators/xml_generator.rb, line 104
    def gen_class_index
      gen_an_index(@classes, 'Classes')
    end
gen_file_index()

[Source]

# File rdoc/generators/xml_generator.rb, line 100
    def gen_file_index
      gen_an_index(@files, 'Files')
    end
gen_into(list)

[Source]

# File rdoc/generators/xml_generator.rb, line 92
    def gen_into(list)
      res = []
      list.each do |item|
        res << item.value_hash
      end
      res
    end
gen_method_index()

[Source]

# File rdoc/generators/xml_generator.rb, line 108
    def gen_method_index
      gen_an_index(HtmlMethod.all_methods, 'Methods')
    end
generate(info)

Build the initial indices and output objects based on an array of TopLevel objects containing the extracted information.

[Source]

# File rdoc/generators/xml_generator.rb, line 30
    def generate(info)
      @info       = info
      @files      = []
      @classes    = []
      @hyperlinks = {}

      build_indices
      generate_xml
    end
generate_xml()

Generate all the HTML. For the one-file case, we generate all the information in to one big hash

[Source]

# File 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


Class: NameDescriptor

Class | NameDescriptor
In: | 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

[Source]

# File 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

Public Instance methods

full_class_name()

Return the full class name (with ’::’ between the components) or "" if there’s no class name

[Source]

# File rdoc/ri/ri_util.rb, line 72
  def full_class_name
    @class_names.join("::")
  end


Class: Options

Class | Options
In: | 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
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

[Source]

# File rdoc/options.rb, line 342
  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

      @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 "--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()

[Source]

# File rdoc/options.rb, line 506
  def title
    @title ||= "RDoc Documentation"
  end
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

[Source]

# File rdoc/options.rb, line 513
  def title=(string)
    @title ||= string
  end


Module: Options::OptionList

Module | Options::OptionList
In: | 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." ], [ "--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

[Source]

# File rdoc/options.rb, line 256
    def OptionList.error(msg)
      $stderr.puts
      $stderr.puts msg
      $stderr.puts "\nFor help on options, try 'rdoc --help'\n\n"
      exit 1
    end
help_output()

[Source]

# File rdoc/options.rb, line 314
    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
options()

[Source]

# File rdoc/options.rb, line 236
    def OptionList.options
      OPTION_LIST.map do |long, short, arg,|
        [ long,
          short,
          arg ? GetoptLong::REQUIRED_ARGUMENT : GetoptLong::NO_ARGUMENT
        ]
      end
    end
strip_output(text)

[Source]

# File rdoc/options.rb, line 246
    def OptionList.strip_output(text)
      text =~ /^\s+/
      leading_spaces = $&
      text.gsub!(/^#{leading_spaces}/, '')
      $stdout.puts text
    end
usage(generator_names)

Show usage and exit

[Source]

# File rdoc/options.rb, line 265
    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


Module: RDoc

Module | RDoc
In: | rdoc/usage.rb rdoc/rdoc.rb rdoc/parsers/parse_simple.rb rdoc/parsers/parse_rb.rb rdoc/parsers/parse_f95.rb rdoc/parsers/parse_c.rb rdoc/parsers/parserfactory.rb rdoc/generators/template/xml/xml.rb rdoc/generators/template/xml/rdf.rb rdoc/generators/template/html/one_page_html.rb rdoc/generators/template/html/old_html.rb rdoc/generators/template/html/kilmer.rb rdoc/generators/template/html/html.rb rdoc/generators/template/html/hefss.rb rdoc/generators/template/chm/chm.rb rdoc/diagram.rb rdoc/code_objects.rb

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 © 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.

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

DOT_DOC_FILENAME = ".document" Name of the dotfile that contains the description of files to be processed in the current directory
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' ]
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"

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)

[Source]

# File 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(*args)

Display usage

[Source]

# File rdoc/usage.rb, line 98
  def RDoc.usage_no_exit(*args)
    main_program_file, = caller[-1].split(/:\d+/, 2)
    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


Class: RDoc::Alias

Class | RDoc::Alias
In: | 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)

[Source]

# File 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

Public Instance methods

to_s()

[Source]

# File rdoc/code_objects.rb, line 701
    def to_s
      "alias: #{self.old_name} ->  #{self.new_name}\n#{self.comment}"
    end


Class: RDoc::AnonClass

Class | RDoc::AnonClass
In: | rdoc/code_objects.rb
Parent: | ClassModule

Anonymous classes


Class: RDoc::AnyMethod

Class | RDoc::AnyMethod
In: | 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)

[Source]

# File 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

Public Instance methods

<=>(other)

[Source]

# File rdoc/code_objects.rb, line 650
    def <=>(other)
      @name <=> other.name
    end
add_alias(method)

[Source]

# File rdoc/code_objects.rb, line 682
    def add_alias(method)
      @aliases << method
    end
param_seq()

[Source]

# File 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
to_s()

[Source]

# File rdoc/code_objects.rb, line 654
    def to_s
      res = self.class.name + ": " + @name + " (" + @text + ")\n"
      res << @comment.to_s
      res
    end


Class: RDoc::Attr

Class | RDoc::Attr
In: | 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)

[Source]

# File 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

Public Instance methods

<=>(other)

[Source]

# File rdoc/code_objects.rb, line 735
    def <=>(other)
      self.name <=> other.name
    end
to_s()

[Source]

# File rdoc/code_objects.rb, line 731
    def to_s
      "attr: #{self.name} #{self.rw}\n#{self.comment}"
    end


Class: RDoc::C_Parser

Class | RDoc::C_Parser
In: | rdoc/parsers/parse_c.rb
Parent: | Object

See rdoc/c_parse.rb

Methods

new scan

Public Class methods

new(top_level, file_name, body, options, stats)

prepare to parse a C file

[Source]

# File rdoc/parsers/parse_c.rb, line 175
    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

Public Instance methods

scan()

Extract the classes/modules and methods from a C file and return the corresponding top-level object

[Source]

# File rdoc/parsers/parse_c.rb, line 188
    def scan
      remove_commented_out_lines
      do_classes
      do_constants
      do_methods
      do_includes
      do_aliases
      @top_level
    end


Class: RDoc::ClassModule

Class | RDoc::ClassModule
In: | 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)

[Source]

# File rdoc/code_objects.rb, line 556
    def initialize(name, superclass = nil)
      @name       = name
      @diagram    = nil
      @superclass = superclass
      @comment    = ""
      super()
    end

Public Instance methods

find_class_named(name)

[Source]

# File 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
full_name()

Return the fully qualified name of this class or module

[Source]

# File rdoc/code_objects.rb, line 565
    def full_name
      if @parent && @parent.full_name
        @parent.full_name + "::" + @name
      else
        @name
      end
    end
http_url(prefix)

[Source]

# File rdoc/code_objects.rb, line 573
    def http_url(prefix)
      path = full_name.split("::")
      File.join(prefix, *path) + ".html"
    end
is_module?()

Return true if this object represents a module

[Source]

# File rdoc/code_objects.rb, line 579
    def is_module?
      false
    end
to_s()

to_s is simply for debugging

[Source]

# File rdoc/code_objects.rb, line 584
    def to_s
      res = self.class.name + ": " + @name
      res << @comment.to_s
      res << super
      res
    end


Class: RDoc::CodeObject

Class | RDoc::CodeObject
In: | 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

[Source]

# File 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()

[Source]

# File rdoc/code_objects.rb, line 75
    def initialize
      @document_self = true
      @document_children = true
      @force_documentation = false
      @done_documenting = false
    end

Public Instance methods

comment=(comment)

Update the comment, but don’t overwrite a real comment with an empty one

[Source]

# File rdoc/code_objects.rb, line 87
    def comment=(comment)
      @comment = comment unless comment.empty?
    end
document_children=(val)

[Source]

# File rdoc/code_objects.rb, line 57
    def document_children=(val)
      @document_children = val
      if !val
        remove_classes_and_modules
      end
    end
document_self=(val)

[Source]

# File rdoc/code_objects.rb, line 34
    def document_self=(val)
      @document_self = val
      if !val
        remove_methods_etc
      end
    end
remove_classes_and_modules()

Default callbacks to nothing, but this is overridden for classes and modules

[Source]

# File rdoc/code_objects.rb, line 69
    def remove_classes_and_modules
    end
remove_methods_etc()

[Source]

# File rdoc/code_objects.rb, line 72
    def remove_methods_etc
    end
start_doc()

set and cleared by :startdoc: and :enddoc:, this is used to toggle the capturing of documentation

[Source]

# File rdoc/code_objects.rb, line 43
    def start_doc
      @document_self = true
      @document_children = true
    end
stop_doc()

[Source]

# File rdoc/code_objects.rb, line 48
    def stop_doc
      @document_self = false
      @document_children = false
    end


Class: RDoc::Constant

Class | RDoc::Constant
In: | rdoc/code_objects.rb
Parent: | CodeObject

Represent a constant

Methods

new

Attributes

name | [RW]
value | [RW]

Public Class methods

new(name, value, comment)

[Source]

# File rdoc/code_objects.rb, line 710
    def initialize(name, value, comment)
      super()
      @name = name
      @value = value
      self.comment = comment
    end


Class: RDoc::Context

Class | RDoc::Context
In: | 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()

[Source]

# File 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

Public Instance methods

<=>(other)

allow us to sort modules by name

[Source]

# File rdoc/code_objects.rb, line 370
    def <=>(other)
      name <=> other.name
    end
add_alias(an_alias)

[Source]

# File 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_attribute(an_attribute)

[Source]

# File rdoc/code_objects.rb, line 243
    def add_attribute(an_attribute)
      add_to(@attributes, an_attribute)
    end
add_class(class_type, name, superclass)

[Source]

# File rdoc/code_objects.rb, line 229
    def add_class(class_type, name, superclass)
      add_class_or_module(@classes, class_type, name, superclass)
    end
add_class_or_module(collection, class_type, name, superclass=nil)

[Source]

# File 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_constant(const)

[Source]

# File rdoc/code_objects.rb, line 266
    def add_constant(const)
      add_to(@constants, const)
    end
add_include(an_include)

[Source]

# File rdoc/code_objects.rb, line 262
    def add_include(an_include)
      add_to(@includes, an_include)
    end
add_method(a_method)

[Source]

# File 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_module(class_type, name)

[Source]

# File rdoc/code_objects.rb, line 233
    def add_module(class_type, name)
      add_class_or_module(@modules, class_type, name, nil)
    end
add_require(a_require)

Requires always get added to the top-level (file) context

[Source]

# File 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_to(array, thing)

[Source]

# File 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
classes()

map the class hash to an array externally

[Source]

# File rdoc/code_objects.rb, line 181
    def classes
      @classes.values
    end
defined_in?(file)

Return true if at least part of this thing was defined in file

[Source]

# File rdoc/code_objects.rb, line 225
    def defined_in?(file)
      @in_files.include?(file)
    end
each_attribute() {|a| ...}

[Source]

# File rdoc/code_objects.rb, line 352
    def each_attribute
      @attributes.each {|a| yield a}
    end
each_classmodule() {|m| ...}

Iterate over all the classes and modules in this object

[Source]

# File rdoc/code_objects.rb, line 343
    def each_classmodule
      @modules.each_value {|m| yield m}
      @classes.each_value {|c| yield c}
    end
each_constant() {|c| ...}

[Source]

# File rdoc/code_objects.rb, line 356
    def each_constant
      @constants.each {|c| yield c}
    end
each_method() {|m| ...}

[Source]

# File rdoc/code_objects.rb, line 348
    def each_method
      @method_list.each {|m| yield m}
    end
find_enclosing_module_named(name)

find a module at a higher scope

[Source]

# File rdoc/code_objects.rb, line 336
    def find_enclosing_module_named(name)
      parent && parent.find_module_named(name)
    end
find_local_symbol(symbol)

[Source]

# File 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
find_module_named(name)

Find a named module

[Source]

# File 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_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

[Source]

# File 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
initialize_classes_and_modules()

[Source]

# File rdoc/code_objects.rb, line 322
    def initialize_classes_and_modules
      @classes     = {}
      @modules     = {}
    end
initialize_methods_etc()

[Source]

# File rdoc/code_objects.rb, line 308
    def initialize_methods_etc
      @method_list = []
      @attributes  = []
      @aliases     = []
      @requires    = []
      @includes    = []
      @constants   = []
    end
modules()

map the module hash to an array externally

[Source]

# File rdoc/code_objects.rb, line 186
    def modules
      @modules.values
    end
ongoing_visibility=(vis)

Change the default visibility for new methods

[Source]

# File rdoc/code_objects.rb, line 191
    def ongoing_visibility=(vis)
      @visibility = vis
    end
record_location(toplevel)

Record the file that we happen to find it in

[Source]

# File rdoc/code_objects.rb, line 220
    def record_location(toplevel)
      @in_files << toplevel unless @in_files.include?(toplevel)
    end
remove_classes_and_modules()

and remove classes and modules when we see a :nodoc: all

[Source]

# File rdoc/code_objects.rb, line 318
    def remove_classes_and_modules
      initialize_classes_and_modules
    end
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

[Source]

# File rdoc/code_objects.rb, line 304
    def remove_methods_etc
      initialize_methods_etc
    end
set_current_section(title, comment)

Handle sections

[Source]

# File rdoc/code_objects.rb, line 431
    def set_current_section(title, comment)
      @current_section = Section.new(title, comment)
      @sections << @current_section
    end
set_visibility_for(methods, vis, singleton=false)

Given an array methods of method names, set the visibility of the corresponding AnyMethod object

[Source]

# File 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
toplevel()

Return the toplevel that owns us

[Source]

# File rdoc/code_objects.rb, line 362
    def toplevel
      return @toplevel if defined? @toplevel
      @toplevel = self
      @toplevel = @toplevel.parent until TopLevel === @toplevel
      @toplevel
    end


Class: RDoc::Context::Section

Class | RDoc::Context::Section
In: | rdoc/code_objects.rb
Parent: | Object

Contents

  • The title

Methods

new

Attributes

comment | [R]
sequence | [R]
title | [R]

Public Class methods

new(title, comment)

[Source]

# File rdoc/code_objects.rb, line 125
      def initialize(title, comment)
        @title = title
        @@sequence.succ!
        @sequence = @@sequence.dup
        set_comment(comment)
      end

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: | 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

[Source]

# File rdoc/diagram.rb, line 36
    def initialize(info, options)
      @info = info
      @options = options
      @counter = 0
      File.makedirs(DOT_PATH)
    end

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.

[Source]

# File rdoc/diagram.rb, line 47
    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',
                                    'label' => i.file_absolute_name,
                                    '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, i.name)

        # 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',
                                      'label' => i.full_name,
                                      '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,
                                       "Module: #{mod.name}")
        end
      end
      $stderr.puts unless @options.quiet
    end


Class: RDoc::Fortran95parser

Class | RDoc::Fortran95parser
In: | rdoc/parsers/parse_f95.rb
Parent: | Object

Methods

find_comments new progress scan

Public Class methods

new(top_level, file_name, body, options, stats)

prepare to parse a Fortran 95 file

[Source]

# File rdoc/parsers/parse_f95.rb, line 35
    def initialize(top_level, file_name, body, options, stats)
      @body = body
      @stats = stats
      @options = options
      @top_level = top_level
      @progress = $stderr unless options.quiet
    end

Public Instance methods

find_comments(text)

[Source]

# File rdoc/parsers/parse_f95.rb, line 97
    def find_comments text
      lines = text.split("\n").reverse
      comment_block = Array.new
      lines.each do |line|
        break if line =~ /^\s*\w/
        comment_block.unshift line.sub(/^!\s?/,"")
      end
      nice_lines = comment_block.join("\n").split "\n\s*\n"
      nice_lines.shift
      nice_lines.shift
      nice_lines.shift
    end
progress(char)

[Source]

# File rdoc/parsers/parse_f95.rb, line 110
    def progress(char)
      unless @options.quiet
        @progress.print(char)
        @progress.flush
      end
    end
scan()

devine code constructs

[Source]

# File rdoc/parsers/parse_f95.rb, line 44
    def scan

      # modules and programs
      if @body =~ /^(module|program)\s+(\w+)/i
        progress "m"
        f9x_module = @top_level.add_module NormalClass, $2
        f9x_module.record_location @top_level
        first_comment, second_comment = $`.gsub(/^!\s?/,"").split "\n\s*\n"
        if second_comment
          @top_level.comment = first_comment if first_comment
          f9x_module.comment = second_comment
        else
          f9x_module.comment = first_comment if first_comment
        end
      end

      # use modules
      remaining_code = @body
      while remaining_code =~ /^\s*use\s+(\w+)/i
        remaining_code = $~.post_match
        progress "."
        f9x_module.add_include Include.new($1, "") if f9x_module
      end

      # subroutines
      remaining_code = @body
      while remaining_code =~ /^\s*subroutine\s+(\w+)\s*\((.*?)\)/im
        remaining_code = $~.post_match
        subroutine = AnyMethod.new("Text", $1)
        subroutine.singleton = false

        prematchText = $~.pre_match
        params = $2
        params.gsub!(/&/,'')
        subroutine.params = params
        comment = find_comments prematchText
        subroutine.comment = comment if comment

        subroutine.start_collecting_tokens
        remaining_code =~ /^\s*end\s+subroutine/i
        code = "subroutine #{subroutine.name} (#{subroutine.params})\n"
        code += $~.pre_match
        code += "\nend subroutine\n"
        subroutine.add_token Token.new(1,1).set_text(code)

        progress "s"
        f9x_module.add_method subroutine if f9x_module
      end

      @top_level

    end


Class: RDoc::Include

Class | RDoc::Include
In: | rdoc/code_objects.rb
Parent: | CodeObject

an included module

Methods

new

Attributes

name [RW]

Public Class methods

new(name, comment)

[Source]

# File rdoc/code_objects.rb, line 757
    def initialize(name, comment)
      super()
      @name = name
      self.comment = comment
    end


Class: RDoc::NormalClass

Class | RDoc::NormalClass
In: | rdoc/code_objects.rb
Parent: | ClassModule

Normal classes


Class: RDoc::NormalModule

Class | RDoc::NormalModule
In: | rdoc/code_objects.rb
Parent: | ClassModule

Module

Methods

is_module?

Public Instance methods

is_module?()

[Source]

# File rdoc/code_objects.rb, line 612
    def is_module?
      true
    end


Module: RDoc::Page

Module | RDoc::Page
In: | rdoc/generators/template/xml/xml.rb rdoc/generators/template/xml/rdf.rb rdoc/generators/template/html/one_page_html.rb rdoc/generators/template/html/old_html.rb rdoc/generators/template/html/kilmer.rb rdoc/generators/template/html/html.rb rdoc/generators/template/html/hefss.rb rdoc/generators/template/chm/chm.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> }
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,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%">CVS</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%">CVS</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%">CVS</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%">CVS</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> .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%">CVS</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%">CVS</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>-></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> }
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%">CVS</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%">CVS</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> .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> <!-- 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
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> }

Public Instance methods

write_extra_pages()

[Source]

# File 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
write_extra_pages()

[Source]

# File 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


Module: RDoc::ParserFactory

Module | RDoc::ParserFactory
In: | 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"

[Source]

# File 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
can_parse(file_name)

Return a parser that can handle a particular extension

[Source]

# File rdoc/parsers/parserfactory.rb, line 62
    def ParserFactory.can_parse(file_name)
      @@parsers.find {|p| p.regexp.match(file_name) }
    end
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

[Source]

# File 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

Public Instance methods

parse_files_matching(regexp)

Record the fact that a particular class parses files that match a given extension

[Source]

# File rdoc/parsers/parserfactory.rb, line 56
    def parse_files_matching(regexp)
      @@parsers.unshift Parsers.new(regexp, self)
    end


Class: RDoc::RDoc

Class | RDoc::RDoc
In: | 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

[Source]

# File rdoc/rdoc.rb, line 231
    def document(argv)

      TopLevel::reset

      @stats = Stats.new

      options = Options.instance
      options.parse(argv, GENERATORS)

      unless options.all_one_file
        setup_output_dir(options.op_dir)
      end

      file_info = parse_files(options)

      gen = options.generator

      $stderr.puts "\nGenerating #{gen.key.upcase}..." unless options.quiet

      require gen.file_name

      gen_class = Generators.const_get(gen.class_name)

      unless file_info.empty?
        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)
        ensure
          Dir.chdir(pwd)
        end
      end

      unless options.quiet
        puts
        @stats.print
      end
    end


Class: RDoc::RDocError

Class | RDoc::RDocError
In: | 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: | rdoc/code_objects.rb
Parent: | CodeObject

a required file

Methods

new

Attributes

name [RW]

Public Class methods

new(name, comment)

[Source]

# File rdoc/code_objects.rb, line 745
    def initialize(name, comment)
      super()
      @name = name.gsub(/'|"/, "") #'
      self.comment = comment
    end


Class: RDoc::RubyParser

Class | RDoc::RubyParser
In: | 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)

[Source]

# File 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

Public Instance methods

scan()

[Source]

# File 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


Class: RDoc::SimpleParser

Class | RDoc::SimpleParser
In: | 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

[Source]

# File 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

Public Instance methods

remove_private_comments(comment)

[Source]

# File rdoc/parsers/parse_simple.rb, line 37
    def remove_private_comments(comment)
      comment.gsub(/^--.*?^\+\+/m, '').sub(/^--.*/m, '')
    end
scan()

Extract the file contents and attach them to the toplevel as a comment

[Source]

# File rdoc/parsers/parse_simple.rb, line 31
    def scan
      #    @body.gsub(/^(\s\n)+/, '')
      @top_level.comment = remove_private_comments(@body)
      @top_level
    end


Class: RDoc::SingleClass

Class | RDoc::SingleClass
In: | rdoc/code_objects.rb
Parent: | ClassModule

Singleton classes


Class: RDoc::Stats

Class | RDoc::Stats
In: | 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()

[Source]

# File rdoc/rdoc.rb, line 34
    def initialize
      @num_files = @num_classes = @num_modules = @num_methods = 0
      @start = Time.now
    end

Public Instance methods

print()

[Source]

# File rdoc/rdoc.rb, line 38
    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


Class: RDoc::Token

Class | RDoc::Token
In: | rdoc/parsers/parse_f95.rb
Parent: | Object

See rdoc/parsers/parse_f95.rb

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)

[Source]

# File rdoc/parsers/parse_f95.rb, line 13
    def initialize(line_no, char_no)
      @line_no = line_no
      @char_no = char_no
      @text    = NO_TEXT
    end

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

[Source]

# File rdoc/parsers/parse_f95.rb, line 20
    def set_text(text)
      @text = text
      self
    end


Class: RDoc::TopLevel

Class | RDoc::TopLevel
In: | 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()

[Source]

# File rdoc/code_objects.rb, line 518
    def TopLevel.all_classes_and_modules
      @@all_classes.values + @@all_modules.values
    end
find_class_named(name)

[Source]

# File 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
new(file_name)

[Source]

# File 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
reset()

[Source]

# File rdoc/code_objects.rb, line 472
    def TopLevel::reset
      @@all_classes = {}
      @@all_modules = {}
    end

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.

[Source]

# File 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
find_class_or_module_named(symbol)

[Source]

# File 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_local_symbol(symbol)

[Source]

# File rdoc/code_objects.rb, line 530
    def find_local_symbol(symbol)
      find_class_or_module_named(symbol) || super
    end
find_module_named(name)

Find a named module

[Source]

# File rdoc/code_objects.rb, line 541
    def find_module_named(name)
      find_class_or_module_named(name) || find_enclosing_module_named(name)
    end
full_name()

[Source]

# File rdoc/code_objects.rb, line 486
    def full_name
      nil
    end


Module: RI

Module | RI
In: | rdoc/ri/ri_writer.rb rdoc/ri/ri_reader.rb rdoc/ri/ri_paths.rb rdoc/ri/ri_options.rb rdoc/ri/ri_formatter.rb rdoc/ri/ri_descriptions.rb rdoc/ri/ri_cache.rb

Descriptions are created by RDoc (in ri_generator) and written out in serialized form into the documentation tree. ri then reads these to generate the documentation

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: | rdoc/ri/ri_descriptions.rb
Parent: | NamedThing

Alias = Struct.new(:old_name, :new_name)


Class: RI::AnsiFormatter

Class | RI::AnsiFormatter
In: | 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)

[Source]

# File rdoc/ri/ri_formatter.rb, line 405
    def initialize(*args)
      print "\033[0m"
      super
    end

Public Instance methods

bold_print(txt)

[Source]

# File rdoc/ri/ri_formatter.rb, line 426
    def bold_print(txt)
      print "\033[1m#{txt}\033[m"
    end
display_heading(text, level, indent)

[Source]

# File 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
write_attribute_text(prefix, line)

[Source]

# File 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


Class: RI::Attribute

Class | RI::Attribute
In: | rdoc/ri/ri_descriptions.rb
Parent: | NamedThing

Methods

new

Attributes

comment | [R]
rw | [R]

Public Class methods

new(name, rw, comment)

[Source]

# File rdoc/ri/ri_descriptions.rb, line 34
    def initialize(name, rw, comment)
      super(name)
      @rw = rw
      @comment = comment
    end


Class: RI::AttributeFormatter

Class | RI::AttributeFormatter
In: | 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

wrap

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

[Source]

# File 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


Class: RI::AttributeFormatter::AttrChar

Class | RI::AttributeFormatter::AttrChar
In: | rdoc/ri/ri_formatter.rb
Parent: | Object

TODO: struct?

Methods

new

Attributes

attr | [R]
char | [R]

Public Class methods

new(char, attr)

[Source]

# File rdoc/ri/ri_formatter.rb, line 260
      def initialize(char, attr)
        @char = char
        @attr = attr
      end


Class: RI::AttributeFormatter::AttributeString

Class | RI::AttributeFormatter::AttributeString
In: | rdoc/ri/ri_formatter.rb
Parent: | Object

Methods

<< empty? new next_word

Attributes

txt [R]

Public Class methods

new()

[Source]

# File rdoc/ri/ri_formatter.rb, line 270
      def initialize
        @txt = []
        @optr = 0
      end

Public Instance methods

<<(char)

[Source]

# File rdoc/ri/ri_formatter.rb, line 275
      def <<(char)
        @txt << char
      end
empty?()

[Source]

# File rdoc/ri/ri_formatter.rb, line 279
      def empty?
        @optr >= @txt.length
      end
next_word()

accept non space, then all following spaces

[Source]

# File 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


Class: RI::ClassDescription

Class | RI::ClassDescription
In: | rdoc/ri/ri_descriptions.rb
Parent: | ModuleDescription

Methods

display_name superclass_string

Attributes

superclass [RW]

Public Instance methods

display_name()

[Source]

# File rdoc/ri/ri_descriptions.rb, line 126
    def display_name
      "Class"
    end
superclass_string()

[Source]

# File rdoc/ri/ri_descriptions.rb, line 130
    def superclass_string
      if @superclass && @superclass != "Object"
        @superclass
      else
        nil
      end
    end


Class: RI::ClassEntry

Class | RI::ClassEntry
In: | 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)

[Source]

# File 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

Public Instance methods

add_path(path)

We found this class in more tha one place, so add in the name from there.

[Source]

# File rdoc/ri/ri_cache.rb, line 19
    def add_path(path)
      @path_names << path
    end
all_method_names()

Return a list of all out method names

[Source]

# File 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
classes_and_modules()

[Source]

# File rdoc/ri/ri_cache.rb, line 67
    def classes_and_modules
      @inferior_classes
    end
contained_class_named(name)

Return an exact match to a particular name

[Source]

# File rdoc/ri/ri_cache.rb, line 72
    def contained_class_named(name)
      @inferior_classes.find {|c| c.name == name}
    end
contained_modules_matching(name)

Return a list of any classes or modules that we contain that match a given string

[Source]

# File rdoc/ri/ri_cache.rb, line 63
    def contained_modules_matching(name)
      @inferior_classes.find_all {|c| c.name[name]}
    end
full_name()

Return our full name

[Source]

# File rdoc/ri/ri_cache.rb, line 95
    def full_name
      res = @in_class.full_name
      res << "::" unless res.empty?
      res << @name
    end
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

[Source]

# File 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
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

[Source]

# File 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(name, is_class_method)

Find methods matching ‘name’ in ourselves and in any classes we contain

[Source]

# File 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


Class: RI::Constant

Class | RI::Constant
In: | rdoc/ri/ri_descriptions.rb
Parent: | NamedThing

Methods

new

Attributes

comment | [R]
value | [R]

Public Class methods

new(name, value, comment)

[Source]

# File rdoc/ri/ri_descriptions.rb, line 43
    def initialize(name, value, comment)
      super(name)
      @value = value
      @comment = comment
    end


Class: RI::Description

Class | RI::Description
In: | rdoc/ri/ri_descriptions.rb
Parent: | Object

Methods

<=> deserialize serialize

Attributes

comment | [RW]
full_name | [RW]
name | [RW]

Public Class methods

deserialize(from)

[Source]

# File rdoc/ri/ri_descriptions.rb, line 71
    def Description.deserialize(from)
      YAML.load(from)
    end

Public Instance methods

<=>(other)

[Source]

# File rdoc/ri/ri_descriptions.rb, line 75
    def <=>(other)
      @name <=> other.name
    end
serialize()

[Source]

# File rdoc/ri/ri_descriptions.rb, line 67
    def serialize
      self.to_yaml
    end


Class: RI::HtmlFormatter

Class | RI::HtmlFormatter
In: | 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)

[Source]

# File rdoc/ri/ri_formatter.rb, line 470
    def initialize(*args)
      super
    end

Public Instance methods

blankline()

[Source]

# File rdoc/ri/ri_formatter.rb, line 498
    def blankline()
      puts("<p>")
    end
bold_print(txt)

[Source]

# File rdoc/ri/ri_formatter.rb, line 494
    def bold_print(txt)
      tag("b") { txt }
    end
break_to_newline()

[Source]

# File rdoc/ri/ri_formatter.rb, line 502
    def break_to_newline
      puts("<br>")
    end
display_heading(text, level, indent)

[Source]

# File 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(list)

[Source]

# File 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(item, prefix=@indent)

[Source]

# File rdoc/ri/ri_formatter.rb, line 555
    def display_verbatim_flow_item(item, prefix=@indent)
        print("<pre>")
        item.body.split(/\n/).each do |line|
          puts conv_html(line)
        end
        puts("</pre>")
    end
draw_line(label=nil)

[Source]

# File rdoc/ri/ri_formatter.rb, line 487
    def draw_line(label=nil)
      if label != nil
        bold_print(label)
      end
      puts("<hr>")
    end
write_attribute_text(prefix, line)

[Source]

# File 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


Class: RI::IncludedModule

Class | RI::IncludedModule
In: | rdoc/ri/ri_descriptions.rb
Parent: | NamedThing


Class: RI::MethodDescription

Class | RI::MethodDescription
In: | 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: | 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)

[Source]

# File 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

Public Instance methods

full_name()

[Source]

# File 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


Class: RI::MethodSummary

Class | RI::MethodSummary
In: | rdoc/ri/ri_descriptions.rb
Parent: | NamedThing

Methods

new

Public Class methods

new(name="")

[Source]

# File rdoc/ri/ri_descriptions.rb, line 55
    def initialize(name="")
      super
    end


Class: RI::ModuleDescription

Class | RI::ModuleDescription
In: | 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()

[Source]

# File rdoc/ri/ri_descriptions.rb, line 103
    def display_name
      "Module"
    end
merge_in(old)

merge in another class desscription into this one

[Source]

# File 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
        @comment << SM::Flow::RULE.new
        @comment.concat old.comment
      end
    end
superclass_string()

the ‘ClassDescription’ subclass overrides this to format up the name of a parent

[Source]

# File rdoc/ri/ri_descriptions.rb, line 109
    def superclass_string
      nil
    end


Class: RI::NamedThing

Class | RI::NamedThing
In: | rdoc/ri/ri_descriptions.rb
Parent: | Object

Methods

<=> eql? hash new

Attributes

name [R]

Public Class methods

new(name)

[Source]

# File rdoc/ri/ri_descriptions.rb, line 11
    def initialize(name)
      @name = name
    end

Public Instance methods

<=>(other)

[Source]

# File rdoc/ri/ri_descriptions.rb, line 14
    def <=>(other)
      @name <=> other.name
    end
eql?(other)

[Source]

# File rdoc/ri/ri_descriptions.rb, line 22
    def eql?(other)
      @name.eql?(other)
    end
hash()

[Source]

# File rdoc/ri/ri_descriptions.rb, line 18
    def hash
      @name.hash
    end


Class: RI::Options

Class | RI::Options
In: | rdoc/ri/ri_options.rb
Parent: | Object

Methods

displayer new parse paths 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()

[Source]

# File rdoc/ri/ri_options.rb, line 178
    def initialize
      @use_stdout   = !STDOUT.tty?
      @width        = 72
      @formatter    = RI::TextFormatter.for("plain")
      @list_classes = false
      @list_names   = false
    end

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)

[Source]

# File rdoc/ri/ri_options.rb, line 250
    def displayer
      ::RiDisplay.new(self)
    end
parse(args)

Parse command line options.

[Source]

# File rdoc/ri/ri_options.rb, line 189
    def parse(args)

      old_argv = ARGV.dup
#      if ENV["RI"]
#        ARGV.replace(ENV["RI"].split.concat(ARGV))
#      end

     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 "--doc-dir"
            if File.directory?(arg)
              @doc_dir = 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
paths()

Return the doc_dir as an array, or nil if no overriding doc dir was given

[Source]

# File rdoc/ri/ri_options.rb, line 242
    def paths
      defined?(@doc_dir) ? [ @doc_dir ] : nil
    end
show_version()

Show the version and exit

[Source]

# File rdoc/ri/ri_options.rb, line 172
    def show_version
      puts VERSION_STRING
      exit(0)
    end


Module: RI::Options::OptionList

Module | RI::Options::OptionList
In: | 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."], [ "--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

[Source]

# File rdoc/ri/ri_options.rb, line 95
      def OptionList.error(msg)
        $stderr.puts
        $stderr.puts msg
        $stderr.puts "\nFor help on options, try 'ri --help'\n\n"
        exit 1
      end
options()

[Source]

# File rdoc/ri/ri_options.rb, line 75
      def OptionList.options
        OPTION_LIST.map do |long, short, arg,|
          [ long,
           short,
           arg ? GetoptLong::REQUIRED_ARGUMENT : GetoptLong::NO_ARGUMENT
          ]
        end
      end
strip_output(text)

[Source]

# File rdoc/ri/ri_options.rb, line 85
      def OptionList.strip_output(text)
        text =~ /^\s+/
        leading_spaces = $&
        text.gsub!(/^#{leading_spaces}/, '')
        $stdout.puts text
      end
usage(short_form=false)

Show usage and exit

[Source]

# File rdoc/ri/ri_options.rb, line 104
      def OptionList.usage(short_form=false)

        puts
        puts(RI::VERSION_STRING)
        puts

        name = File.basename($0)
        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\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 = sprintf("%15s", "#{long}, #{short}")
            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


Class: RI::OverstrikeFormatter

Class | RI::OverstrikeFormatter
In: | 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

[Source]

# File rdoc/ri/ri_formatter.rb, line 390
    def bold_print(text)
      text.split(//).each do |ch|
        print ch, BS, ch
      end
    end
write_attribute_text(prefix, line)

[Source]

# File 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


Class: RI::RiCache

Class | RI::RiCache
In: | 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)

[Source]

# File 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


Class: RI::RiReader

Class | RI::RiReader
In: | 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)

[Source]

# File rdoc/ri/ri_reader.rb, line 8
    def initialize(ri_cache)
      @cache = ri_cache
    end

Public Instance methods

all_names()

return a list of all classes, modules, and methods

[Source]

# File rdoc/ri/ri_reader.rb, line 71
    def all_names
      res = []
      find_names_in(res, @cache.toplevel)
    end
find_class_by_name(full_name)

[Source]

# File 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(name, is_class_method, namespaces)

[Source]

# File 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
full_class_names()

return the names of all classes and modules

[Source]

# File rdoc/ri/ri_reader.rb, line 65
    def full_class_names
      res = []
      find_classes_in(res, @cache.toplevel)
    end
get_class(class_entry)

Return a class description

[Source]

# File 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
get_method(method_entry)

return the MethodDescription for a given MethodEntry by deserializing the YAML

[Source]

# File 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
lookup_namespace_in(target, namespaces)

[Source]

# File 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
top_level_namespace()

[Source]

# File rdoc/ri/ri_reader.rb, line 12
    def top_level_namespace
      [ @cache.toplevel ]
    end


Class: RI::RiWriter

Class | RI::RiWriter
In: | 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)

[Source]

# File rdoc/ri/ri_writer.rb, line 6
    def RiWriter.class_desc_path(dir, class_desc)
      File.join(dir, "cdesc-" + class_desc.name + ".yaml")
    end
external_to_internal(name)

And the reverse operation

[Source]

# File 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
internal_to_external(name)

Convert a name from internal form (containing punctuation) to an external form (where punctuation is replaced by %xx)

[Source]

# File rdoc/ri/ri_writer.rb, line 15
    def RiWriter.internal_to_external(name)
      name.gsub(/\W/) { sprintf("%%%02x", $&[0]) }
    end
new(base_dir)

[Source]

# File rdoc/ri/ri_writer.rb, line 24
    def initialize(base_dir)
      @base_dir = base_dir
    end

Public Instance methods

add_class(class_desc)

[Source]

# File 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(class_desc, method_desc)

[Source]

# File 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
remove_class(class_desc)

[Source]

# File rdoc/ri/ri_writer.rb, line 28
    def remove_class(class_desc)
      FileUtils.rm_rf(path_to_dir(class_desc.full_name))
    end


Class: RI::SimpleFormatter

Class | RI::SimpleFormatter
In: | 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

[Source]

# File rdoc/ri/ri_formatter.rb, line 617
    def blankline
    end
display_heading(text, level, indent)

Place heading level indicators inline with heading.

[Source]

# File rdoc/ri/ri_formatter.rb, line 635
    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
draw_line(label=nil)

Display labels only, no lines

[Source]

# File rdoc/ri/ri_formatter.rb, line 624
    def draw_line(label=nil)
      unless label.nil? then
        bold_print(label)
        puts
      end
    end


Class: RI::TextFormatter

Class | RI::TextFormatter
In: | 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)

[Source]

# File rdoc/ri/ri_formatter.rb, line 666
    def TextFormatter.for(name)
      FORMATTERS[name.downcase]
    end
list()

[Source]

# File rdoc/ri/ri_formatter.rb, line 662
    def TextFormatter.list
      FORMATTERS.keys.sort.join(", ")
    end
new(options, indent)

[Source]

# File rdoc/ri/ri_formatter.rb, line 6
    def initialize(options, indent)
      @options = options
      @width   = options.width
      @indent  = indent
    end

Public Instance methods

blankline()

[Source]

# File rdoc/ri/ri_formatter.rb, line 51
    def blankline
      puts
    end
bold_print(txt)

[Source]

# File rdoc/ri/ri_formatter.rb, line 66
    def bold_print(txt)
      print txt
    end
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

[Source]

# File rdoc/ri/ri_formatter.rb, line 61
    def break_to_newline
    end
conv_html(txt)

convert HTML entities back to ASCII

[Source]

# File rdoc/ri/ri_formatter.rb, line 79
    def conv_html(txt)
      txt.
          gsub(/&gt;/, '>').
          gsub(/&lt;/, '<').
          gsub(/&quot;/, '"').
          gsub(/&amp;/, '&')

    end
conv_markup(txt)

convert markup into display form

[Source]

# File 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_flow(flow)

[Source]

# File rdoc/ri/ri_formatter.rb, line 210
    def display_flow(flow)
      flow.each do |f|
        display_flow_item(f)
      end
    end
display_flow_item(item, prefix=@indent)

[Source]

# File 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_heading(text, level, indent)

[Source]

# File 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_list(list)

[Source]

# File 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_verbatim_flow_item(item, prefix=@indent)

[Source]

# File 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
draw_line(label=nil)

[Source]

# File 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
raw_print_line(txt)

[Source]

# File rdoc/ri/ri_formatter.rb, line 72
    def raw_print_line(txt)
      puts txt
    end
strip_attributes(txt)

[Source]

# File 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
wrap(txt, prefix=@indent, linelen=@width)

[Source]

# File 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


Class: RI::TopLevelEntry

Class | RI::TopLevelEntry
In: | 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()

[Source]

# File rdoc/ri/ri_cache.rb, line 135
    def full_name
      ""
    end
methods_matching(name, is_class_method)

[Source]

# File rdoc/ri/ri_cache.rb, line 131
    def methods_matching(name, is_class_method)
      res = recursively_find_methods_matching(name, is_class_method)
    end
module_named(name)

[Source]

# File rdoc/ri/ri_cache.rb, line 139
    def module_named(name)

    end


Module: RiDisplay

Module | RiDisplay
In: | 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)

[Source]

# File rdoc/ri/ri_display.rb, line 22
  def RiDisplay.append_features(display_class)
    @@display_class = display_class
  end
new(*args)

[Source]

# File rdoc/ri/ri_display.rb, line 26
  def RiDisplay.new(*args)
    @@display_class.new(*args)
  end


Class: RiDriver

Class | RiDriver
In: | 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()

[Source]

# File 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)

    paths = @options.paths || RI::Paths::PATH
    if paths.empty?
      report_missing_documentation(paths)
    end
    @ri_reader = RI::RiReader.new(RI::RiCache.new(paths))
    @display   = @options.displayer
  end

Public Instance methods

get_info_for(arg)

[Source]

# File rdoc/ri/ri_driver.rb, line 86
  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()

[Source]

# File rdoc/ri/ri_driver.rb, line 122
  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
report_class_stuff(namespaces)

[Source]

# File rdoc/ri/ri_driver.rb, line 68
  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
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

[Source]

# File rdoc/ri/ri_driver.rb, line 51
  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_missing_documentation(paths)

Couldn‘t find documentation in paths, so tell the user what to do

[Source]

# File rdoc/ri/ri_driver.rb, line 35
  def report_missing_documentation(paths)
    STDERR.puts "No ri documentation found in:"
    paths.each do |d|
      STDERR.puts "     #{d}"
    end
    STDERR.puts "\nWas rdoc run to create documentation?\n\n"
    RDoc::usage("Installing Documentation")
  end


Class: RiError

Class | RiError
In: | rdoc/ri/ri_util.rb
Parent: | Exception


Class: RubyLex

Class | RubyLex
In: | rdoc/parsers/parse_rb.rb
Parent: | Object

Lexical analyzer for Ruby source

Methods

char_no debug? get_read getc getc_of_rests gets identify_comment identify_gvar identify_here_document identify_identifier identify_number identify_quotation identify_string lex lex_init lex_int2 line_no new peek peek_equal? read_escape skip_inner_expression token ungetc

Included Modules

RubyToken

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" => "]"
PERCENT_PAREN | = | { "{" => "}", "[" => "]", "<" => ">", "(" => ")"
Ltype2Token | = | { "\'" => TkSTRING, "\"" => TkSTRING, "\`" => TkXSTRING, "\/" => TkREGEXP, "]" => TkDSTRING
DLtype2Token | = | { "\"" => TkDSTRING, "\`" => TkDXSTRING, "\/" => TkDREGEXP, }

Attributes

continue | [R]
exception_on_syntax_error | [RW]
indent | [R]
lex_state | [R]
read_auto_clean_up | [RW]
skip_space | [RW]

Public Class methods

debug?()

[Source]

# File rdoc/parsers/parse_rb.rb, line 443
  def RubyLex.debug?
    false
  end
new(content)

[Source]

# File 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

Public Instance methods

char_no()

[Source]

# File rdoc/parsers/parse_rb.rb, line 480
  def char_no
    @reader.column
  end
get_read()

[Source]

# File rdoc/parsers/parse_rb.rb, line 484
  def get_read
    @reader.get_read
  end
getc()

[Source]

# File rdoc/parsers/parse_rb.rb, line 488
  def getc
    @reader.getc
  end
getc_of_rests()

[Source]

# File rdoc/parsers/parse_rb.rb, line 492
  def getc_of_rests
    @reader.getc_already_read
  end
gets()

[Source]

# File 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
identify_comment()

[Source]

# File 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
identify_gvar()

[Source]

# File 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_here_document()

[Source]

# File 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_identifier()

[Source]

# File 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_number(start)

[Source]

# File 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_quotation(initial_char)

[Source]

# File 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_string(ltype, quoted = ltype, opener=nil, initial_char = nil)

[Source]

# File 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
lex()

[Source]

# File 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
lex_init()

[Source]

# File 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()

[Source]

# File 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
line_no()

io functions

[Source]

# File rdoc/parsers/parse_rb.rb, line 476
  def line_no
    @reader.line_num
  end
peek(i = 0)

[Source]

# File rdoc/parsers/parse_rb.rb, line 515
  def peek(i = 0)
    @reader.peek(i)
  end
peek_equal?(str)

[Source]

# File rdoc/parsers/parse_rb.rb, line 511
  def peek_equal?(str)
    @reader.peek_equal(str)
  end
read_escape()

[Source]

# File 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
skip_inner_expression()

[Source]

# File 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
token()

[Source]

# File 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
ungetc(c = nil)

[Source]

# File rdoc/parsers/parse_rb.rb, line 507
  def ungetc(c = nil)
    @reader.ungetc(c)
  end


Class: RubyLex::BufferedReader

Class | RubyLex::BufferedReader
In: | 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)

[Source]

# File rdoc/parsers/parse_rb.rb, line 349
    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

Public Instance methods

column()

[Source]

# File rdoc/parsers/parse_rb.rb, line 368
    def column
      @offset - @last_newline
    end
divert_read_from(reserve)

[Source]

# File rdoc/parsers/parse_rb.rb, line 422
    def divert_read_from(reserve)
      @content[@offset, 0] = reserve
      @size      = @content.size
    end
get_read()

[Source]

# File rdoc/parsers/parse_rb.rb, line 403
    def get_read
      res = @content[@read_back_offset...@offset]
      @read_back_offset = @offset
      res
    end
getc()

[Source]

# File rdoc/parsers/parse_rb.rb, line 372
    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()

[Source]

# File rdoc/parsers/parse_rb.rb, line 391
    def getc_already_read
      getc
    end
peek(at)

[Source]

# File rdoc/parsers/parse_rb.rb, line 409
    def peek(at)
      pos = @offset + at
      if pos >= @size
        nil
      else
        @content[pos, 1]
      end
    end
peek_equal(str)

[Source]

# File rdoc/parsers/parse_rb.rb, line 418
    def peek_equal(str)
      @content[@offset, str.length] == str
    end
ungetc(ch)

[Source]

# File rdoc/parsers/parse_rb.rb, line 395
    def ungetc(ch)
      raise "unget past beginning of file" if @offset <= 0
      @offset -= 1
      if @content[@offset] == ?\n
        @newline_pending = false
      end
    end


Module: RubyToken

Module | RubyToken
In: | rdoc/parsers/parse_rb.rb

Definitions of all tokens involved in the lexical analysis

Methods

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
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)

[Source]

# File rdoc/parsers/parse_rb.rb, line 271
  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

Public Instance methods

Token(token, value = nil)

[Source]

# File rdoc/parsers/parse_rb.rb, line 113
  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
set_token_position(line, char)

[Source]

# File rdoc/parsers/parse_rb.rb, line 108
  def set_token_position(line, char)
    @prev_line_no = line
    @prev_char_no = char
  end


Class: RubyToken::TkError

Class | RubyToken::TkError
In: | rdoc/parsers/parse_rb.rb
Parent: | Token


Class: RubyToken::TkId

Class | RubyToken::TkId
In: | rdoc/parsers/parse_rb.rb
Parent: | Token

Methods

new

Attributes

name [R]

Public Class methods

new(line_no, char_no, name)

[Source]

# File rdoc/parsers/parse_rb.rb, line 65
    def initialize(line_no, char_no, name)
      super(line_no, char_no)
      @name = name
    end


Class: RubyToken::TkKW

Class | RubyToken::TkKW
In: | rdoc/parsers/parse_rb.rb
Parent: | TkId


Class: RubyToken::TkNode

Class | RubyToken::TkNode
In: | rdoc/parsers/parse_rb.rb
Parent: | Token

Attributes

node [R]


Class: RubyToken::TkOPASGN

Class | RubyToken::TkOPASGN
In: | rdoc/parsers/parse_rb.rb
Parent: | TkOp

Methods

new

Attributes

op [R]

Public Class methods

new(line_no, char_no, op)

[Source]

# File rdoc/parsers/parse_rb.rb, line 89
    def initialize(line_no, char_no, op)
      super(line_no, char_no)
      op = TkReading2Token[op] unless op.kind_of?(Symbol)
      @op = op
    end


Class: RubyToken::TkOp

Class | RubyToken::TkOp
In: | rdoc/parsers/parse_rb.rb
Parent: | Token

Methods

name

Public Instance methods

name()

[Source]

# File rdoc/parsers/parse_rb.rb, line 83
    def name
      self.class.op_name
    end


Class: RubyToken::TkUnknownChar

Class | RubyToken::TkUnknownChar
In: | rdoc/parsers/parse_rb.rb
Parent: | Token

Methods

new

Attributes

name [R]

Public Class methods

new(line_no, char_no, id)

[Source]

# File rdoc/parsers/parse_rb.rb, line 98
    def initialize(line_no, char_no, id)
      super(line_no, char_no)
      @name = char_no.chr
    end


Class: RubyToken::TkVal

Class | RubyToken::TkVal
In: | rdoc/parsers/parse_rb.rb
Parent: | Token

Methods

new

Public Class methods

new(line_no, char_no, value = nil)

[Source]

# File rdoc/parsers/parse_rb.rb, line 76
    def initialize(line_no, char_no, value = nil)
      super(line_no, char_no)
      set_text(value)
    end


Class: RubyToken::Token

Class | RubyToken::Token
In: | rdoc/parsers/parse_rb.rb
Parent: | Object

Methods

new set_text

Constants

NO_TEXT = "??".freeze

Attributes

char_no | [R]
line_no | [R]
text | [R]
text | [R]

Public Class methods

new(line_no, char_no)

[Source]

# File rdoc/parsers/parse_rb.rb, line 44
    def initialize(line_no, char_no)
      @line_no = line_no
      @char_no = char_no
      @text    = NO_TEXT
    end

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

[Source]

# File rdoc/parsers/parse_rb.rb, line 52
    def set_text(text)
      @text = text
      self
    end


Class: SM::AttrChanger

Class | SM::AttrChanger
In: | rdoc/markup/simple_markup/inline.rb
Parent: | Object

Methods

to_s

Public Instance methods

to_s()

[Source]

# File rdoc/markup/simple_markup/inline.rb, line 46
    def to_s
      "Attr: +#{Attribute.as_string(@turn_on)}/-#{Attribute.as_string(@turn_on)}"
    end


Class: SM::AttrSpan

Class | SM::AttrSpan
In: | 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)

[Source]

# File rdoc/markup/simple_markup/inline.rb, line 53
    def initialize(length)
      @attrs = Array.new(length, 0)
    end

Public Instance methods

[](n)

[Source]

# File rdoc/markup/simple_markup/inline.rb, line 63
    def [](n)
      @attrs[n]
    end
set_attrs(start, length, bits)

[Source]

# File 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


Class: SM::Attribute

Class | SM::Attribute
In: | 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)

[Source]

# File 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
bitmap_for(name)

[Source]

# File 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
each_name_of(bitmap) {|name.to_s if (bitmap & bit) != 0| ...}

[Source]

# File 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


Class: SM::AttributeManager

Class | SM::AttributeManager
In: | 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()

[Source]

# File 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)
    end

Public Instance methods

add_html(tag, name)

[Source]

# File rdoc/markup/simple_markup/inline.rb, line 236
    def add_html(tag, name)
      HTML_TAGS[tag.downcase] = Attribute.bitmap_for(name)
    end
add_special(pattern, name)

[Source]

# File rdoc/markup/simple_markup/inline.rb, line 240
    def add_special(pattern, name)
      SPECIAL[pattern] = Attribute.bitmap_for(name)
    end
add_word_pair(start, stop, name)

[Source]

# File rdoc/markup/simple_markup/inline.rb, line 220
    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
attribute(turn_on, turn_off)

Return an attribute object with the given turn_on and turn_off bits set

[Source]

# File rdoc/markup/simple_markup/inline.rb, line 122
    def attribute(turn_on, turn_off)
      AttrChanger.new(turn_on, turn_off)
    end
change_attribute(current, new)

[Source]

# File 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(current_set, new_set)

[Source]

# File 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
convert_attrs(str, attrs)

Map attributes like textto the sequence \001\002<char>\001\003<char>, where <char> is a per-attribute specific character

[Source]

# File 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(str, attrs)

[Source]

# File 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(str, attrs)

[Source]

# File 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, $1.length, attr | Attribute::SPECIAL)
          end
        end
      end
    end
copy_string(start_pos, end_pos)

[Source]

# File 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
display_attributes()

[Source]

# File rdoc/markup/simple_markup/inline.rb, line 261
    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
flow(str)

[Source]

# File rdoc/markup/simple_markup/inline.rb, line 244
    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
mask_protected_sequences()

[Source]

# File 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
split_into_flow()

[Source]

# File rdoc/markup/simple_markup/inline.rb, line 283
    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
unmask_protected_sequences()

[Source]

# File rdoc/markup/simple_markup/inline.rb, line 204
    def unmask_protected_sequences
      @str.gsub!(/(.)#{PROTECT_ATTR}/, "\\1\000")
    end


Class: SM::BlankLine

Class | SM::BlankLine
In: | rdoc/markup/simple_markup/fragments.rb
Parent: | Paragraph


Module: SM::Flow

Module | SM::Flow
In: | 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: | rdoc/markup/simple_markup/to_flow.rb
Parent: | Object

Methods

<< new

Attributes

contents | [R]
type | [R]

Public Class methods

new(type)

[Source]

# File rdoc/markup/simple_markup/to_flow.rb, line 13
      def initialize(type)
        @type = type
        @contents = []
      end

Public Instance methods

<<(stuff)

[Source]

# File rdoc/markup/simple_markup/to_flow.rb, line 17
      def <<(stuff)
        @contents << stuff
      end


Class: SM::Fragment

Class | SM::Fragment
In: | 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)

[Source]

# File 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
new(level, param, type, txt)

[Source]

# File 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
type_name(name)

[Source]

# File rdoc/markup/simple_markup/fragments.rb, line 37
    def Fragment.type_name(name)
      TYPE_MAP[name] = self
    end

Public Instance methods

add_text(txt)

[Source]

# File 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()

[Source]

# File rdoc/markup/simple_markup/fragments.rb, line 27
    def to_s
      "L#@level: #{self.class.name.split('::')[-1]}\n#@txt"
    end


Class: SM::Heading

Class | SM::Heading
In: | rdoc/markup/simple_markup/fragments.rb
Parent: | Paragraph

Methods

head_level

Public Instance methods

head_level()

[Source]

# File rdoc/markup/simple_markup/fragments.rb, line 63
    def head_level
      @param.to_i
    end


Class: SM::Line

Class | SM::Line
In: | 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)

[Source]

# File 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

Public Instance methods

isBlank?()

Return true if this line is blank

[Source]

# File rdoc/markup/simple_markup/lines.rb, line 62
    def isBlank?
      @text.length.zero?
    end
stamp(type, level, param="", flag=nil)

stamp a line with a type, a level, a prefix, and a flag

[Source]

# File 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(size)

Strip off the leading margin

[Source]

# File 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()

[Source]

# File rdoc/markup/simple_markup/lines.rb, line 83
    def to_s
      "#@type#@level: #@text"
    end


Class: SM::LineCollection

Class | SM::LineCollection
In: | 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()

[Source]

# File rdoc/markup/simple_markup/fragments.rb, line 127
    def initialize
      @fragments = []
    end

Public Instance methods

accept(am, visitor)

[Source]

# File 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
add(fragment)

[Source]

# File rdoc/markup/simple_markup/fragments.rb, line 131
    def add(fragment)
      @fragments << fragment
    end
each(&b)

[Source]

# File rdoc/markup/simple_markup/fragments.rb, line 135
    def each(&b)
      @fragments.each(&b)
    end
fragment_for(*args)

Factory for different fragment types

[Source]

# File rdoc/markup/simple_markup/fragments.rb, line 145
    def fragment_for(*args)
      Fragment.for(*args)
    end
normalize()

tidy up at the end

[Source]

# File 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_a()

For testing

[Source]

# File rdoc/markup/simple_markup/fragments.rb, line 140
    def to_a
      @fragments.map {|fragment| fragment.to_s}
    end
to_s()

[Source]

# File rdoc/markup/simple_markup/fragments.rb, line 157
    def to_s
      @fragments.join("\n----\n")
    end


Class: SM::Lines

Class | SM::Lines
In: | 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)

[Source]

# File rdoc/markup/simple_markup/lines.rb, line 98
    def initialize(lines)
      @lines = lines
      rewind
    end

Public Instance methods

as_text()

[Source]

# File rdoc/markup/simple_markup/lines.rb, line 143
    def as_text
      @lines.map {|l| l.text}.join("\n")
    end
delete(a_line)

[Source]

# File rdoc/markup/simple_markup/lines.rb, line 133
    def delete(a_line)
      a_line.deleted = true
    end
each() {|line unless line.deleted| ...}

[Source]

# File rdoc/markup/simple_markup/lines.rb, line 107
    def each
      @lines.each do |line|
        yield line unless line.deleted
      end
    end
empty?()

[Source]

# File rdoc/markup/simple_markup/lines.rb, line 103
    def empty?
      @lines.size.zero?
    end
line_types()

[Source]

# File rdoc/markup/simple_markup/lines.rb, line 147
    def line_types
      @lines.map {|l| l.type }
    end
next()

[Source]

# File 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
normalize()

[Source]

# File 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
rewind()

def [](index)

  @lines[index]

end

[Source]

# File rdoc/markup/simple_markup/lines.rb, line 117
    def rewind
      @nextline = 0
    end
unget()

[Source]

# File rdoc/markup/simple_markup/lines.rb, line 129
    def unget
      @nextline -= 1
    end


Class: SM::ListBase

Class | SM::ListBase
In: | 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: | rdoc/markup/simple_markup/fragments.rb
Parent: | ListBase

Methods

new

Public Class methods

new(level, type)

[Source]

# File rdoc/markup/simple_markup/fragments.rb, line 98
    def initialize(level, type)
      super(level, "", type, nil)
    end


Class: SM::ListItem

Class | SM::ListItem
In: | rdoc/markup/simple_markup/fragments.rb
Parent: | ListBase


Class: SM::ListStart

Class | SM::ListStart
In: | rdoc/markup/simple_markup/fragments.rb
Parent: | ListBase

Methods

new

Public Class methods

new(level, param, type)

[Source]

# File rdoc/markup/simple_markup/fragments.rb, line 92
    def initialize(level, param, type)
      super(level, param, type, nil)
    end


Class: SM::Paragraph

Class | SM::Paragraph
In: | 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: | 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)

[Source]

# File 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

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|

[Source]

# File 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


Class: SM::Rule

Class | SM::Rule
In: | rdoc/markup/simple_markup/fragments.rb
Parent: | Fragment

A horizontal rule


Class: SM::SimpleMarkup

Class | SM::SimpleMarkup
In: | 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.

[Source]

# File rdoc/markup/simple_markup.rb, line 207
    def initialize
      @am = AttributeManager.new
      @output = nil
    end

Public Instance methods

add_html(tag, name)

Add to the sequences recognized as general markup

[Source]

# File rdoc/markup/simple_markup.rb, line 225
    def add_html(tag, name)
      @am.add_html(tag, name)
    end
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

[Source]

# File rdoc/markup/simple_markup.rb, line 239
    def add_special(pattern, name)
      @am.add_special(pattern, name)
    end
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

[Source]

# File rdoc/markup/simple_markup.rb, line 217
    def add_word_pair(start, stop, name)
      @am.add_word_pair(start, stop, name)
    end
content()

for debugging, we allow access to our line contents as text

[Source]

# File rdoc/markup/simple_markup.rb, line 464
    def content
      @lines.as_text
    end
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

[Source]

# File 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
get_line_types()

for debugging, return the list of line types

[Source]

# File rdoc/markup/simple_markup.rb, line 470
    def get_line_types
      @lines.line_types
    end


Class: SM::Special

Class | SM::Special
In: | 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)

[Source]

# File rdoc/markup/simple_markup/inline.rb, line 75
    def initialize(type, text)
      @type, @text = type, text
    end

Public Instance methods

==(o)

[Source]

# File rdoc/markup/simple_markup/inline.rb, line 79
    def ==(o)
      self.text == o.text && self.type == o.type
    end
to_s()

[Source]

# File rdoc/markup/simple_markup/inline.rb, line 83
    def to_s
      "Special: type=#{type}, text=#{text.dump}"
    end


Class: SM::ToFlow

Class | SM::ToFlow
In: | 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()

[Source]

# File rdoc/markup/simple_markup/to_flow.rb, line 37
    def initialize
      init_tags
    end

Public Instance methods

accept_blank_line(am, fragment)

[Source]

# File rdoc/markup/simple_markup/to_flow.rb, line 111
    def accept_blank_line(am, fragment)
      # @res << annotate("<p />") << "\n"
    end
accept_heading(am, fragment)

[Source]

# File 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
accept_list_end(am, fragment)

[Source]

# File rdoc/markup/simple_markup/to_flow.rb, line 103
    def accept_list_end(am, fragment)
      @res = @list_stack.pop
    end
accept_list_item(am, fragment)

[Source]

# File 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_list_start(am, fragment)

[Source]

# File 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_paragraph(am, fragment)

[Source]

# File 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_rule(am, fragment)

[Source]

# File 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_verbatim(am, fragment)

[Source]

# File 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
add_tag(name, start, stop)

Add a new set of HTML tags for an attribute. We allow separate start and end tags for flexibility

[Source]

# File 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(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

[Source]

# File rdoc/markup/simple_markup/to_flow.rb, line 66
    def annotate(tag)
      tag
    end
end_accepting()

[Source]

# File rdoc/markup/simple_markup/to_flow.rb, line 78
    def end_accepting
      @res
    end
init_tags()

Set up the standard mapping of attributes to HTML tags

[Source]

# File 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
start_accepting()

Here’s the client side of the visitor pattern

[Source]

# File rdoc/markup/simple_markup/to_flow.rb, line 73
    def start_accepting
      @res = []
      @list_stack = []
    end


Class: SM::ToHtml

Class | SM::ToHtml
In: | 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()

[Source]

# File rdoc/markup/simple_markup/to_html.rb, line 21
    def initialize
      init_tags
    end

Public Instance methods

accept_blank_line(am, fragment)

[Source]

# File rdoc/markup/simple_markup/to_html.rb, line 105
    def accept_blank_line(am, fragment)
      # @res << annotate("<p />") << "\n"
    end
accept_heading(am, fragment)

[Source]

# File 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
accept_list_end(am, fragment)

[Source]

# File 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(am, fragment)

[Source]

# File 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_list_start(am, fragment)

[Source]

# File 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_paragraph(am, fragment)

[Source]

# File 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_rule(am, fragment)

[Source]

# File 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_verbatim(am, fragment)

[Source]

# File 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
add_tag(name, start, stop)

Add a new set of HTML tags for an attribute. We allow separate start and end tags for flexibility

[Source]

# File 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(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

[Source]

# File rdoc/markup/simple_markup/to_html.rb, line 50
    def annotate(tag)
      tag
    end
end_accepting()

[Source]

# File rdoc/markup/simple_markup/to_html.rb, line 62
    def end_accepting
      @res
    end
init_tags()

Set up the standard mapping of attributes to HTML tags

[Source]

# File 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
start_accepting()

Here’s the client side of the visitor pattern

[Source]

# File rdoc/markup/simple_markup/to_html.rb, line 57
    def start_accepting
      @res = ""
      @in_list_entry = []
    end
wrap(txt, line_len = 76)

This is a higher speed (if messier) version of wrap

[Source]

# File 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


Class: SM::ToLaTeX

Class | SM::ToLaTeX
In: | rdoc/markup/simple_markup/to_latex.rb
Parent: | Object

Convert SimpleMarkup to basic LaTeX report format

Methods

escape init_tags l l new

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)

[Source]

# File rdoc/markup/simple_markup/to_latex.rb, line 24
    def self.l(str)
      str.tr('\\', BS).tr('{', OB).tr('}', CB).tr('$', DL)
    end
new()

[Source]

# File rdoc/markup/simple_markup/to_latex.rb, line 45
    def initialize
      init_tags
      @list_depth = 0
      @prev_list_types = []
    end

Public Instance methods

escape(str)

Escape a LaTeX string

[Source]

# File 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 a new set of LaTeX tags for an attribute. We allow
    # separate start and end tags for flexibility
    #
    def add_tag(name, start, stop)
      @attr_tags << InlineTag.new(SM::Attribute.bitmap_for(name), start, stop)
    end

    ##
    # Here's the client side of the visitor pattern

    def start_accepting
      @res = ""
      @in_list_entry = []
    end

    def end_accepting
      @res.tr(BS, '\\').tr(OB, '{').tr(CB, '}').tr(DL, '$')
    end

    def accept_paragraph(am, fragment)
      @res << wrap(convert_flow(am.flow(fragment.txt)))
      @res << "\n"
    end

    def accept_verbatim(am, fragment)
      @res << "\n\\begin{code}\n"
      @res << fragment.txt.sub(/[\n\s]+\Z/, '')
      @res << "\n\\end{code}\n\n"
    end

    def accept_rule(am, fragment)
      size = fragment.param
      size = 10 if size > 10
      @res << "\n\n\\rule{\\linewidth}{#{size}pt}\n\n"
    end

    def accept_list_start(am, fragment)
      @res << list_name(fragment.type, true) <<"\n"
      @in_list_entry.push false
    end

    def accept_list_end(am, fragment)
      if tag = @in_list_entry.pop
        @res << tag << "\n"
      end
      @res << list_name(fragment.type, false) <<"\n"
    end

    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

    def accept_blank_line(am, fragment)
      # @res << "\n"
    end

    def accept_heading(am, fragment)
      @res << convert_heading(fragment.head_level, am.flow(fragment.txt))
    end

    # This is a higher speed (if messier) version of wrap

    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

    #######################################################################

    private

    #######################################################################

    def on_tags(res, item)
      attr_mask = item.turn_on
      return if attr_mask.zero?

      @attr_tags.each do |tag|
        if attr_mask & tag.bit != 0
          res << tag.on
        end
      end
    end

    def off_tags(res, item)
      attr_mask = item.turn_off
      return if attr_mask.zero?

      @attr_tags.reverse_each do |tag|
        if attr_mask & tag.bit != 0
          res << tag.off
        end
      end
    end

    def convert_flow(flow)
      res = ""
      flow.each do |item|
        case item
        when String
#          $stderr.puts "Converting '#{item}'"
          res << convert_string(item)
        when AttrChanger
          off_tags(res, item)
          on_tags(res,  item)
        when Special
          res << convert_special(item)
        else
          raise "Unknown flow element: #{item.inspect}"
        end
      end
      res
    end

    # some of these patterns are taken from SmartyPants...

    def convert_string(item)

      escape(item).

      # convert ... to elipsis (and make sure .... becomes .<elipsis>)
        gsub(/\.\.\.\./, '.\ldots{}').gsub(/\.\.\./, '\ldots{}').

      # convert single closing quote
        gsub(%r{([^ \t\r\n\[\{\(])\'}) { "#$1'" }.
        gsub(%r{\'(?=\W|s\b)}) { "'" }.

      # convert single opening quote
        gsub(/'/, '`').

      # convert double closing quote
        gsub(%r{([^ \t\r\n\[\{\(])\"(?=\W)}) { "#$1''" }.

      # convert double opening quote
        gsub(/"/, "``").

      # convert copyright
        gsub(/\(c\)/, '\copyright{}')

    end

    def convert_special(special)
      handled = false
      Attribute.each_name_of(special.type) do |name|
        method_name = "handle_special_#{name}"
        if self.respond_to? method_name
          special.text = send(method_name, special)
          handled = true
        end
      end
      raise "Unhandled special: #{special}" unless handled
      special.text
    end

    def convert_heading(level, flow)
      res =
        case level
        when 1 then "\\chapter{"
        when 2 then "\\section{"
        when 3 then "\\subsection{"
        when 4 then "\\subsubsection{"
        else  "\\paragraph{"
        end +
        convert_flow(flow) +
        "}\n"
    end

    def list_name(list_type, is_open_tag)
      tags = LIST_TYPE_TO_LATEX[list_type] || raise("Invalid list type: #{list_type.inspect}")
      if tags[2] # enumerate
        if is_open_tag
          @list_depth += 1
          if @prev_list_types[@list_depth] != tags[2]
            case @list_depth
            when 1
              roman = "i"
            when 2
              roman = "ii"
            when 3
              roman = "iii"
            when 4
              roman = "iv"
            else
              raise("Too deep list: level #{@list_depth}")
            end
            @prev_list_types[@list_depth] = tags[2]
            return l("\\renewcommand{\\labelenum#{roman}}{#{tags[2]}{enum#{roman}}}") + "\n" + tags[0]
          end
        else
          @list_depth -= 1
        end
      end
      tags[ is_open_tag ? 0 : 1]
    end

    def list_item_start(am, fragment)
      case fragment.type
      when ListBase::BULLET, ListBase::NUMBER, ListBase::UPPERALPHA, ListBase::LOWERALPHA
        "\\item "

      when ListBase::LABELED
        "\\item[" + convert_flow(am.flow(fragment.param)) + "] "

      when ListBase::NOTE
          convert_flow(am.flow(fragment.param)) + " & "
      else
        raise "Invalid list type"
      end
    end

    def list_end_for(fragment_type)
      case fragment_type
      when ListBase::BULLET, ListBase::NUMBER, ListBase::UPPERALPHA, ListBase::LOWERALPHA, ListBase::LABELED
        ""
      when ListBase::NOTE
        "\\\\\n"
      else
        raise "Invalid list type"
      end
    end

  end

end
init_tags()

Set up the standard mapping of attributes to LaTeX

[Source]

# File 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
l(arg)

[Source]

# File rdoc/markup/simple_markup/to_latex.rb, line 28
    def l(arg)
      SM::ToLaTeX.l(arg)
    end


Class: SM::Verbatim

Class | SM::Verbatim
In: | 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)

[Source]

# File rdoc/markup/simple_markup/fragments.rb, line 109
    def add_text(txt)
      @txt << txt.chomp << "\n"
    end


Class: TemplatePage

Class | TemplatePage
In: | 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

[Source]

# File 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

Public Instance methods

expand_line(line)

Given an individual line, we look for %xxx% constructs and HREF:ref:name: constructs, substituting for each.

[Source]

# File 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
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

[Source]

# File 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
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)

[Source]

# File rdoc/template.rb, line 144
  def write_html_on(op, value_hash)
    @context = Context.new
    op << substitute_into(@lines, value_hash).tr("\000", '\\')
  end


Class: TemplatePage::Context

Class | TemplatePage::Context
In: | 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()

[Source]

# File rdoc/template.rb, line 47
    def initialize
      @stack = []
    end

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

[Source]

# File 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(key)

Lookup any key in the stack of hashes

[Source]

# File rdoc/template.rb, line 73
    def lookup(key)
      @stack.reverse_each do |level|
        val = level[key]
        return val if val
      end
      nil
    end
pop()

[Source]

# File rdoc/template.rb, line 55
    def pop
      @stack.pop
    end
push(hash)

[Source]

# File rdoc/template.rb, line 51
    def push(hash)
      @stack.push(hash)
    end


Class: TemplatePage::LineReader

Class | TemplatePage::LineReader
In: | 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

[Source]

# File rdoc/template.rb, line 87
    def initialize(lines)
      @lines = lines
    end

Public Instance methods

dup()

Return a copy of ourselves that can be modified without affecting us

[Source]

# File rdoc/template.rb, line 112
    def dup
      LineReader.new(@lines.dup)
    end
read()

read the next line

[Source]

# File rdoc/template.rb, line 92
    def read
      @lines.shift
    end
read_up_to(pattern)

Return a list of lines up to the line that matches a pattern. That last line is discarded.

[Source]

# File 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


Module: TokenStream

Module | TokenStream
In: | 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)

[Source]

# File rdoc/tokenstream.rb, line 16
  def add_token(tk)
    @token_stream << tk
  end
add_tokens(tks)

[Source]

# File rdoc/tokenstream.rb, line 19
  def add_tokens(tks)
    tks.each  {|tk| add_token(tk)}
  end
pop_token()

[Source]

# File rdoc/tokenstream.rb, line 22
  def pop_token
    @token_stream.pop
  end
start_collecting_tokens()

[Source]

# File rdoc/tokenstream.rb, line 13
  def start_collecting_tokens
    @token_stream = []
  end
token_stream()

[Source]

# File rdoc/tokenstream.rb, line 9
  def token_stream
    @token_stream
  end


File: code_objects.rb

code_objects.rb

Path: | rdoc/code_objects.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

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: | rdoc/diagram.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

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: dot.rb

dot.rb

Path: | rdoc/dot/dot.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005


File: chm_generator.rb

chm_generator.rb

Path: | rdoc/generators/chm_generator.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

rdoc/generators/html_generator


File: html_generator.rb

html_generator.rb

Path: | rdoc/generators/html_generator.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

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: | rdoc/generators/ri_generator.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

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: chm.rb

chm.rb

Path: | rdoc/generators/template/chm/chm.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

rdoc/generators/template/html/html


File: hefss.rb

hefss.rb

Path: | rdoc/generators/template/html/hefss.rb
Last Update: | Mon Dec 01 17:12:48 AUS Eastern Daylight Time 2003


File: html.rb

html.rb

Path: | rdoc/generators/template/html/html.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

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 © 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: | rdoc/generators/template/html/kilmer.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005


File: old_html.rb

old_html.rb

Path: | rdoc/generators/template/html/old_html.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

rdoc/generators/template/html/one_page_html


File: one_page_html.rb

one_page_html.rb

Path: | rdoc/generators/template/html/one_page_html.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005


File: rdf.rb

rdf.rb

Path: | rdoc/generators/template/xml/rdf.rb
Last Update: | Mon Dec 01 17:12:48 AUS Eastern Daylight Time 2003


File: xml.rb

xml.rb

Path: | rdoc/generators/template/xml/xml.rb
Last Update: | Mon Dec 01 17:12:48 AUS Eastern Daylight Time 2003


File: xml_generator.rb

xml_generator.rb

Path: | rdoc/generators/xml_generator.rb
Last Update: | Mon Dec 01 17:12:48 AUS Eastern Daylight Time 2003

Required files

ftools rdoc/options rdoc/markup/simple_markup rdoc/markup/simple_markup/to_html rdoc/generators/html_generator


File: simple_markup.rb

simple_markup.rb

Path: | rdoc/markup/simple_markup.rb
Last Update: | Tue Oct 25 16:35:29 AUS Eastern Standard Time 2005

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: | rdoc/markup/simple_markup/fragments.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

rdoc/markup/simple_markup/lines.rb


File: inline.rb

inline.rb

Path: | rdoc/markup/simple_markup/inline.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005


File: lines.rb

lines.rb

Path: | rdoc/markup/simple_markup/lines.rb
Last Update: | Mon Dec 01 17:12:48 AUS Eastern Daylight Time 2003

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: | rdoc/markup/simple_markup/preprocess.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005


File: to_flow.rb

to_flow.rb

Path: | rdoc/markup/simple_markup/to_flow.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

rdoc/markup/simple_markup/fragments rdoc/markup/simple_markup/inline cgi


File: to_html.rb

to_html.rb

Path: | rdoc/markup/simple_markup/to_html.rb
Last Update: | Mon Dec 01 17:12:48 AUS Eastern Daylight Time 2003

Required files

rdoc/markup/simple_markup/fragments rdoc/markup/simple_markup/inline cgi


File: to_latex.rb

to_latex.rb

Path: | rdoc/markup/simple_markup/to_latex.rb
Last Update: | Mon Dec 01 17:12:48 AUS Eastern Daylight Time 2003

Required files

rdoc/markup/simple_markup/fragments rdoc/markup/simple_markup/inline cgi


File: options.rb

options.rb

Path: | rdoc/options.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

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: parse_c.rb

parse_c.rb

Path: | rdoc/parsers/parse_c.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

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 outomatically 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.
  */

Required files

rdoc/code_objects rdoc/parsers/parserfactory


File: parse_f95.rb

parse_f95.rb

Path: | rdoc/parsers/parse_f95.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Parse a Fortran 95 file.

Required files

rdoc/code_objects


File: parse_rb.rb

parse_rb.rb

Path: | rdoc/parsers/parse_rb.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

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

tracer e2mmap irb/slex rdoc/code_objects rdoc/tokenstream rdoc/markup/simple_markup/preprocess rdoc/parsers/parserfactory


File: parse_simple.rb

parse_simple.rb

Path: | rdoc/parsers/parse_simple.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

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: | rdoc/parsers/parserfactory.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

rdoc/parsers/parse_simple


File: rdoc.rb

rdoc.rb

Path: | rdoc/rdoc.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

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

Constants

VERSION_STRING = %{RDoc V1.0.1 - 20041108} See README.


File: ri_cache.rb

ri_cache.rb

Path: | rdoc/ri/ri_cache.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005


File: ri_descriptions.rb

ri_descriptions.rb

Path: | rdoc/ri/ri_descriptions.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

yaml rdoc/markup/simple_markup/fragments


File: ri_display.rb

ri_display.rb

Path: | rdoc/ri/ri_display.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

rdoc/ri/ri_util rdoc/ri/ri_formatter rdoc/ri/ri_options tempfile


File: ri_driver.rb

ri_driver.rb

Path: | rdoc/ri/ri_driver.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

rdoc/usage rdoc/ri/ri_paths 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: | rdoc/ri/ri_formatter.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005


File: ri_options.rb

ri_options.rb

Path: | rdoc/ri/ri_options.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

We handle the parsing of options, and subsequently as a singleton object to be queried for option values

Required files

rdoc/ri/ri_display singleton getoptlong


File: ri_paths.rb

ri_paths.rb

Path: | rdoc/ri/ri_paths.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

rbconfig


File: ri_reader.rb

ri_reader.rb

Path: | rdoc/ri/ri_reader.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

rdoc/ri/ri_descriptions rdoc/ri/ri_writer rdoc/markup/simple_markup/to_flow


File: ri_util.rb

ri_util.rb

Path: | rdoc/ri/ri_util.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005


File: ri_writer.rb

ri_writer.rb

Path: | rdoc/ri/ri_writer.rb
Last Update: | Fri Dec 19 07:08:25 AUS Eastern Daylight Time 2003

Required files

fileutils


File: template.rb

template.rb

Path: | rdoc/template.rb
Last Update: | Mon Dec 01 17:12:48 AUS Eastern Daylight Time 2003

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: | rdoc/tokenstream.rb
Last Update: | Mon Dec 01 17:12:48 AUS Eastern Daylight Time 2003

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: | rdoc/usage.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

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 © 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: readbytes.rb

readbytes.rb

Path: | readbytes.rb
Last Update: | Fri Aug 13 15:45:16 AUS Eastern Standard Time 1999

readbytes.rb

add IO#readbytes, which reads fixed sized data. it guarantees read data size.


Class: IO

Class | IO
In: | readbytes.rb
Parent: | Object

Methods

readbytes

Public Instance methods

readbytes(n)

[Source]

# File readbytes.rb, line 15
  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


Class: TruncatedDataError

Class | TruncatedDataError
In: | readbytes.rb
Parent: | IOError

readbytes.rb

add IO#readbytes, which reads fixed sized data. it guarantees read data size.

Methods

new

Attributes

data [R]

Public Class methods

new(mesg, data)

[Source]

# File readbytes.rb, line 7
  def initialize(mesg, data)
    @data = data
    super(mesg)
  end


Module: Readline

Module | Readline
In: | readline/readline.c

Methods

basic_quote_characters basic_quote_characters= basic_word_break_characters basic_word_break_characters= completer_quote_characters completer_quote_characters= completer_word_break_characters completer_word_break_characters= completion_append_character completion_append_character= completion_case_fold completion_case_fold= completion_proc completion_proc= emacs_editing_mode filename_quote_characters filename_quote_characters= readline vi_editing_mode

Public Class methods

basic_quote_characters()
basic_quote_characters=(p1)
basic_word_break_characters()
basic_word_break_characters=(p1)
completer_quote_characters()
completer_quote_characters=(p1)
completer_word_break_characters()
completer_word_break_characters=(p1)
completion_append_character()
completion_append_character=(p1)
completion_case_fold()
completion_case_fold=(p1)
completion_proc()
completion_proc=(p1)
emacs_editing_mode()
filename_quote_characters()
filename_quote_characters=(p1)
vi_editing_mode()

Public Instance methods

readline(...)


File: readline.c

readline.c

Path: | readline/readline.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


Class: Resolv

Class | Resolv
In: | 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)

[Source]

# File resolv.rb, line 206
  def self.each_address(name, &block)
    DefaultResolver.each_address(name, &block)
  end
each_name(address, &proc)

[Source]

# File resolv.rb, line 218
  def self.each_name(address, &proc)
    DefaultResolver.each_name(address, &proc)
  end
getaddress(name)

[Source]

# File resolv.rb, line 198
  def self.getaddress(name)
    DefaultResolver.getaddress(name)
  end
getaddresses(name)

[Source]

# File resolv.rb, line 202
  def self.getaddresses(name)
    DefaultResolver.getaddresses(name)
  end
getname(address)

[Source]

# File resolv.rb, line 210
  def self.getname(address)
    DefaultResolver.getname(address)
  end
getnames(address)

[Source]

# File resolv.rb, line 214
  def self.getnames(address)
    DefaultResolver.getnames(address)
  end
new(resolvers=[Hosts.new, DNS.new])

[Source]

# File resolv.rb, line 222
  def initialize(resolvers=[Hosts.new, DNS.new])
    @resolvers = resolvers
  end

Public Instance methods

each_address(name) {|name| ...}

[Source]

# File 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
each_name(address) {|name.to_s| ...}

[Source]

# File 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
getaddress(name)

[Source]

# File resolv.rb, line 226
  def getaddress(name)
    each_address(name) {|address| return address}
    raise ResolvError.new("no address for #{name}")
  end
getaddresses(name)

[Source]

# File resolv.rb, line 231
  def getaddresses(name)
    ret = []
    each_address(name) {|address| ret << address}
    return ret
  end
getname(address)

[Source]

# File resolv.rb, line 252
  def getname(address)
    each_name(address) {|name| return name}
    raise ResolvError.new("no name for #{address}")
  end
getnames(address)

[Source]

# File resolv.rb, line 257
  def getnames(address)
    ret = []
    each_name(address) {|name| ret << name}
    return ret
  end


Class: Resolv::DNS

Class | Resolv::DNS
In: | 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)

[Source]

# File resolv.rb, line 381
    def initialize(config_info=nil)
      @mutex = Mutex.new
      @config = Config.new(config_info)
      @initialized = nil
    end
open(*args) {|dns| ...}

[Source]

# File resolv.rb, line 371
    def self.open(*args)
      dns = new(*args)
      return dns unless block_given?
      begin
        yield dns
      ensure
        dns.close
      end
    end

Public Instance methods

close()

[Source]

# File resolv.rb, line 404
    def close
      @mutex.synchronize {
        if @initialized
          @requester.close if @requester
          @requester = nil
          @initialized = false
        end
      }
    end
each_address(name) {|resource.address| ...}

[Source]

# File resolv.rb, line 425
    def each_address(name)
      each_resource(name, Resource::IN::A) {|resource| yield resource.address}
    end
each_name(address) {|resource.name| ...}

[Source]

# File 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
each_resource(name, typeclass, &proc)

[Source]

# File 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(msg, name, typeclass) {|data if n0 == n| ...}

[Source]

# File 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
getaddress(name)

[Source]

# File 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(name)

[Source]

# File resolv.rb, line 419
    def getaddresses(name)
      ret = []
      each_address(name) {|address| ret << address}
      return ret
    end
getname(address)

[Source]

# File 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(address)

[Source]

# File resolv.rb, line 434
    def getnames(address)
      ret = []
      each_name(address) {|name| ret << name}
      return ret
    end
getresource(name, typeclass)

[Source]

# File 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(name, typeclass)

[Source]

# File resolv.rb, line 459
    def getresources(name, typeclass)
      ret = []
      each_resource(name, typeclass) {|resource| ret << resource}
      return ret
    end
lazy_initialize()

[Source]

# File 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


Class: Resolv::DNS::Config

Class | Resolv::DNS::Config
In: | 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")

[Source]

# File 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
new(config_info=nil)

[Source]

# File resolv.rb, line 717
      def initialize(config_info=nil)
        @mutex = Mutex.new
        @config_info = config_info
        @initialized = nil
      end
parse_resolv_conf(filename)

[Source]

# File 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

Public Instance methods

generate_candidates(name)

[Source]

# File 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()

[Source]

# File 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
lazy_initialize()

[Source]

# File 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
resolv(name) {|candidate, tout, nameserver| ...}

[Source]

# File 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
single?()

[Source]

# File resolv.rb, line 829
      def single?
        lazy_initialize
        if @nameserver.length == 1
          return @nameserver[0]
        else
          return nil
        end
      end


Class: Resolv::DNS::Config::NXDomain

Class | Resolv::DNS::Config::NXDomain
In: | resolv.rb
Parent: | ResolvError


Class: Resolv::DNS::Config::OtherResolvError

Class | Resolv::DNS::Config::OtherResolvError
In: | resolv.rb
Parent: | ResolvError


Class: Resolv::DNS::DecodeError

Class | Resolv::DNS::DecodeError
In: | resolv.rb
Parent: | StandardError


Class: Resolv::DNS::EncodeError

Class | Resolv::DNS::EncodeError
In: | resolv.rb
Parent: | StandardError


Module: Resolv::DNS::Label

Module | Resolv::DNS::Label
In: | resolv.rb

Methods

split

Classes and Modules

Class Resolv::DNS::Label::Str

Public Class methods

split(arg)

[Source]

# File resolv.rb, line 929
      def self.split(arg)
        labels = []
        arg.scan(/[^\.]+/) {labels << Str.new($&)}
        return labels
      end


Class: Resolv::DNS::Label::Str

Class | Resolv::DNS::Label::Str
In: | resolv.rb
Parent: | Object

Methods

== eql? hash inspect new to_s

Attributes

downcase | [R]
string | [R]

Public Class methods

new(string)

[Source]

# File resolv.rb, line 936
        def initialize(string)
          @string = string
          @downcase = string.downcase
        end

Public Instance methods

==(other)

[Source]

# File resolv.rb, line 950
        def ==(other)
          return @downcase == other.downcase
        end
eql?(other)

[Source]

# File resolv.rb, line 954
        def eql?(other)
          return self == other
        end
hash()

[Source]

# File resolv.rb, line 958
        def hash
          return @downcase.hash
        end
inspect()

[Source]

# File resolv.rb, line 946
        def inspect
          return "#<#{self.class} #{self.to_s}>"
        end
to_s()

[Source]

# File resolv.rb, line 942
        def to_s
          return @string
        end


Class: Resolv::DNS::Message

Class | Resolv::DNS::Message
In: | 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)

[Source]

# File 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
new(id = (@@identifier += 1) & 0xffff)

[Source]

# File 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

Public Instance methods

==(other)

[Source]

# File 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_additional(name, ttl, data)

[Source]

# File resolv.rb, line 1108
      def add_additional(name, ttl, data)
        @additional << [Name.create(name), ttl, data]
      end
add_answer(name, ttl, data)

[Source]

# File resolv.rb, line 1088
      def add_answer(name, ttl, data)
        @answer << [Name.create(name), ttl, data]
      end
add_authority(name, ttl, data)

[Source]

# File resolv.rb, line 1098
      def add_authority(name, ttl, data)
        @authority << [Name.create(name), ttl, data]
      end
add_question(name, typeclass)

[Source]

# File resolv.rb, line 1078
      def add_question(name, typeclass)
        @question << [Name.create(name), typeclass]
      end
each_additional() {|name, ttl, data| ...}

[Source]

# File resolv.rb, line 1112
      def each_additional
        @additional.each {|name, ttl, data|
          yield name, ttl, data
        }
      end
each_answer() {|name, ttl, data| ...}

[Source]

# File resolv.rb, line 1092
      def each_answer
        @answer.each {|name, ttl, data|
          yield name, ttl, data
        }
      end
each_authority() {|name, ttl, data| ...}

[Source]

# File resolv.rb, line 1102
      def each_authority
        @authority.each {|name, ttl, data|
          yield name, ttl, data
        }
      end
each_question() {|name, typeclass| ...}

[Source]

# File resolv.rb, line 1082
      def each_question
        @question.each {|name, typeclass|
          yield name, typeclass
        }
      end
each_resource() {|name, ttl, data| ...}

[Source]

# File 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()

[Source]

# File 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


Class: Resolv::DNS::Message::MessageDecoder

Class | Resolv::DNS::Message::MessageDecoder
In: | 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| ...}

[Source]

# File resolv.rb, line 1251
        def initialize(data)
          @data = data
          @index = 0
          @limit = data.length
          yield self
        end

Public Instance methods

get_bytes(len = @limit - @index)

[Source]

# File resolv.rb, line 1272
        def get_bytes(len = @limit - @index)
          d = @data[@index, len]
          @index += len
          return d
        end
get_label()

[Source]

# File resolv.rb, line 1343
        def get_label
          return Label::Str.new(self.get_string)
        end
get_labels(limit=nil)

[Source]

# File 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_length16() {|len| ...}

[Source]

# File 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_name()

[Source]

# File resolv.rb, line 1314
        def get_name
          return Name.new(self.get_labels)
        end
get_question()

[Source]

# File 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()

[Source]

# File 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
get_string()

[Source]

# File 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()

[Source]

# File resolv.rb, line 1306
        def get_string_list
          strings = []
          while @index < @limit
            strings << self.get_string
          end
          strings
        end
get_unpack(template)

[Source]

# File 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


Class: Resolv::DNS::Message::MessageEncoder

Class | Resolv::DNS::Message::MessageEncoder
In: | 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| ...}

[Source]

# File resolv.rb, line 1156
        def initialize
          @data = ''
          @names = {}
          yield self
        end

Public Instance methods

put_bytes(d)

[Source]

# File resolv.rb, line 1166
        def put_bytes(d)
          @data << d
        end
put_label(d)

[Source]

# File resolv.rb, line 1212
        def put_label(d)
          self.put_string(d.string)
        end
put_labels(d)

[Source]

# File 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_length16() {|| ...}

[Source]

# File 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_name(d)

[Source]

# File resolv.rb, line 1194
        def put_name(d)
          put_labels(d.to_a)
        end
put_pack(template, *d)

[Source]

# File resolv.rb, line 1170
        def put_pack(template, *d)
          @data << d.pack(template)
        end
put_string(d)

[Source]

# File resolv.rb, line 1183
        def put_string(d)
          self.put_pack("C", d.length)
          @data << d
        end
put_string_list(ds)

[Source]

# File resolv.rb, line 1188
        def put_string_list(ds)
          ds.each {|d|
            self.put_string(d)
          }
        end
to_s()

[Source]

# File resolv.rb, line 1162
        def to_s
          return @data
        end


Class: Resolv::DNS::Name

Class | Resolv::DNS::Name
In: | resolv.rb
Parent: | Object

Methods

== [] absolute? create eql? hash inspect length new subdomain_of? to_a to_s

Public Class methods

create(arg)

[Source]

# File 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(labels, absolute=true)

[Source]

# File resolv.rb, line 976
      def initialize(labels, absolute=true)
        @labels = labels
        @absolute = absolute
      end

Public Instance methods

==(other)

[Source]

# File resolv.rb, line 989
      def ==(other)
        return false unless Name === other
        return @labels == other.to_a && @absolute == other.absolute?
      end
[](i)

[Source]

# File resolv.rb, line 1025
      def [](i)
        return @labels[i]
      end
absolute?()

[Source]

# File resolv.rb, line 985
      def absolute?
        return @absolute
      end
eql?(other)

Alias for #==

hash()

[Source]

# File resolv.rb, line 1013
      def hash
        return @labels.hash ^ @absolute.hash
      end
inspect()

[Source]

# File resolv.rb, line 981
      def inspect
        "#<#{self.class}: #{self.to_s}#{@absolute ? '.' : ''}>"
      end
length()

[Source]

# File resolv.rb, line 1021
      def length
        return @labels.length
      end
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

[Source]

# File 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
to_a()

[Source]

# File resolv.rb, line 1017
      def to_a
        return @labels
      end
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"

[Source]

# File resolv.rb, line 1037
      def to_s
        return @labels.join('.')
      end


Module: Resolv::DNS::OpCode

Module | Resolv::DNS::OpCode
In: | resolv.rb

Constants

Query | = | 0
IQuery | = | 1
Status | = | 2
Notify | = | 4
Update | = | 5


Class: Resolv::DNS::Query

Class | Resolv::DNS::Query
In: | resolv.rb
Parent: | Object

Methods

decode_rdata encode_rdata

Public Class methods

decode_rdata(msg)

[Source]

# File resolv.rb, line 1367
      def self.decode_rdata(msg)
        raise DecodeError.new("#{self.class} is query.")
      end

Public Instance methods

encode_rdata(msg)

[Source]

# File resolv.rb, line 1363
      def encode_rdata(msg)
        raise EncodeError.new("#{self.class} is query.")
      end


Module: Resolv::DNS::RCode

Module | Resolv::DNS::RCode
In: | 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: | 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()

[Source]

# File resolv.rb, line 528
      def initialize
        @senders = {}
      end

Public Instance methods

close()

[Source]

# File 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(arg)

[Source]

# File 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


Class: Resolv::DNS::Requester::ConnectedUDP

Class | Resolv::DNS::Requester::ConnectedUDP
In: | resolv.rb
Parent: | Requester

Methods

new sender

Classes and Modules

Class Resolv::DNS::Requester::ConnectedUDP::Sender

Public Class methods

new(host, port=Port)

[Source]

# File resolv.rb, line 620
        def initialize(host, port=Port)
          super()
          @host = host
          @port = port
          @sock = UDPSocket.new
          @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

Public Instance methods

sender(msg, data, queue, host=@host, port=@port)

[Source]

# File 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


Class: Resolv::DNS::Requester::ConnectedUDP::Sender

Class | Resolv::DNS::Requester::ConnectedUDP::Sender
In: | resolv.rb
Parent: | Requester::Sender

Methods

send

Public Instance methods

send()

[Source]

# File resolv.rb, line 658
          def send
            @sock.send(@msg, 0)
          end


Class: Resolv::DNS::Requester::RequestError

Class | Resolv::DNS::Requester::RequestError
In: | resolv.rb
Parent: | StandardError


Class: Resolv::DNS::Requester::Sender

Class | Resolv::DNS::Requester::Sender
In: | resolv.rb
Parent: | Object

Methods

new recv

Attributes

queue [R]

Public Class methods

new(msg, data, sock, queue)

[Source]

# File resolv.rb, line 556
        def initialize(msg, data, sock, queue)
          @msg = msg
          @data = data
          @sock = sock
          @queue = queue
        end

Public Instance methods

recv(msg)

[Source]

# File resolv.rb, line 564
        def recv(msg)
          @queue.push([msg, @data])
        end


Class: Resolv::DNS::Requester::TCP

Class | Resolv::DNS::Requester::TCP
In: | resolv.rb
Parent: | Requester

Methods

new sender

Classes and Modules

Class Resolv::DNS::Requester::TCP::Sender

Public Class methods

new(host, port=Port)

[Source]

# File 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

Public Instance methods

sender(msg, data, queue, host=@host, port=@port)

[Source]

# File 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


Class: Resolv::DNS::Requester::TCP::Sender

Class | Resolv::DNS::Requester::TCP::Sender
In: | resolv.rb
Parent: | Requester::Sender

Methods

send

Public Instance methods

send()

[Source]

# File resolv.rb, line 705
          def send
            @sock.print(@msg)
            @sock.flush
          end


Class: Resolv::DNS::Requester::UnconnectedUDP

Class | Resolv::DNS::Requester::UnconnectedUDP
In: | resolv.rb
Parent: | Requester

Methods

new sender

Classes and Modules

Class Resolv::DNS::Requester::UnconnectedUDP::Sender

Public Class methods

new()

[Source]

# File 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

Public Instance methods

sender(msg, data, queue, host, port=Port)

[Source]

# File 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


Class: Resolv::DNS::Requester::UnconnectedUDP::Sender

Class | Resolv::DNS::Requester::UnconnectedUDP::Sender
In: | resolv.rb
Parent: | Requester::Sender

Methods

new send

Public Class methods

new(msg, data, sock, host, port, queue)

[Source]

# File resolv.rb, line 607
          def initialize(msg, data, sock, host, port, queue)
            super(msg, data, sock, queue)
            @host = host
            @port = port
          end

Public Instance methods

send()

[Source]

# File resolv.rb, line 613
          def send
            @sock.send(@msg, 0, @host, @port)
          end


Class: Resolv::DNS::Resource

Class | Resolv::DNS::Resource
In: | 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)

[Source]

# File resolv.rb, line 1379
      def self.decode_rdata(msg)
        raise NotImplementedError.new
      end
get_class(type_value, class_value)

[Source]

# File 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

Public Instance methods

==(other)

[Source]

# File 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
encode_rdata(msg)

[Source]

# File resolv.rb, line 1375
      def encode_rdata(msg)
        raise NotImplementedError.new
      end
eql?(other)

[Source]

# File resolv.rb, line 1390
      def eql?(other)
        return self == other
      end
hash()

[Source]

# File resolv.rb, line 1394
      def hash
        h = 0
        self.instance_variables.each {|name|
          h ^= self.instance_eval("#{name}.hash")
        }
        return h
      end


Class: Resolv::DNS::Resource::ANY

Class | Resolv::DNS::Resource::ANY
In: | resolv.rb
Parent: | Query

Constants

TypeValue = 255


Class: Resolv::DNS::Resource::CNAME

Class | Resolv::DNS::Resource::CNAME
In: | resolv.rb
Parent: | DomainName

Constants

TypeValue = 5


Class: Resolv::DNS::Resource::DomainName

Class | Resolv::DNS::Resource::DomainName
In: | resolv.rb
Parent: | Resource

Methods

decode_rdata encode_rdata new

Attributes

name [R]

Public Class methods

decode_rdata(msg)

[Source]

# File resolv.rb, line 1441
        def self.decode_rdata(msg)
          return self.new(msg.get_name)
        end
new(name)

[Source]

# File resolv.rb, line 1432
        def initialize(name)
          @name = name
        end

Public Instance methods

encode_rdata(msg)

[Source]

# File resolv.rb, line 1437
        def encode_rdata(msg)
          msg.put_name(@name)
        end


Class: Resolv::DNS::Resource::Generic

Class | Resolv::DNS::Resource::Generic
In: | resolv.rb
Parent: | Resource

Methods

create decode_rdata encode_rdata new

Attributes

data [R]

Public Class methods

create(type_value, class_value)

[Source]

# File 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
decode_rdata(msg)

[Source]

# File resolv.rb, line 1417
        def self.decode_rdata(msg)
          return self.new(msg.get_bytes)
        end
new(data)

[Source]

# File resolv.rb, line 1408
        def initialize(data)
          @data = data
        end

Public Instance methods

encode_rdata(msg)

[Source]

# File resolv.rb, line 1413
        def encode_rdata(msg)
          msg.put_bytes(data)
        end


Class: Resolv::DNS::Resource::HINFO

Class | Resolv::DNS::Resource::HINFO
In: | resolv.rb
Parent: | Resource

Methods

decode_rdata encode_rdata new

Constants

TypeValue = 13

Attributes

cpu | [R]
os | [R]

Public Class methods

decode_rdata(msg)

[Source]

# File resolv.rb, line 1504
        def self.decode_rdata(msg)
          cpu = msg.get_string
          os = msg.get_string
          return self.new(cpu, os)
        end
new(cpu, os)

[Source]

# File resolv.rb, line 1493
        def initialize(cpu, os)
          @cpu = cpu
          @os = os
        end

Public Instance methods

encode_rdata(msg)

[Source]

# File resolv.rb, line 1499
        def encode_rdata(msg)
          msg.put_string(@cpu)
          msg.put_string(@os)
        end


Module: Resolv::DNS::Resource::IN

Module | Resolv::DNS::Resource::IN
In: | 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: | 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)

[Source]

# File resolv.rb, line 1607
          def self.decode_rdata(msg)
            return self.new(IPv4.new(msg.get_bytes(4)))
          end
new(address)

[Source]

# File resolv.rb, line 1598
          def initialize(address)
            @address = IPv4.create(address)
          end

Public Instance methods

encode_rdata(msg)

[Source]

# File resolv.rb, line 1603
          def encode_rdata(msg)
            msg.put_bytes(@address.address)
          end


Class: Resolv::DNS::Resource::IN::AAAA

Class | Resolv::DNS::Resource::IN::AAAA
In: | 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)

[Source]

# File resolv.rb, line 1648
          def self.decode_rdata(msg)
            return self.new(IPv6.new(msg.get_bytes(16)))
          end
new(address)

[Source]

# File resolv.rb, line 1639
          def initialize(address)
            @address = IPv6.create(address)
          end

Public Instance methods

encode_rdata(msg)

[Source]

# File resolv.rb, line 1644
          def encode_rdata(msg)
            msg.put_bytes(@address.address)
          end


Class: Resolv::DNS::Resource::IN::SRV

Class | Resolv::DNS::Resource::IN::SRV
In: | 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)

[Source]

# File 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(priority, weight, port, target)

Create a SRV resource record.

[Source]

# File 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

Public Instance methods

encode_rdata(msg)

[Source]

# File 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


Class: Resolv::DNS::Resource::IN::WKS

Class | Resolv::DNS::Resource::IN::WKS
In: | 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)

[Source]

# File 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(address, protocol, bitmap)

[Source]

# File resolv.rb, line 1615
          def initialize(address, protocol, bitmap)
            @address = IPv4.create(address)
            @protocol = protocol
            @bitmap = bitmap
          end

Public Instance methods

encode_rdata(msg)

[Source]

# File resolv.rb, line 1622
          def encode_rdata(msg)
            msg.put_bytes(@address.address)
            msg.put_pack("n", @protocol)
            msg.put_bytes(@bitmap)
          end


Class: Resolv::DNS::Resource::MINFO

Class | Resolv::DNS::Resource::MINFO
In: | resolv.rb
Parent: | Resource

Methods

decode_rdata encode_rdata new

Constants

TypeValue = 14

Attributes

emailbx | [R]
rmailbx | [R]

Public Class methods

decode_rdata(msg)

[Source]

# File resolv.rb, line 1525
        def self.decode_rdata(msg)
          rmailbx = msg.get_string
          emailbx = msg.get_string
          return self.new(rmailbx, emailbx)
        end
new(rmailbx, emailbx)

[Source]

# File resolv.rb, line 1514
        def initialize(rmailbx, emailbx)
          @rmailbx = rmailbx
          @emailbx = emailbx
        end

Public Instance methods

encode_rdata(msg)

[Source]

# File resolv.rb, line 1520
        def encode_rdata(msg)
          msg.put_name(@rmailbx)
          msg.put_name(@emailbx)
        end


Class: Resolv::DNS::Resource::MX

Class | Resolv::DNS::Resource::MX
In: | resolv.rb
Parent: | Resource

Methods

decode_rdata encode_rdata new

Constants

TypeValue = 15

Attributes

exchange | [R]
preference | [R]

Public Class methods

decode_rdata(msg)

[Source]

# File 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(preference, exchange)

[Source]

# File resolv.rb, line 1535
        def initialize(preference, exchange)
          @preference = preference
          @exchange = exchange
        end

Public Instance methods

encode_rdata(msg)

[Source]

# File resolv.rb, line 1541
        def encode_rdata(msg)
          msg.put_pack('n', @preference)
          msg.put_name(@exchange)
        end


Class: Resolv::DNS::Resource::NS

Class | Resolv::DNS::Resource::NS
In: | resolv.rb
Parent: | DomainName

Constants

TypeValue = 2


Class: Resolv::DNS::Resource::PTR

Class | Resolv::DNS::Resource::PTR
In: | resolv.rb
Parent: | DomainName

Constants

TypeValue = 12


Class: Resolv::DNS::Resource::SOA

Class | Resolv::DNS::Resource::SOA
In: | 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)

[Source]

# File 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(mname, rname, serial, refresh, retry_, expire, minimum)

[Source]

# File 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

Public Instance methods

encode_rdata(msg)

[Source]

# File 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


Class: Resolv::DNS::Resource::TXT

Class | Resolv::DNS::Resource::TXT
In: | resolv.rb
Parent: | Resource

Methods

data decode_rdata encode_rdata new

Constants

TypeValue = 16

Attributes

strings [R]

Public Class methods

decode_rdata(msg)

[Source]

# File resolv.rb, line 1569
        def self.decode_rdata(msg)
          strings = msg.get_string_list
          return self.new(*strings)
        end
new(first_string, *rest_strings)

[Source]

# File resolv.rb, line 1556
        def initialize(first_string, *rest_strings)
          @strings = [first_string, *rest_strings]
        end

Public Instance methods

data()

[Source]

# File resolv.rb, line 1561
        def data
          @strings[0]
        end
encode_rdata(msg)

[Source]

# File resolv.rb, line 1565
        def encode_rdata(msg)
          msg.put_string_list(@strings)
        end


Class: Resolv::Hosts

Class | Resolv::Hosts
In: | 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)

[Source]

# File resolv.rb, line 288
    def initialize(filename = DefaultFileName)
      @filename = filename
      @mutex = Mutex.new
      @initialized = nil
    end

Public Instance methods

each_address(name, &proc)

[Source]

# File resolv.rb, line 336
    def each_address(name, &proc)
      lazy_initialize
      if @name2addr.include?(name)
        @name2addr[name].each(&proc)
      end
    end
each_name(address, &proc)

[Source]

# File resolv.rb, line 354
    def each_name(address, &proc)
      lazy_initialize
      if @addr2name.include?(address)
        @addr2name[address].each(&proc)
      end
    end
getaddress(name)

[Source]

# File resolv.rb, line 325
    def getaddress(name)
      each_address(name) {|address| return address}
      raise ResolvError.new("#{@filename} has no name: #{name}")
    end
getaddresses(name)

[Source]

# File resolv.rb, line 330
    def getaddresses(name)
      ret = []
      each_address(name) {|address| ret << address}
      return ret
    end
getname(address)

[Source]

# File resolv.rb, line 343
    def getname(address)
      each_name(address) {|name| return name}
      raise ResolvError.new("#{@filename} has no address: #{address}")
    end
getnames(address)

[Source]

# File resolv.rb, line 348
    def getnames(address)
      ret = []
      each_name(address) {|name| ret << name}
      return ret
    end
lazy_initialize()

[Source]

# File 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


Class: Resolv::IPv4

Class | Resolv::IPv4
In: | 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)

[Source]

# File 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(address)

[Source]

# File 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

Public Instance methods

==(other)

[Source]

# File resolv.rb, line 1756
    def ==(other)
      return @address == other.address
    end
eql?(other)

[Source]

# File resolv.rb, line 1760
    def eql?(other)
      return self == other
    end
hash()

[Source]

# File resolv.rb, line 1764
    def hash
      return @address.hash
    end
inspect()

[Source]

# File resolv.rb, line 1747
    def inspect
      return "#<#{self.class} #{self.to_s}>"
    end
to_name()

[Source]

# File resolv.rb, line 1751
    def to_name
      return DNS::Name.create(
        '%d.%d.%d.%d.in-addr.arpa.' % @address.unpack('CCCC').reverse)
    end
to_s()

[Source]

# File resolv.rb, line 1743
    def to_s
      return sprintf("%d.%d.%d.%d", *@address.unpack("CCCC"))
    end


Class: Resolv::IPv6

Class | Resolv::IPv6
In: | 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)

[Source]

# File 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(address)

[Source]

# File 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

Public Instance methods

==(other)

[Source]

# File resolv.rb, line 1869
    def ==(other)
      return @address == other.address
    end
eql?(other)

[Source]

# File resolv.rb, line 1873
    def eql?(other)
      return self == other
    end
hash()

[Source]

# File resolv.rb, line 1877
    def hash
      return @address.hash
    end
inspect()

[Source]

# File resolv.rb, line 1859
    def inspect
      return "#<#{self.class} #{self.to_s}>"
    end
to_name()

[Source]

# File 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
to_s()

[Source]

# File 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


Class: Resolv::ResolvError

Class | Resolv::ResolvError
In: | resolv.rb
Parent: | StandardError


Class: Resolv::ResolvTimeout

Class | Resolv::ResolvTimeout
In: | resolv.rb
Parent: | TimeoutError


File: resolv.rb

resolv.rb

Path: | resolv.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

Required files

socket fcntl timeout thread win32/resolv


File: resolv-replace.rb

resolv-replace.rb

Path: | resolv-replace.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

Required files

socket resolv


Class: SOCKSSocket

Class | SOCKSSocket
In: | resolv-replace.rb
Parent: | Object

Methods

new

External Aliases

initialize -> original_resolv_initialize

Public Class methods

new(host, serv)

[Source]

# File resolv-replace.rb, line 59
  def initialize(host, serv)
    original_resolv_initialize(IPSocket.getaddress(host), port)
  end


Class: TCPSocket

Class | TCPSocket
In: | resolv-replace.rb
Parent: | Object

Methods

new

External Aliases

initialize -> original_resolv_initialize

Public Class methods

new(host, serv, *rest)

[Source]

# File 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


Class: UDPSocket

Class | UDPSocket
In: | resolv-replace.rb
Parent: | Object

Methods

bind connect send

External Aliases

bind | -> | original_resolv_bind
connect | -> | original_resolv_connect
send | -> | original_resolv_send

Public Instance methods

bind(host, port)

[Source]

# File resolv-replace.rb, line 25
  def bind(host, port)
    original_resolv_bind(IPSocket.getaddress(host), port)
  end
connect(host, port)

[Source]

# File resolv-replace.rb, line 30
  def connect(host, port)
    original_resolv_connect(IPSocket.getaddress(host), port)
  end
send(mesg, flags, *rest)

[Source]

# File 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


File: rexml.rb

rexml.rb

Path: | rexml/rexml.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

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.3
Date: | 2005/224

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


Class: Array

Class | Array
In: | rexml/xpath_parser.rb
Parent: | Object

Methods

dclone

Public Instance methods

dclone()

[Source]

# File rexml/xpath_parser.rb, line 18
  def dclone
    klone = self.clone
    klone.clear
    self.each{|v| klone << v.dclone}
    klone
  end


Class: Object

Class | Object
In: | rexml/xpath_parser.rb
Parent: | Object

Methods

dclone

Public Instance methods

dclone()

[Source]

# File rexml/xpath_parser.rb, line 8
  def dclone
    clone
  end


Module: REXML
In: rexml/xpath_parser.rb
rexml/xpath.rb
rexml/xmltokens.rb
rexml/xmldecl.rb
rexml/validation/validationexception.rb
rexml/validation/validation.rb
rexml/validation/relaxng.rb
rexml/text.rb
rexml/syncenumerator.rb
rexml/streamlistener.rb
rexml/source.rb
rexml/sax2listener.rb
rexml/rexml.rb
rexml/quickpath.rb
rexml/parsers/xpathparser.rb
rexml/parsers/ultralightparser.rb
rexml/parsers/treeparser.rb
rexml/parsers/streamparser.rb
rexml/parsers/sax2parser.rb
rexml/parsers/pullparser.rb
rexml/parsers/lightparser.rb
rexml/parsers/baseparser.rb
rexml/parseexception.rb
rexml/parent.rb
rexml/output.rb
rexml/node.rb
rexml/namespace.rb
rexml/light/node.rb
rexml/instruction.rb
rexml/functions.rb
rexml/entity.rb
rexml/encodings/UTF-8.rb
rexml/encodings/UTF-16.rb
rexml/encodings/US-ASCII.rb
rexml/encodings/UNILE.rb
rexml/encodings/SHIFT-JIS.rb
rexml/encodings/ISO-8859-15.rb
rexml/encodings/ISO-8859-1.rb
rexml/encodings/ICONV.rb
rexml/encodings/EUC-JP.rb
rexml/encodings/CP-1252.rb
rexml/encoding.rb
rexml/element.rb
rexml/dtd/notationdecl.rb
rexml/dtd/entitydecl.rb
rexml/dtd/elementdecl.rb
rexml/dtd/dtd.rb
rexml/dtd/attlistdecl.rb
rexml/document.rb
rexml/doctype.rb
rexml/comment.rb
rexml/child.rb
rexml/cdata.rb
rexml/attribute.rb
rexml/attlistdecl.rb

-*- mode: ruby; ruby-indent-level: 2; indent-tabs-mode: t; tab-width: 2 -*- vim: sw=2 ts=2

Classes and Modules

Module REXML::DTD
Module REXML::Encoding
Module REXML::EntityConst
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::XMLDecl
Class REXML::XPath
Class REXML::XPathParser

Constants

Copyright | = | "Copyright © 2001, 2002, 2003, 2004 Sean Russell <ser@germane-software.com>"
Date | = | "2005/224"
Version | = | "3.1.3"


Class: REXML::AttlistDecl

Class | REXML::AttlistDecl
In: | 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?

[Source]

# File rexml/attlistdecl.rb, line 28
                def initialize(source)
                        super()
                        if (source.kind_of? Array)
                                @element_name, @pairs, @contents = *source
                        end
                end

Public Instance methods

[](key)

Access the attlist attribute/value pairs.

 value = attlist_decl[ attribute_name ]

[Source]

# File rexml/attlistdecl.rb, line 37
                def [](key)
                        @pairs[key]
                end
each(&block)

Itterate over the key/value pairs:

 attlist_decl.each { |attribute_name, attribute_value| ... }

[Source]

# File rexml/attlistdecl.rb, line 49
                def each(&block)
                        @pairs.each(&block)
                end
include?(key)

Whether an attlist declaration includes the given attribute definition

 if attlist_decl.include? "xmlns:foobar"

[Source]

# File rexml/attlistdecl.rb, line 43
                def include?(key)
                        @pairs.keys.include? key
                end
node_type()

[Source]

# File rexml/attlistdecl.rb, line 58
                def node_type
                        :attlistdecl
                end
write(out, indent=-1)

Write out exactly what we got in.

[Source]

# File rexml/attlistdecl.rb, line 54
                def write out, indent=-1
                        out << @contents
                end


Class: REXML::Attribute

Class | REXML::Attribute
In: | 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.

 Attribute.new( attribute_to_clone )
 Attribute.new( source )
 Attribute.new( "attr", "attr_value" )
 Attribute.new( "attr", "attr_value", parent_element )

[Source]

# File rexml/attribute.rb, line 26
                def initialize( first, second=nil, parent=nil )
                        @normalized = @unnormalized = @element = nil
                        if first.kind_of? Attribute
                                self.name = first.expanded_name
                                @value = first.value
                                if second.kind_of? Element
                                        @element = second
                                else
                                        @element = first.element
                                end
                        elsif first.kind_of? String
                                @element = parent if parent.kind_of? Element
                                self.name = first
                                @value = second.to_s
                        else
                                raise "illegal argument #{first.class.name} to Attribute constructor"
                        end
                end

Public Instance methods

==( other )

Returns true if other is an Attribute and has the same name and value, false otherwise.

[Source]

# File rexml/attribute.rb, line 74
                def ==( other )
                        other.kind_of?(Attribute) and other.name==name and other.value==@value
                end
clone()

Returns a copy of this attribute

[Source]

# File rexml/attribute.rb, line 121
                def clone
                        Attribute.new self
                end
element=( element )

Sets the element of which this object is an attribute. Normally, this is not directly called.

Returns this attribute

[Source]

# File rexml/attribute.rb, line 129
                def element=( element )
                        @element = element
                        self
                end
hash()

Creates (and returns) a hash from both the name and value

[Source]

# File rexml/attribute.rb, line 79
                def hash
                        name.hash + value.hash
                end
inspect()

[Source]

# File rexml/attribute.rb, line 150
    def inspect
      rv = ""
      write( rv )
      rv
    end
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"

[Source]

# File rexml/attribute.rb, line 67
                def namespace arg=nil
                        arg = prefix if arg.nil?
                        @element.namespace arg
                end
node_type()

[Source]

# File rexml/attribute.rb, line 146
    def node_type
      :attribute
    end
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                                   # -> ""

[Source]

# File rexml/attribute.rb, line 54
                def prefix
                        pf = super
                        if pf == ""
                                pf = @element.prefix if @element
                        end
                        pf
                end
remove()

Removes this Attribute from the tree, and returns true if successfull

This method is usually not called directly.

[Source]

# File rexml/attribute.rb, line 137
                def remove
                        @element.attributes.delete self.name unless @element.nil?
                end
to_s()

Returns the attribute value, with entities replaced

[Source]

# File rexml/attribute.rb, line 94
                def to_s
                        return @normalized if @normalized

                        doctype = nil
                        if @element
                                doc = @element.document
                                doctype = doc.doctype if doc
                        end

                        @unnormalized = nil
                        @normalized = Text::normalize( @value, doctype )
                end
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'"

[Source]

# File rexml/attribute.rb, line 89
                def to_string
                        "#@expanded_name='#{to_s().gsub(/'/, '&apos;')}'"
                end
value()

Returns the UNNORMALIZED value of this attribute. That is, entities have been expanded to their values

[Source]

# File rexml/attribute.rb, line 109
                def value
                        return @unnormalized if @unnormalized
                        doctype = nil
                        if @element
                                doc = @element.document
                                doctype = doc.doctype if doc
                        end
                        @normalized = nil
                        @unnormalized = Text::unnormalize( @value, doctype )
                end
write( output, indent=-1 )

Writes this attribute (EG, puts ‘key="value"’ to the output)

[Source]

# File rexml/attribute.rb, line 142
                def write( output, indent=-1 )
                        output << to_string
                end
xpath()

[Source]

# File rexml/attribute.rb, line 156
    def xpath
      path = @element.xpath
      path += "/@#{self.expanded_name}"
      return path
    end


Class: REXML::Attributes

Class | REXML::Attributes
In: | 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 length namespaces new prefixes size to_a

Public Class methods

new(element)

Constructor

element: the Element of which this is an Attribute

[Source]

# File rexml/element.rb, line 982
                def initialize element
                        @element = element
                end

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.
 doc = Document.new "<a foo:att='1' bar:att='2' att='3'/>"
 doc.root.attributes['att']         #-> '3'
 doc.root.attributes['bar:att']     #-> '2'

[Source]

# File rexml/element.rb, line 996
                def [](name)
                        attr = get_attribute(name)
                        return attr.value unless attr.nil?
                        return nil
                end
[]=( 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

[Source]

# File rexml/element.rb, line 1098
                def []=( name, value )
                        if value.nil?                # Delete the named attribute
                                attr = get_attribute(name)
                                delete attr
                                return
                        end
                        value = Attribute.new(name, value) unless value.kind_of? Attribute
                        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
add( attribute )

Adds an attribute, overriding any existing attribute by the same name. Namespaces are significant.

attribute: An Attribute

[Source]

# File rexml/element.rb, line 1209
                def add( attribute )
                        self[attribute.name] = attribute
                end
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'/>"

[Source]

# File rexml/element.rb, line 1177
                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
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

[Source]

# File rexml/element.rb, line 1219
                def delete_all( name )
                        rv = []
                        each_attribute { |attribute|
                                rv << attribute if attribute.expanded_name == name
                        }
                        rv.each{ |attr| attr.remove }
                        return rv
                end
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 }

[Source]

# File rexml/element.rb, line 1038
                def each
                        each_attribute do |attr|
                                yield attr.expanded_name, attr.value
                        end
                end
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
 }

[Source]

# File rexml/element.rb, line 1023
                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
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"

[Source]

# File rexml/element.rb, line 1053
                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
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

[Source]

# File rexml/element.rb, line 1009
                def length
                        c = 0
                        each_attribute { c+=1 }
                        c
                end
namespaces()

[Source]

# File rexml/element.rb, line 1151
                def namespaces
                        namespaces = []
                        each_attribute do |attribute|
                                namespaces << 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.value if attribute.prefix == 'xmlns' or attribute.name == 'xmlns'
                                }
                        end
                        namespaces
                end
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']

[Source]

# File rexml/element.rb, line 1135
                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
size()

Alias for length

to_a()

[Source]

# File rexml/element.rb, line 1002
                def to_a
                        values.flatten
                end


Class: REXML::CData

Class | REXML::CData
In: | rexml/cdata.rb
Parent: | Text

Methods

clone new to_s 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 )

[Source]

# File rexml/cdata.rb, line 15
                def initialize( first, whitespace=true, parent=nil )
                        super( first, whitespace, parent, true, true, ILLEGAL )
                end

Public Instance methods

clone()

Make a copy of this object

Examples

 c = CData.new( "Some text" )
 d = c.clone
 d.to_s        # -> "Some text"

[Source]

# File rexml/cdata.rb, line 25
                def clone
                        CData.new self
                end
to_s()

Returns the content of this CData object

Examples

 c = CData.new( "Some text" )
 c.to_s        # -> "Some text"

[Source]

# File rexml/cdata.rb, line 34
                def to_s
                        @string
                end
write( output=$stdout, indent=-1, transitive=false, ie_hack=false )

Generates XML output of this object

output: | Where to write the string. Defaults to $stdout
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 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.

Examples

 c = CData.new( " Some text " )
 c.write( $stdout )     #->  <![CDATA[ Some text ]]>

[Source]

# File rexml/cdata.rb, line 61
                def write( output=$stdout, indent=-1, transitive=false, ie_hack=false )
      #indent( output, indent ) unless transitive
                        output << START
                        output << @string
                        output << STOP
                end


Class: REXML::Child

Class | REXML::Child
In: | 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

[Source]

# File 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

Public Instance methods

bytes()

This doesn’t yet handle encodings

[Source]

# File rexml/child.rb, line 90
                def bytes
                        encoding = document.encoding

                        to_s
                end
document()
Returns: the document this child belongs to, or nil if this child

belongs to no document

[Source]

# File rexml/child.rb, line 84
                def document
                        return parent.document unless parent.nil?
                        nil
                end
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>

[Source]

# File rexml/child.rb, line 67
                def next_sibling=( other )
                  parent.insert_after self, other
                end
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

[Source]

# File rexml/child.rb, line 51
                def parent=( other )
                        return @parent if @parent == other
                        @parent.delete self if defined? @parent and @parent
                        @parent = other
                end
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>

[Source]

# File rexml/child.rb, line 78
                def previous_sibling=(other)
                  parent.insert_before self, other
                end
remove()

Removes this child from the parent.

Returns: self

[Source]

# File rexml/child.rb, line 36
                def remove
                        unless @parent.nil?
                                @parent.delete self
                        end
                        self
                end
replace_with( child )

Replaces this object with another object. Basically, calls Parent.replace_child

Returns: self

[Source]

# File rexml/child.rb, line 28
                def replace_with( child )
                        @parent.replace_child( self, child )
                        self
                end


Class: REXML::Comment

Class | REXML::Comment
In: | 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]

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

[Source]

# File rexml/comment.rb, line 21
                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

Public Instance methods

<=>(other)

Compares this Comment to another; the contents of the comment are used in the comparison.

[Source]

# File rexml/comment.rb, line 69
                def <=>(other)
                        other.to_s <=> @string
                end
==( other )

Compares this Comment to another; the contents of the comment are used in the comparison.

[Source]

# File rexml/comment.rb, line 76
                def ==( other )
                        other.kind_of? Comment and
                        (other <=> self) == 0
                end
clone()

[Source]

# File rexml/comment.rb, line 31
                def clone
                        Comment.new self
                end
node_type()

[Source]

# File rexml/comment.rb, line 81
    def node_type
      :comment
    end
write( output, indent=-1, transitive=false, ie_hack=false )
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: | 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.

[Source]

# File rexml/comment.rb, line 53
                def write( output, indent=-1, transitive=false, ie_hack=false )
                        indent( output, indent )
                        output << START
                        output << @string
      if indent>-1
        output << "\n"
        indent( output, indent )
      end
                        output << STOP
                end


Module: REXML::DTD

Module | REXML::DTD
In: | rexml/dtd/notationdecl.rb rexml/dtd/entitydecl.rb rexml/dtd/elementdecl.rb rexml/dtd/dtd.rb 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: | 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: | 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)

[Source]

# File rexml/dtd/elementdecl.rb, line 11
                        def initialize match
                                @name = match[1]
                                @rest = match[2]
                        end


Class: REXML::DTD::EntityDecl

Class | REXML::DTD::EntityDecl
In: | 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 "…">

[Source]

# File 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
parse_source(source, listener)

[Source]

# File 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

Public Instance methods

to_s()

[Source]

# File rexml/dtd/entitydecl.rb, line 37
                        def to_s
                                rv = "<!ENTITY #@name "
                                rv << "#@middle " if @middle.size > 0
                                rv << @content
                                rv
                        end
write( output, indent )

[Source]

# File rexml/dtd/entitydecl.rb, line 44
                        def write( output, indent )
        indent( output, indent )
                                output << to_s
                        end


Class: REXML::DTD::NotationDecl

Class | REXML::DTD::NotationDecl
In: | 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)

[Source]

# File 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
parse_source(source, listener)

[Source]

# File 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

Public Instance methods

to_s()

[Source]

# File rexml/dtd/notationdecl.rb, line 23
                        def to_s
                                "<!NOTATION #@name #@middle #@rest>"
                        end
write( output, indent )

[Source]

# File rexml/dtd/notationdecl.rb, line 27
                        def write( output, indent )
        indent( output, indent )
                                output << to_s
                        end


Class: REXML::DTD::Parser

Class | REXML::DTD::Parser
In: | rexml/dtd/dtd.rb
Parent: | Object

Methods

parse parse_helper

Public Class methods

parse( input )

[Source]

# File 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( input )

Takes a String and parses it out

[Source]

# File 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 << EleemntDecl.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


Class: REXML::Declaration

Class | REXML::Declaration
In: | 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)

[Source]

# File rexml/doctype.rb, line 161
                def initialize src
                        super()
                        @string = src
                end

Public Instance methods

to_s()

[Source]

# File rexml/doctype.rb, line 166
                def to_s
                        @string+'>'
                end
write( output, indent )

[Source]

# File rexml/doctype.rb, line 170
                def write( output, indent )
                        output << ('   '*indent) if indent > 0
                        output << to_s
                end


Class: REXML::DocType

Class | REXML::DocType
In: | 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 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.

[Source]

# File 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

Public Instance methods

add(child)

[Source]

# File rexml/doctype.rb, line 147
                def add child
                        super(child)
                        @entities = DEFAULT_ENTITIES.clone if @entities == DEFAULT_ENTITIES
                        @entities[ child.name ] = child if child.kind_of? Entity
                end
attribute_of(element, attribute)

[Source]

# File 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
attributes_of(element)

[Source]

# File 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
clone()

[Source]

# File rexml/doctype.rb, line 94
                def clone
                        DocType.new self
                end
context()

[Source]

# File rexml/doctype.rb, line 139
    def context
      @parent.context
    end
entity( name )

[Source]

# File rexml/doctype.rb, line 143
                def entity( name )
                        @entities[name].unnormalized if @entities[name]
                end
node_type()

[Source]

# File rexml/doctype.rb, line 70
                def node_type
                        :doctype
                end
write( output, indent=0, transitive=false, ie_hack=false )
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: | 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.

[Source]

# File rexml/doctype.rb, line 116
                def write( output, indent=0, transitive=false, ie_hack=false )
                        indent( output, indent )
                        output << START
                        output << ' '
                        output << @name
                        output << " #@external_id" if @external_id
                        output << " #@long_name" if @long_name
                        output << " #@uri" if @uri
                        unless @children.empty?
                                next_indent = indent + 1
                                output << ' ['
                                child = nil         # speed
                                @children.each { |child|
                                        output << "\n"
                                        child.write( output, next_indent )
                                }
                                output << "\n"
                                #output << '   '*next_indent
                                output << "]"
                        end
                        output << STOP
                end


Class: REXML::Document

Class | REXML::Document
In: | 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. NOTE that I’m not sure what the context is for; I cloned it out of the Electric XML API (in which it also seems to do nothing), and it is now legacy. It may do something, someday… it may disappear.

[Source]

# File rexml/document.rb, line 37
                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
parse_stream( source, listener )

[Source]

# File rexml/document.rb, line 172
                def Document::parse_stream( source, listener )
                        Parsers::StreamParser.new( source, listener ).parse
                end

Public Instance methods

<<( child )

Alias for add

add( child )

We override this, because XMLDecls and DocTypes must go at the start of the document

[Source]

# File rexml/document.rb, line 69
                def add( child )
                        if child.kind_of? XMLDecl
                                @children.unshift child
                        elsif child.kind_of? DocType
                                if @children[0].kind_of? XMLDecl
                                        @children[1,0] = child
                                else
                                        @children.unshift 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(arg=nil, arg2=nil)

[Source]

# File rexml/document.rb, line 87
                def add_element(arg=nil, arg2=nil)
                        rv = super
                        raise "attempted adding second root element to document" if @elements.size > 1
                        rv
                end
clone()

Should be obvious

[Source]

# File rexml/document.rb, line 54
                def clone
                        Document.new self
                end
doctype()

@return the DocType child of the document, if one exists, and nil otherwise.

[Source]

# File rexml/document.rb, line 103
                def doctype
                        @children.find { |item| item.kind_of? DocType }
                end
encoding()

@return the XMLDecl encoding of this document as a String. If no XMLDecl has been set, returns the default encoding.

[Source]

# File rexml/document.rb, line 123
                def encoding
                        xml_decl().encoding
                end
expanded_name()

According to the XML spec, a root node has no expanded name

[Source]

# File rexml/document.rb, line 59
                def expanded_name
                        ''
                        #d = doc_type
                        #d ? d.name : "UNDEFINED"
                end
name()

Alias for expanded_name

node_type()

[Source]

# File rexml/document.rb, line 49
    def node_type
      :document
    end
root()

@return the root Element of the document, or nil if this document has no children.

[Source]

# File rexml/document.rb, line 95
                def root
      elements[1]
      #self
      #@children.find { |item| item.kind_of? Element }
                end
stand_alone?()

@return the XMLDecl standalone value of this document as a String. If no XMLDecl has been set, returns the default setting.

[Source]

# File rexml/document.rb, line 129
                def stand_alone?
                        xml_decl().stand_alone?
                end
version()

@return the XMLDecl version of this document as a String. If no XMLDecl has been set, returns the default version.

[Source]

# File rexml/document.rb, line 117
                def version
                        xml_decl().version
                end
write( output=$stdout, indent=-1, transitive=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.

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 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

[Source]

# File rexml/document.rb, line 161
                def write( output=$stdout, indent=-1, transitive=false, ie_hack=false )
                        output = Output.new( output, xml_decl.encoding ) if xml_decl.encoding != "UTF-8" && !output.kind_of?(Output)
                        @children.each { |node|
                                indent( output, indent ) if node.node_type == :element
                                if node.write( output, indent, transitive, ie_hack )
          output << "\n" unless indent<0 or node == @children[-1]
        end
                        }
                end
xml_decl()

@return the XMLDecl of this document; if no XMLDecl has been set, the default declaration is returned.

[Source]

# File rexml/document.rb, line 109
                def xml_decl
                        rv = @children[0]
      return rv if rv.kind_of? XMLDecl
      rv = @children.unshift(XMLDecl.default)[0]
                end


Class: REXML::Element

Class | REXML::Element
In: | 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.

[Source]

# File 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

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.
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'/>

[Source]

# File rexml/element.rb, line 591
                def add_attribute( key, value=nil )
                        if key.kind_of? Attribute
                                @attributes << key
                        else
                                @attributes[key] = value
                        end
                end
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"] ] )

[Source]

# File rexml/element.rb, line 603
                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
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

[Source]

# File 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)
                        if attrs.kind_of? Hash
                                attrs.each do |key, value|
                                        el.attributes[key]=value if key =~ /^xmlns:/
                                end
                                attrs.each do |key, value|
                                        el.attributes[key]=value if key !~ /^xmlns:/
                                end
                        end
                        el
                end
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'/>

[Source]

# File 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
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.

[Source]

# File rexml/element.rb, line 528
                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
attribute( name, namespace=nil )

Attributes #

[Source]

# File rexml/element.rb, line 559
                def attribute( name, namespace=nil )
                        prefix = ''
                        if namespace
                                prefix = attributes.prefixes.each { |prefix|
                                        return "#{prefix}:" if namespace( prefix ) == namespace
                                } || ''
                        end
                        attributes.get_attribute( "#{prefix}#{name}" )
                end
cdatas()

Get an array of all CData children. IMMUTABLE

[Source]

# File rexml/element.rb, line 635
                def cdatas
                        find_all { |child| child.kind_of? CData }.freeze
                end
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/>"

[Source]

# File rexml/element.rb, line 96
                def clone
                        Element.new self
                end
comments()

Get an array of all Comment children. IMMUTABLE

[Source]

# File rexml/element.rb, line 641
                def comments
                        find_all { |child| child.kind_of? Comment }.freeze
                end
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/>

[Source]

# File rexml/element.rb, line 624
                def delete_attribute(key)
                        attr = @attributes.get_attribute(key)
                        attr.remove unless attr.nil?
                end
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

[Source]

# File rexml/element.rb, line 320
                def delete_element element
                        @elements.delete element
                end
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/>

[Source]

# File 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
document()

Evaluates to the document to which this element belongs, or nil if this element doesn’t belong to a document.

[Source]

# File rexml/element.rb, line 131
                def document
      rt = root
                        rt.parent if rt
                end
each_element( xpath=nil ) {|Element| ...}

Synonym for Element.elements.each

[Source]

# File rexml/element.rb, line 397
                def each_element( xpath=nil, &block ) # :yields: Element
                        @elements.each( xpath, &block )
                end
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}

[Source]

# File rexml/element.rb, line 355
                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( 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}

[Source]

# File rexml/element.rb, line 386
                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
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

[Source]

# File rexml/element.rb, line 405
                def get_elements( xpath )
                        @elements.to_a( xpath )
                end
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 "

[Source]

# File rexml/element.rb, line 466
                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
has_attributes?()

Evaluates to true if this element has any attributes set, false otherwise.

[Source]

# File rexml/element.rb, line 571
                def has_attributes?
                        return !@attributes.empty?
                end
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

[Source]

# File rexml/element.rb, line 329
                def has_elements?
                        !@elements.empty?
                end
has_text?()

Evaluates to true if this element has at least one Text child

[Source]

# File rexml/element.rb, line 437
                def has_text?
                        not text().nil?
                end
ignore_whitespace_nodes()

[Source]

# File 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
inspect()

[Source]

# File 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
instructions()

Get an array of all Instruction children. IMMUTABLE

[Source]

# File rexml/element.rb, line 647
                def instructions
                        find_all { |child| child.kind_of? Instruction }.freeze
                end
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'

[Source]

# File 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
namespaces()

[Source]

# File rexml/element.rb, line 202
                def namespaces
                        namespaces = []
                        namespaces = parent.namespaces if parent
                        namespaces |= attributes.namespaces
                        return namespaces
                end
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

[Source]

# File rexml/element.rb, line 414
                def next_element
                        element = next_sibling
                        element = element.next_sibling until element.nil? or element.kind_of? Element
                        return element
                end
node_type()

[Source]

# File rexml/element.rb, line 540
    def node_type
      :element
    end
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']

[Source]

# File rexml/element.rb, line 195
                def prefixes
                        prefixes = []
                        prefixes = parent.prefixes if parent
                        prefixes |= attributes.prefixes
                        return prefixes
                end
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

[Source]

# File rexml/element.rb, line 425
                def previous_element
                        element = previous_sibling
                        element = element.previous_sibling until element.nil? or element.kind_of? Element
                        return element
                end
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.

[Source]

# File rexml/element.rb, line 178
                def raw
                        @raw = (@context and @context[:raw] and
                        (@context[:raw] == :all or
                        @context[:raw].include? expanded_name))
                        @raw
                end
root()

[Source]

# File 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
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

[Source]

# File rexml/element.rb, line 119
                def root_node
                        parent.nil? ? self : parent.root_node
                end
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 "

[Source]

# File rexml/element.rb, line 455
                def text( path = nil )
                        rv = get_text(path)
                        return rv.value unless rv.nil?
                        nil
                end
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>'

[Source]

# File rexml/element.rb, line 497
                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
texts()

Get an array of all Text children. IMMUTABLE

[Source]

# File rexml/element.rb, line 653
                def texts
                        find_all { |child| child.kind_of? Text }.freeze
                end
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.

[Source]

# File 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
write(writer=$stdout, indent=-1, transitive=false, ie_hack=false)

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

[Source]

# File rexml/element.rb, line 679
                def write(writer=$stdout, indent=-1, transitive=false, ie_hack=false)
                        #print "ID:#{indent}"
                        writer << "<#@expanded_name"

                        @attributes.each_attribute do |attr|
                                writer << " "
                                attr.write( writer, indent )
                        end unless @attributes.empty?

                        if @children.empty?
        if transitive and indent>-1
          writer << "\n"
          indent( writer, indent )
        elsif ie_hack
          writer << " "
        end
                                writer << "/"
                        else
                                if transitive and indent>-1 and !@children[0].kind_of? Text
                                        writer << "\n"
                                        indent writer, indent+1
                                end
                                writer << ">"
                                write_children( writer, indent, transitive, ie_hack )
                                writer << "</#{expanded_name}"
                        end
                        if transitive and indent>-1 and !@children.empty?
                                writer << "\n"
                                indent -= 1 if next_sibling.nil?
                                indent(writer, indent)
                        end
                        writer << ">"
                end
xpath()

[Source]

# File rexml/element.rb, line 544
    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


Class: REXML::ElementDecl

Class | REXML::ElementDecl
In: | rexml/doctype.rb
Parent: | Declaration

Methods

new

Public Class methods

new( src )

[Source]

# File rexml/doctype.rb, line 178
                def initialize( src )
                        super
                end


Class: REXML::Elements

Class | REXML::Elements
In: | 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 delete delete_all each empty? index new size to_a

Included Modules

Enumerable

Public Class methods

new(parent)

Constructor

parent: the parent Element

[Source]

# File rexml/element.rb, line 775
                def initialize parent
                        @element = parent
                end

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"/>

[Source]

# File rexml/element.rb, line 800
                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
[]=( 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>

[Source]

# File rexml/element.rb, line 833
                def []=( index, element )
                        previous = self[index]
                        if previous.nil?
                                @element.add element
                        else
                                previous.replace_with element
                        end
                        return previous
                end
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>

[Source]

# File rexml/element.rb, line 909
                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
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/>

[Source]

# File rexml/element.rb, line 873
                def delete element
                        if element.kind_of? Element
                                @element.delete element
                        else
                                el = self[element]
                                el.remove if el
                        end
                end
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/>]

[Source]

# File rexml/element.rb, line 888
                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
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/>

[Source]

# File rexml/element.rb, line 938
                def each( xpath=nil, &block)
                        XPath::each( @element, xpath ) {|e| yield e if e.kind_of? Element }
                end
empty?()

Returns true if there are no Element children, false otherwise

[Source]

# File rexml/element.rb, line 844
                def empty?
                        @element.find{ |child| child.kind_of? Element}.nil?
                end
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

[Source]

# File rexml/element.rb, line 851
                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
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

[Source]

# File rexml/element.rb, line 946
                def size
                        count = 0
                        @element.each {|child| count+=1 if child.kind_of? Element }
                        count
                end
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/> ]

[Source]

# File rexml/element.rb, line 959
                def to_a( xpath=nil )
                        rv = XPath.match( @element, xpath )
                        return rv.find_all{|e| e.kind_of? Element} if xpath
                        rv
                end


Module: REXML::Encoding

Module | REXML::Encoding
In: | rexml/encodings/UTF-8.rb rexml/encodings/UTF-16.rb rexml/encodings/US-ASCII.rb rexml/encodings/UNILE.rb rexml/encodings/SHIFT-JIS.rb rexml/encodings/ISO-8859-15.rb rexml/encodings/ISO-8859-1.rb rexml/encodings/ICONV.rb rexml/encodings/EUC-JP.rb rexml/encodings/CP-1252.rb rexml/encoding.rb

Methods

apply check_encoding decode_ascii decode_eucjp decode_iconv decode_sjis decode_unile decode_utf16 decode_utf8 encode_ascii encode_eucjp encode_iconv encode_sjis encode_unile encode_utf16 encode_utf8 encoding= encoding_method register

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'

Attributes

encoding [R] ID —> Encoding name

Public Class methods

apply(obj, enc)

[Source]

# File rexml/encoding.rb, line 8
               def self.apply(obj, enc)
                       @encoding_methods[enc][obj]
               end
encoding_method(enc)

[Source]

# File rexml/encoding.rb, line 11
               def self.encoding_method(enc)
                       @encoding_methods[enc]
               end
register(enc, &block)

[Source]

# File rexml/encoding.rb, line 5
               def self.register(enc, &block)
                       @encoding_methods[enc] = block
               end

Public Instance methods

check_encoding(str)

[Source]

# File rexml/encoding.rb, line 55
                def check_encoding str
                        # We have to recognize UTF-16, LSB UTF-16, and UTF-8
                        return UTF_16 if str[0] == 254 && str[1] == 255
                        return UNILE if str[0] == 255 && str[1] == 254
                        str =~ /^\s*<?xml\s*version=(['"]).*?\2\s*encoding=(["'])(.*?)\2/um
                        return $1.upcase if $1
                        return UTF_8
                end
decode_ascii(str)

Convert to UTF-8

[Source]

# File rexml/encodings/US-ASCII.rb, line 19
    def decode_ascii(str)
      str.unpack('C*').pack('U*')
    end
decode_eucjp(str)

[Source]

# File rexml/encodings/EUC-JP.rb, line 5
    def decode_eucjp(str)
      Uconv::euctou8(str)
    end
decode_iconv(str)

[Source]

# File rexml/encodings/ICONV.rb, line 6
    def decode_iconv(str)
      Iconv.conv(UTF_8, @encoding, str)
    end
decode_sjis(content)

[Source]

# File rexml/encodings/SHIFT-JIS.rb, line 5
    def decode_sjis content
      Uconv::sjistou8(content)
    end
decode_unile(str)

[Source]

# File rexml/encodings/UNILE.rb, line 18
    def decode_unile(str)
      array_enc=str.unpack('C*')
      array_utf8 = []
      2.step(array_enc.size-1, 2){|i|
        array_utf8 << (array_enc.at(i) + array_enc.at(i+1)*0x100)
      }
      array_utf8.pack('U*')
    end
decode_utf16(str)

[Source]

# File rexml/encodings/UTF-16.rb, line 18
    def decode_utf16(str)
      array_enc=str.unpack('C*')
      array_utf8 = []
      2.step(array_enc.size-1, 2){|i|
        array_utf8 << (array_enc.at(i+1) + array_enc.at(i)*0x100)
      }
      array_utf8.pack('U*')
    end
decode_utf8(str)

[Source]

# File rexml/encodings/UTF-8.rb, line 7
    def decode_utf8(str)
      str
    end
encode_ascii(content)

Convert from UTF-8

[Source]

# File 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
encode_eucjp(content)

[Source]

# File rexml/encodings/EUC-JP.rb, line 9
    def encode_eucjp content
      Uconv::u8toeuc(content)
    end
encode_iconv(content)

[Source]

# File rexml/encodings/ICONV.rb, line 10
    def encode_iconv(content)
      Iconv.conv(@encoding, UTF_8, content)
    end
encode_sjis(str)

[Source]

# File rexml/encodings/SHIFT-JIS.rb, line 9
    def encode_sjis(str)
      Uconv::u8tosjis(str)
    end
encode_unile(content)

[Source]

# File 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
encode_utf16(content)

[Source]

# File 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
encode_utf8(content)

[Source]

# File rexml/encodings/UTF-8.rb, line 3
    def encode_utf8 content
      content
    end
encoding=( enc )

[Source]

# File rexml/encoding.rb, line 23
                def encoding=( enc )
                        old_verbosity = $VERBOSE
                        begin
                                $VERBOSE = false
                                return if defined? @encoding and enc == @encoding
                                if enc and enc != UTF_8
                                        @encoding = enc.upcase
                                        begin
                                               require 'rexml/encodings/ICONV.rb'
                                               Encoding.apply(self, "ICONV")
                                        rescue LoadError, Exception => err
                                               raise ArgumentError, "Bad encoding name #@encoding" unless @encoding =~ /^[\w-]+$/
                                                @encoding.untaint
                                                enc_file = File.join( "rexml", "encodings", "#@encoding.rb" )
                                                begin
                                                       require enc_file
                                                       Encoding.apply(self, @encoding)
                                                rescue LoadError
                                                       puts $!.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
                end


Class: REXML::Entity

Class | REXML::Entity
In: | 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.

[Source]

# File rexml/entity.rb, line 68
                def Entity::matches? string
                        (ENTITYDECL =~ string) == 0
                end
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', '&' )

[Source]

# File 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

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

[Source]

# File rexml/entity.rb, line 86
                def normalized
                        @value
                end
to_s()

Returns this entity as a string. See write().

[Source]

# File rexml/entity.rb, line 114
                def to_s
                        rv = ''
                        write rv
                        rv
                end
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.

[Source]

# File rexml/entity.rb, line 75
                def unnormalized
                        v = value()
                        return nil if v.nil?
                        @unnormalized = Text::unnormalize(v, parent)
                        @unnormalized
                end
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"

[Source]

# File rexml/entity.rb, line 129
                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
write(out, indent=-1)

Write out a fully formed, correct entity definition (assuming the Entity object itself is valid.)

[Source]

# File rexml/entity.rb, line 92
                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


Module: REXML::EntityConst

Module | REXML::EntityConst
In: | 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: | rexml/doctype.rb
Parent: | Child

Methods

new to_s write

Public Class methods

new( src )

[Source]

# File rexml/doctype.rb, line 184
                def initialize( src )
                        super()
                        @entity = src
                end

Public Instance methods

to_s()

[Source]

# File rexml/doctype.rb, line 188
                def to_s
                        @entity
                end
write( output, indent )

[Source]

# File rexml/doctype.rb, line 191
                def write( output, indent )
                        output << @entity
                        output << "\n"
                end


Module: REXML::Functions

Module | REXML::Functions
In: | 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 substring substring_after substring_before sum text translate true variables variables=

Public Class methods

boolean( object=nil )

UNTESTED

[Source]

# File rexml/functions.rb, line 255
    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
ceiling( number )

[Source]

# File rexml/functions.rb, line 350
    def Functions::ceiling( number )
      number(number).ceil
    end
compare_language(lang1, lang2)

[Source]

# File rexml/functions.rb, line 302
    def Functions::compare_language lang1, lang2
      lang2.downcase.index(lang1.downcase) == 0
    end
concat( *objects )

UNTESTED

[Source]

# File rexml/functions.rb, line 132
    def Functions::concat( *objects )
      objects.join
    end
contains( string, test )

Fixed by Mike Stok

[Source]

# File rexml/functions.rb, line 142
    def Functions::contains( string, test )
      string(string).include? string(test)
    end
context=(value)

[Source]

# File rexml/functions.rb, line 19
    def Functions::context=(value); @@context = value; end
count( node_set )

[Source]

# File rexml/functions.rb, line 39
    def Functions::count( node_set )
      node_set.size
    end
false( )

UNTESTED

[Source]

# File rexml/functions.rb, line 279
    def Functions::false(  )
      false
    end
floor( number )

[Source]

# File rexml/functions.rb, line 346
    def Functions::floor( number )
      number(number).floor
    end
get_namespace( node_set = nil ) {|@@context[:node] if defined? @@context[:node].namespace| ...}

Helper method.

[Source]

# File 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.namespace
          yield node_set
        else
          return unless node_set.kind_of? Enumerable
          node_set.each { |node| yield node if defined? node.namespace }
        end
      end
    end
id( object )

Since REXML is non-validating, this method is not implemented as it requires a DTD

[Source]

# File rexml/functions.rb, line 45
    def Functions::id( object )
    end
lang( language )

UNTESTED

[Source]

# File rexml/functions.rb, line 284
    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
last( )

[Source]

# File rexml/functions.rb, line 31
    def Functions::last( )
      @@context[:size]
    end
local_name( node_set=nil )

UNTESTED

[Source]

# File rexml/functions.rb, line 49
    def Functions::local_name( node_set=nil )
      get_namespace( node_set ) do |node|
        return node.local_name
      end
    end
method_missing( id )

[Source]

# File rexml/functions.rb, line 366
    def Functions::method_missing( id )
      puts "METHOD MISSING #{id.id2name}"
      XPath.match( @@context[:node], id.id2name )
    end
name( node_set=nil )

[Source]

# File rexml/functions.rb, line 59
    def Functions::name( node_set=nil )
      get_namespace( node_set ) do |node|
        node.expanded_name
      end
    end
namespace_context()

[Source]

# File rexml/functions.rb, line 16
    def Functions::namespace_context ; @@namespace_context ; end
namespace_context=(x)

[Source]

# File rexml/functions.rb, line 14
    def Functions::namespace_context=(x) ; @@namespace_context=x ; end
namespace_uri( node_set=nil )

[Source]

# File rexml/functions.rb, line 55
    def Functions::namespace_uri( node_set=nil )
      get_namespace( node_set ) {|node| node.namespace}
    end
normalize_space( string=nil )

UNTESTED

[Source]

# File rexml/functions.rb, line 208
    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
not( object )

UNTESTED

[Source]

# File rexml/functions.rb, line 269
    def Functions::not( object )
      not boolean( object )
    end
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

[Source]

# File rexml/functions.rb, line 319
    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 )
        #puts "STRING OF #{object.inspect} = #{str}"
        if str =~ /^\d+/
          object.to_s.to_f
        else
          (0.0 / 0.0)
        end
      end
    end
position( )

[Source]

# File rexml/functions.rb, line 35
    def Functions::position( )
      @@context[:index]
    end
processing_instruction( node )

[Source]

# File rexml/functions.rb, line 362
    def Functions::processing_instruction( node )
      node.node_type == :processing_instruction
    end
round( number )

[Source]

# File rexml/functions.rb, line 354
    def Functions::round( number )
      begin
        number(number).round
      rescue FloatDomainError
        number(number)
      end
    end
starts_with( string, test )

Fixed by Mike Stok

[Source]

# File rexml/functions.rb, line 137
    def Functions::starts_with( string, test )
      string(string).index(string(test)) == 0
    end
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.

[Source]

# File rexml/functions.rb, line 114
    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.text
        else
          object.to_s
        end
      else
        object.to_s
      end
    end
string_length( string )

UNTESTED

[Source]

# File rexml/functions.rb, line 203
    def Functions::string_length( string )
      string(string).length
    end
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.

[Source]

# File rexml/functions.rb, line 170
    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
substring_after( string, test )

Kouhei fixed this too

[Source]

# File rexml/functions.rb, line 158
    def Functions::substring_after( string, test )
      ruby_string = string(string)
      ruby_index = ruby_string.index(string(test))
      if ruby_index.nil?
        ""
      else
        ruby_string[ ruby_index+1..-1 ]
      end
    end
substring_before( string, test )

Kouhei fixed this

[Source]

# File rexml/functions.rb, line 147
    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
sum( nodes )

[Source]

# File rexml/functions.rb, line 341
    def Functions::sum( nodes )
      nodes = [nodes] unless nodes.kind_of? Array
      nodes.inject(0) { |r,n| r += number(string(n)) }
    end
text( )

[Source]

# File 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
translate( string, tr1, tr2 )

This is entirely Mike Stok’s beast

[Source]

# File rexml/functions.rb, line 218
    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
true( )

UNTESTED

[Source]

# File rexml/functions.rb, line 274
    def Functions::true( )
      true
    end
variables()

[Source]

# File rexml/functions.rb, line 17
    def Functions::variables ; @@variables ; end
variables=(x)

[Source]

# File rexml/functions.rb, line 15
    def Functions::variables=(x) ; @@variables=x ; end


Class: REXML::IOSource

Class | REXML::IOSource
In: | 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)

block_size has been deprecated

[Source]

# File rexml/source.rb, line 120
                def initialize(arg, block_size=500)
                        @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.
      str = @source.read( 2 )
      if (str[0] == 254 && str[1] == 255) || (str[0] == 255 && str[1] == 254)
        @encoding = check_encoding( str )
        @line_break = encode( '>' )
      else
        @line_break = '>'
      end
      super str+@source.readline( @line_break )
                end

Public Instance methods

consume( pattern )

[Source]

# File rexml/source.rb, line 175
                def consume( pattern )
                        match( pattern, true )
                end
current_line()

@return the current line in the source

[Source]

# File rexml/source.rb, line 206
                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
empty?()

[Source]

# File rexml/source.rb, line 197
                def empty?
                        super and ( @source.nil? || @source.eof? )
                end
match( pattern, cons=false )

[Source]

# File rexml/source.rb, line 179
                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
position()

[Source]

# File rexml/source.rb, line 201
    def position
      @er_source.pos
    end
read()

[Source]

# File rexml/source.rb, line 165
                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
scan(pattern, cons=false)

[Source]

# File rexml/source.rb, line 140
                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
                                                @source = nil
                                        end
                                end
                                rv = super
                        end
                        rv.taint
                        rv
                end


Class: REXML::Instruction

Class | REXML::Instruction
In: | 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.

[Source]

# File 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

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.

[Source]

# File rexml/instruction.rb, line 52
                def ==( other )
                        other.kind_of? Instruction and
                        other.target == @target and
                        other.content == @content
                end
clone()

[Source]

# File rexml/instruction.rb, line 37
                def clone
                        Instruction.new self
                end
inspect()

[Source]

# File rexml/instruction.rb, line 62
    def inspect
      "<?p-i #{target} ...?>"
    end
node_type()

[Source]

# File rexml/instruction.rb, line 58
    def node_type
      :processing_instruction
    end
write(writer, indent=-1, transitive=false, ie_hack=false)

[Source]

# File rexml/instruction.rb, line 41
                def write writer, indent=-1, transitive=false, ie_hack=false
                        indent(writer, indent)
                        writer << START.sub(/\\/u, '')
                        writer << @target
                        writer << ' '
                        writer << @content
                        writer << STOP.sub(/\\/u, '')
                end


Module: REXML::Light

Module | REXML::Light
In: | rexml/light/node.rb

Classes and Modules

Class REXML::Light::Node


Class: REXML::Light::Node

Class | REXML::Light::Node
In: | 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.

[Source]

# File 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

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.

[Source]

# File 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
=~( path )

[Source]

# File rexml/light/node.rb, line 98
                        def =~( path )
                                XPath.match( self, path )
                        end
[]( reference, ns=nil )

[Source]

# File 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
[]=( reference, ns, value=nil )

Doesn‘t handle namespaces yet

[Source]

# File 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
children()

[Source]

# File rexml/light/node.rb, line 151
                        def children
                                self
                        end
each( ) {|at(x+4 )| ...}

[Source]

# File rexml/light/node.rb, line 44
                        def each( &block )
                                size.times { |x| yield( at(x+4) ) }
                        end
has_name?( name, namespace = '' )

[Source]

# File rexml/light/node.rb, line 147
                        def has_name?( name, namespace = '' )
                                at(3) == name and namespace() == namespace
                        end
local_name()

[Source]

# File rexml/light/node.rb, line 62
                        def local_name
                                namesplit
                                @name
                        end
local_name=( name_str )

[Source]

# File rexml/light/node.rb, line 67
                        def local_name=( name_str )
                                _old_put( 1, "#@prefix:#{name_str}" )
                        end
name()

[Source]

# File rexml/light/node.rb, line 48
                        def name
                                at(2)
                        end
name=( name_str, ns=nil )

[Source]

# File 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
namespace( prefix=prefix() )

[Source]

# File rexml/light/node.rb, line 75
                        def namespace( prefix=prefix() )
                                namespace_of( self, prefix )
                        end
namespace=( namespace )

[Source]

# File 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
node_type()

[Source]

# File rexml/light/node.rb, line 133
                        def node_type
                                _old_get(0)
                        end
parent()

[Source]

# File rexml/light/node.rb, line 155
                        def parent
                                at(1)
                        end
parent=( node )

[Source]

# File rexml/light/node.rb, line 58
                        def parent=( node )
                                _old_put(1,node)
                        end
prefix( namespace=nil )

[Source]

# File rexml/light/node.rb, line 71
                        def prefix( namespace=nil )
                                prefix_of( self, namespace )
                        end
root()

[Source]

# File rexml/light/node.rb, line 142
                        def root
                                context = self
                                context = context.at(1) while context.at(1)
                        end
size()

[Source]

# File rexml/light/node.rb, line 36
                        def size
                                if PARENTS.include? @node[0]
                                        @node[-1].size
                                else
                                        0
                                end
                        end
text=( foo )

[Source]

# File rexml/light/node.rb, line 137
                        def text=( foo )
                                replace = at(4).kind_of?(String)? 1 : 0
                                self._old_put(4,replace, normalizefoo)
                        end
to_s()

[Source]

# File rexml/light/node.rb, line 159
                        def to_s

                        end


Module: REXML::Namespace

Module | REXML::Namespace
In: | 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.

[Source]

# File rexml/namespace.rb, line 41
                def fully_expanded_name
                        ns = prefix
                        return "#{ns}:#@name" if ns.size > 0
                        return @name
                end
has_name?( other, ns=nil )

Compares names optionally WITH namespaces

[Source]

# File 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
name=( name )

Sets the name and the expanded name

[Source]

# File rexml/namespace.rb, line 14
                def name=( name )
                        @expanded_name = name
                        name =~ NAMESPLIT
                        if $1
                                @prefix = $1
                        else
                                @prefix = ""
                                @namespace = ""
                        end
                        @name = $2
                end


Module: REXML::Node

Module | REXML::Node
In: | 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

[Source]

# File rexml/node.rb, line 42
                def each_recursive(&block) # :yields: node
                        self.elements.each {|node|
                                block.call(node)
                                node.each_recursive(&block)
                        }
                end
find_first_recursive() {|node| ...}

Find (and return) first subnode (recursively) for which the block evaluates to true. Returns nil if none was found.

[Source]

# File rexml/node.rb, line 51
                def find_first_recursive(&block) # :yields: node
      each_recursive {|node|
        return node if block.call(node)
      }
      return nil
    end
indent(to, ind)

[Source]

# File rexml/node.rb, line 27
                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
index_in_parent()

Returns the index that self has in its parent’s elements array, so that the following equation holds true:

  node == node.parent.elements[node.index_in_parent]

[Source]

# File rexml/node.rb, line 62
    def index_in_parent
      parent.index(self)+1
    end
next_sibling_node()

@return the next sibling (nil if unset)

[Source]

# File rexml/node.rb, line 8
                def next_sibling_node
                        return nil if @parent.nil?
                        @parent[ @parent.index(self) + 1 ]
                end
parent?()

[Source]

# File rexml/node.rb, line 36
                def parent?
                        false;
                end
previous_sibling_node()

@return the previous sibling (nil if unset)

[Source]

# File rexml/node.rb, line 14
                def previous_sibling_node
                        return nil if @parent.nil?
                        ind = @parent.index(self)
                        return nil if ind == 0
                        @parent[ ind - 1 ]
                end
to_s(indent=-1)

[Source]

# File rexml/node.rb, line 21
                def to_s indent=-1
                        rv = ""
                        write rv,indent
                        rv
                end


Class: REXML::NotationDecl

Class | REXML::NotationDecl
In: | rexml/doctype.rb
Parent: | Child

Methods

new to_s write

Public Class methods

new(name, middle, rest)

[Source]

# File rexml/doctype.rb, line 198
                def initialize name, middle, rest
                        @name = name
                        @middle = middle
                        @rest = rest
                end

Public Instance methods

to_s()

[Source]

# File rexml/doctype.rb, line 204
                def to_s
                        "<!NOTATION #@name '#@middle #@rest'>"
                end
write( output, indent=-1 )

[Source]

# File rexml/doctype.rb, line 208
                def write( output, indent=-1 )
                        output << ('   '*indent) if indent > 0
                        output << to_s
                end


Class: REXML::Output

Class | REXML::Output
In: | 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")

[Source]

# File 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

Public Instance methods

<<( content )

[Source]

# File rexml/output.rb, line 16
                def <<( content )
                        @output << (@to_utf ? self.encode(content) : content)
                end
to_s()

[Source]

# File rexml/output.rb, line 20
    def to_s
      "Output[#{encoding}]"
    end


Class: REXML::Parent

Class | REXML::Parent
In: | 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 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

[Source]

# File rexml/parent.rb, line 12
                def initialize parent=nil
                        super(parent)
                        @children = []
                end

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

[Source]

# File rexml/parent.rb, line 57
                def []( index )
                        @children[index]
                end
[]=( *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)

[Source]

# File rexml/parent.rb, line 70
                def []=( *args )
                        args[-1].parent = self
                        @children[*args[0..-2]] = args[-1]
                end
add( object )

[Source]

# File 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
children()

Alias for to_a

deep_clone()

Deeply clones this object. This creates a complete duplicate of this Parent, including all descendants.

[Source]

# File rexml/parent.rb, line 147
                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
delete( object )

[Source]

# File rexml/parent.rb, line 33
                def delete( object )
                        return unless @children.include? object
                        @children.delete object
                        object.parent = nil
                end
delete_at( index )

[Source]

# File rexml/parent.rb, line 47
                def delete_at( index )
                        @children.delete_at index
                end
delete_if( &block )

[Source]

# File rexml/parent.rb, line 43
                def delete_if( &block )
                        @children.delete_if(&block)
                end
each(&block)

[Source]

# File rexml/parent.rb, line 39
                def each(&block)
                        @children.each(&block)
                end
each_child(&block)

Alias for each

each_index( &block )

[Source]

# File rexml/parent.rb, line 51
                def each_index( &block )
                        @children.each_index(&block)
                end
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.

[Source]

# File rexml/parent.rb, line 123
                def index( child )
                        count = -1
                        @children.find { |i| count += 1 ; i.hash == child.hash }
                        count
                end
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)

[Source]

# File 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
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)

[Source]

# File 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
parent?()

[Source]

# File rexml/parent.rb, line 161
                def parent?
                        true
                end
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)

[Source]

# File rexml/parent.rb, line 138
                def replace_child( to_replace, replacement )
                        ind = @children.index( to_replace )
                        to_replace.parent = nil
                        @children[ind,0] = replacement
                        replacement.parent = self
                end
size()

@return the number of children of this parent

[Source]

# File rexml/parent.rb, line 130
                def size
                        @children.size
                end
to_a()

[Source]

# File rexml/parent.rb, line 115
                def to_a
                        @children.dup
                end
unshift( object )

[Source]

# File rexml/parent.rb, line 28
                def unshift( object )
                        object.parent = self
                        @children.unshift object
                end


Class: REXML::ParseException

Class | REXML::ParseException
In: | 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 )

[Source]

# File rexml/parseexception.rb, line 5
    def initialize( message, source=nil, parser=nil, exception=nil )
      super(message)
      @source = source
      @parser = parser
      @continued_exception = exception
    end

Public Instance methods

context()

[Source]

# File rexml/parseexception.rb, line 47
    def context
      @source.current_line
    end
line()

[Source]

# File rexml/parseexception.rb, line 42
    def line
      @source.current_line[2] if @source and defined? @source.current_line and
      @source.current_line
    end
position()

[Source]

# File rexml/parseexception.rb, line 37
    def position
      @source.current_line[0] if @source and defined? @source.current_line and
      @source.current_line
    end
to_s()

[Source]

# File 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


Module: REXML::Parsers

Module | REXML::Parsers
In: | rexml/parsers/xpathparser.rb rexml/parsers/ultralightparser.rb rexml/parsers/treeparser.rb rexml/parsers/streamparser.rb rexml/parsers/sax2parser.rb rexml/parsers/pullparser.rb rexml/parsers/lightparser.rb rexml/parsers/baseparser.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: | 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 pull stream= unnormalize unshift

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]+;)"
REFERENCE_RE | = | /#{REFERENCE}/
DOCTYPE_START | = | /\A\s*<!DOCTYPE\s/um
DOCTYPE_PATTERN | = | /\s*<!DOCTYPE\s+(.*?)(\[|>)/um
ATTRIBUTE_PATTERN | = | /\s*(#{NAME_STR})\s*=\s*(["'])(.*?)\2/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+#{NAME_STR}\s*=\s*(["']).*?\3)*)\s*(\/)?>/um
CLOSE_MATCH | = | /^\s*<\/(#{NAME_STR})\s*>/um
VERSION | = | /\bversion\s*=\s*["'](.*?)['"]/um
ENCODING | = | /\bencoding=["'](.*?)['"]/um
STANDALONE | = | /\bstandalone=["'](.*?)['"]/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+((["']).*?\4)\s*>/um
SYSTEM | = | /^\s*<!NOTATION\s+(\w[\-\w]*)\s+(SYSTEM)\s+((["']).*?\4)\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;", "'", /'/]

Attributes

source [R]

Public Class methods

new( source )

[Source]

# File rexml/parsers/baseparser.rb, line 99
      def initialize( source )
        self.stream = source
      end

Public Instance methods

add_listener( listener )

[Source]

# File rexml/parsers/baseparser.rb, line 103
      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
empty?()

Returns true if there are no more events

[Source]

# File rexml/parsers/baseparser.rb, line 144
      def empty?
        #puts "@source.empty? = #{@source.empty?}"
        #puts "@stack.empty? = #{@stack.empty?}"
        return (@source.empty? and @stack.empty?)
      end
entity( reference, entities )

[Source]

# File rexml/parsers/baseparser.rb, line 372
      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
has_next?()

Returns true if there are more events. Synonymous with !empty?

[Source]

# File rexml/parsers/baseparser.rb, line 151
      def has_next?
        return !(@source.empty? and @stack.empty?)
      end
normalize( input, entities=nil, entity_filter=nil )

Escapes all possible entities

[Source]

# File rexml/parsers/baseparser.rb, line 383
      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
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.

[Source]

# File rexml/parsers/baseparser.rb, line 167
      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()

Returns the next event. This is a PullEvent object.

[Source]

# File rexml/parsers/baseparser.rb, line 182
      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
        @source.read if @source.buffer.size<2
        if @document_status == nil
          @source.consume( /^\s*/um )
          word = @source.match( /(<[^>]*)>/um )
          word = word[1] unless word.nil?
          case word
          when COMMENT_START
            return [ :comment, @source.match( COMMENT_PATTERN, true )[1] ]
          when XMLDECL_START
            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 )
            identity = md[1]
            close = md[2]
            identity =~ IDENTITY
            name = $1
            raise REXML::ParseException("DOCTYPE is missing a name") if name.nil?
            pub_sys = $2.nil? ? nil : $2.strip
            long_name = $3.nil? ? nil : $3.strip
            uri = $4.nil? ? nil : $4.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
          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
              end
            end
            return [ :attlistdecl, element, pairs, contents ]
          when NOTATIONDECL_START
            md = nil
            if @source.match( PUBLIC )
              md = @source.match( PUBLIC, true )
            elsif @source.match( SYSTEM )
              md = @source.match( SYSTEM, true )
            else
              raise REXML::ParseException.new( "error parsing notation: no matching pattern", @source )
            end
            return [ :notationdecl, md[1], md[2], md[3] ]
          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] == ?/
              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)
              #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)
              raise REXML::ParseException.new("malformed XML: missing tag start", @source) unless md
              attrs = []
              if md[2].size > 0
                attrs = md[2].scan( ATTRIBUTE_PATTERN )
                raise REXML::ParseException.new( "error parsing attributes: [#{attrs.join ', '}], excess = \"#$'\"", @source) if $' and $'.strip.size > 0
              end

              if md[4]
                @closed = md[1]
              else
                @tags.push( md[1] )
              end
              attributes = {}
              attrs.each { |a,b,c| attributes[a] = c }
              return [ :start_element, md[1], attributes ]
            end
          else
            md = @source.match( TEXT_PATTERN, true )
            if md[0].length == 0
              #puts "EMPTY = #{empty?}"
              #puts "BUFFER = \"#{@source.buffer}\""
              @source.match( /(\s+)/, true )
            end
            #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::ParseException
          raise
        rescue Exception, NameError => error
          raise REXML::ParseException.new( "Exception parsing",
            @source, self, (error ? error : $!) )
        end
        return [ :dummy ]
      end
stream=( source )

[Source]

# File rexml/parsers/baseparser.rb, line 123
      def stream=( source )
        if source.kind_of? String
          @source = Source.new(source)
        elsif source.kind_of? IO
          @source = IOSource.new(source)
        elsif source.kind_of? Source
          @source = source
        elsif defined? StringIO and source.kind_of? StringIO
          @source = IOSource.new(source)
        else
          raise "#{source.class} is not a valid input stream.  It must be \n"+
          "either a String, IO, StringIO or Source."
        end
        @closed = nil
        @document_status = nil
        @tags = []
        @stack = []
        @entities = []
      end
unnormalize( string, entities=nil, filter=nil )

Unescapes all possible entities

[Source]

# File rexml/parsers/baseparser.rb, line 399
      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
unshift(token)

Push an event back on the head of the stream. This method has (theoretically) infinite depth.

[Source]

# File rexml/parsers/baseparser.rb, line 157
      def unshift token
        @stack.unshift(token)
      end


Class: REXML::Parsers::LightParser

Class | REXML::Parsers::LightParser
In: | rexml/parsers/lightparser.rb
Parent: | Object

Methods

add_listener new parse rewind

Public Class methods

new(stream)

[Source]

# File rexml/parsers/lightparser.rb, line 8
                        def initialize stream
                                @stream = stream
                                @parser = REXML::Parsers::BaseParser.new( stream )
                        end

Public Instance methods

add_listener( listener )

[Source]

# File rexml/parsers/lightparser.rb, line 13
      def add_listener( listener )
        @parser.add_listener( listener )
      end
parse()

[Source]

# File 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
rewind()

[Source]

# File rexml/parsers/lightparser.rb, line 17
      def rewind
        @stream.rewind
        @parser.stream = @stream
      end


Class: REXML::Parsers::PullEvent

Class | REXML::Parsers::PullEvent
In: | 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.

[Source]

# File rexml/parsers/pullparser.rb, line 93
      def initialize(arg)
        @contents = arg
      end

Public Instance methods

[]( start, endd=nil)

[Source]

# File rexml/parsers/pullparser.rb, line 97
      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
attlistdecl?()

Content: [ String text ]

[Source]

# File rexml/parsers/pullparser.rb, line 146
      def attlistdecl?
        @contents[0] == :attlistdecl
      end
cdata?()

Content: [ String text ]

[Source]

# File rexml/parsers/pullparser.rb, line 177
      def cdata?
        @contents[0] == :cdata
      end
comment?()

Content: [ String text ]

[Source]

# File rexml/parsers/pullparser.rb, line 136
      def comment?
        @contents[0] == :comment
      end
doctype?()

Content: [ String name, String pub_sys, String long_name, String uri ]

[Source]

# File rexml/parsers/pullparser.rb, line 141
      def doctype?
        @contents[0] == :start_doctype
      end
elementdecl?()

Content: [ String text ]

[Source]

# File rexml/parsers/pullparser.rb, line 151
      def elementdecl?
        @contents[0] == :elementdecl
      end
end_element?()

Content: [ String tag_name ]

[Source]

# File rexml/parsers/pullparser.rb, line 121
      def end_element?
        @contents[0] == :end_element
      end
entity?()

Content: [ String text ]

[Source]

# File rexml/parsers/pullparser.rb, line 172
      def entity?
        @contents[0] == :entity
      end
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 ]

[Source]

# File rexml/parsers/pullparser.rb, line 162
      def entitydecl?
        @contents[0] == :entitydecl
      end
error?()

[Source]

# File rexml/parsers/pullparser.rb, line 186
      def error?
        @contents[0] == :error
      end
event_type()

[Source]

# File rexml/parsers/pullparser.rb, line 111
      def event_type
        @contents[0]
      end
inspect()

[Source]

# File rexml/parsers/pullparser.rb, line 190
      def inspect
        @contents[0].to_s + ": " + @contents[1..-1].inspect
      end
instruction?()

Content: [ String text ]

[Source]

# File rexml/parsers/pullparser.rb, line 131
      def instruction?
        @contents[0] == :processing_instruction
      end
notationdecl?()

Content: [ String text ]

[Source]

# File rexml/parsers/pullparser.rb, line 167
      def notationdecl?
        @contents[0] == :notationdecl
      end
start_element?()

Content: [ String tag_name, Hash attributes ]

[Source]

# File rexml/parsers/pullparser.rb, line 116
      def start_element?
        @contents[0] == :start_element
      end
text?()

Content: [ String raw_text, String unnormalized_text ]

[Source]

# File rexml/parsers/pullparser.rb, line 126
      def text?
        @contents[0] == :text
      end
xmldecl?()

Content: [ String version, String encoding, String standalone ]

[Source]

# File rexml/parsers/pullparser.rb, line 182
      def xmldecl?
        @contents[0] == :xmldecl
      end


Class: REXML::Parsers::PullParser

Class | REXML::Parsers::PullParser
In: | 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)

[Source]

# File rexml/parsers/pullparser.rb, line 36
      def initialize stream
        @entities = {}
        @listeners = nil
        @parser = BaseParser.new( stream )
        @my_stack = []
      end

Public Instance methods

add_listener( listener )

[Source]

# File rexml/parsers/pullparser.rb, line 43
      def add_listener( listener )
        @listeners = [] unless @listeners
        @listeners << listener
      end
each() {|self.pull| ...}

[Source]

# File rexml/parsers/pullparser.rb, line 48
      def each
        while has_next?
          yield self.pull
        end
      end
peek(depth=0)

[Source]

# File rexml/parsers/pullparser.rb, line 54
      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()

[Source]

# File rexml/parsers/pullparser.rb, line 64
      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(token)

[Source]

# File rexml/parsers/pullparser.rb, line 79
      def unshift token
        @my_stack.unshift token
      end


Class: REXML::Parsers::SAX2Parser

Class | REXML::Parsers::SAX2Parser
In: | rexml/parsers/sax2parser.rb
Parent: | Object

SAX2Parser

Methods

add_listener deafen listen new parse

Public Class methods

new(source)

[Source]

# File rexml/parsers/sax2parser.rb, line 10
                        def initialize source
                                @parser = BaseParser.new(source)
                                @listeners = []
                                @procs = []
                                @namespace_stack = []
                                @has_listeners = false
                                @tag_stack = []
        @entities = {}
                        end

Public Instance methods

add_listener( listener )

[Source]

# File rexml/parsers/sax2parser.rb, line 20
      def add_listener( listener )
        @parser.add_listener( listener )
      end
deafen( listener=nil, &blok )

[Source]

# File rexml/parsers/sax2parser.rb, line 72
                        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
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.

[Source]

# File rexml/parsers/sax2parser.rb, line 54
                        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
parse()

[Source]

# File rexml/parsers/sax2parser.rb, line 81
                        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 :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, :doctype, :attlistdecl,
                                                :elementdecl, :cdata, :notationdecl, :xmldecl
                                                handle( *event )
                                        end
          handle( :progress, @parser.source.position )
                                end
                        end


Class: REXML::Parsers::StreamParser

Class | REXML::Parsers::StreamParser
In: | rexml/parsers/streamparser.rb
Parent: | Object

Methods

add_listener new parse

Public Class methods

new(source, listener)

[Source]

# File rexml/parsers/streamparser.rb, line 4
                        def initialize source, listener
                                @listener = listener
                                @parser = BaseParser.new( source )
                        end

Public Instance methods

add_listener( listener )

[Source]

# File rexml/parsers/streamparser.rb, line 9
      def add_listener( listener )
        @parser.add_listener( listener )
      end
parse()

[Source]

# File 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 :comment, :attlistdecl, :notationdecl, :elementdecl,
            :entitydecl, :cdata, :xmldecl, :attlistdecl
                                                @listener.send( event[0].to_s, *event[1..-1] )
                                        end
                                end
                        end


Class: REXML::Parsers::TreeParser

Class | REXML::Parsers::TreeParser
In: | rexml/parsers/treeparser.rb
Parent: | Object

Methods

add_listener new parse

Public Class methods

new( source, build_context = Document.new )

[Source]

# File rexml/parsers/treeparser.rb, line 6
      def initialize( source, build_context = Document.new )
        @build_context = build_context
        @parser = Parsers::BaseParser.new( source )
      end

Public Instance methods

add_listener( listener )

[Source]

# File rexml/parsers/treeparser.rb, line 11
      def add_listener( listener )
        @parser.add_listener( listener )
      end
parse()

[Source]

# File rexml/parsers/treeparser.rb, line 15
      def parse
        tag_stack = []
        in_doctype = false
        entities = nil
        begin
          while true
            event = @parser.pull
            case event[0]
            when :end_document
              return
            when :start_element
              tag_stack.push(event[1])
              # find the observers for namespaces
              @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 (
                    event[1].strip.size==0 and
                    @build_context.ignore_whitespace_nodes
                  )
                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
          raise ParseException.new( $!.message, @parser.source, @parser, $! )
        end
      end


Class: REXML::Parsers::UltraLightParser

Class | REXML::Parsers::UltraLightParser
In: | rexml/parsers/ultralightparser.rb
Parent: | Object

Methods

add_listener new parse rewind

Public Class methods

new(stream)

[Source]

# File rexml/parsers/ultralightparser.rb, line 7
                        def initialize stream
                                @stream = stream
                                @parser = REXML::Parsers::BaseParser.new( stream )
                        end

Public Instance methods

add_listener( listener )

[Source]

# File rexml/parsers/ultralightparser.rb, line 12
      def add_listener( listener )
        @parser.add_listener( listener )
      end
parse()

[Source]

# File 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
rewind()

[Source]

# File rexml/parsers/ultralightparser.rb, line 16
      def rewind
        @stream.rewind
        @parser.stream = @stream
      end


Class: REXML::Parsers::XPathParser

Class | REXML::Parsers::XPathParser
In: | 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 )

[Source]

# File 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( path )

[Source]

# File 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
namespaces=( namespaces )

[Source]

# File rexml/parsers/xpathparser.rb, line 14
      def namespaces=( namespaces )
        Functions::namespace_context = namespaces
        @namespaces = namespaces
      end
parse(path)

[Source]

# File 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(path)

[Source]

# File rexml/parsers/xpathparser.rb, line 27
      def predicate path
        parsed = []
        Predicate( "[#{path}]", parsed )
        parsed
      end
predicate_to_string( path ) {|path| ...}

[Source]

# File 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


Class: REXML::QuickPath

Class | REXML::QuickPath
In: | 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 )

[Source]

# File rexml/quickpath.rb, line 206
                def QuickPath::attribute( name )
                        return Functions.node.attributes[name] if Functions.node.kind_of? Element
                end
axe( elements, axe_name, rest )

[Source]

# File 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
each(element, path, namespaces=EMPTY_HASH, &block)

[Source]

# File rexml/quickpath.rb, line 15
                def QuickPath::each element, path, namespaces=EMPTY_HASH, &block
                        path = "*" unless path
                        match(element, path, namespaces).each( &block )
                end
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

[Source]

# File 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
first(element, path, namespaces=EMPTY_HASH)

[Source]

# File rexml/quickpath.rb, line 11
                def QuickPath::first element, path, namespaces=EMPTY_HASH
                        match(element, path, namespaces)[0]
                end
function( elements, fname, rest )

[Source]

# File 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
match(element, path, namespaces=EMPTY_HASH)

[Source]

# File 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
method_missing( id, *args )

[Source]

# File 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
name()

[Source]

# File rexml/quickpath.rb, line 210
                def QuickPath::name()
                        return Functions.node.name if Functions.node.kind_of? Element
                end
parse_args( element, string )

[Source]

# File 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
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].

[Source]

# File 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


Module: REXML::SAX2Listener

Module | REXML::SAX2Listener
In: | 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.

[Source]

# File rexml/sax2listener.rb, line 52
                def attlistdecl(element, pairs, contents)
                end
cdata(content)

Called when <![CDATA[ … ]]> is encountered in a document. @p content "…"

[Source]

# File rexml/sax2listener.rb, line 80
                def cdata content
                end
characters(text)

[Source]

# File rexml/sax2listener.rb, line 35
                def characters text
                end
comment(comment)

Called when a comment is encountered. @p comment The content of the comment

[Source]

# File rexml/sax2listener.rb, line 91
                def comment comment
                end
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"

[Source]

# File rexml/sax2listener.rb, line 45
                def doctype name, pub_sys, long_name, uri
                end
elementdecl(content)

<!ELEMENT …>

[Source]

# File rexml/sax2listener.rb, line 55
                def elementdecl content
                end
end_document()

[Source]

# File rexml/sax2listener.rb, line 25
                def end_document
                end
end_element(uri, localname, qname)

[Source]

# File rexml/sax2listener.rb, line 33
                def end_element uri, localname, qname
                end
end_prefix_mapping(prefix)

[Source]

# File rexml/sax2listener.rb, line 29
                def end_prefix_mapping prefix
                end
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"]

[Source]

# File rexml/sax2listener.rb, line 73
                def entitydecl content
                end
notationdecl(content)

<!NOTATION …>

[Source]

# File rexml/sax2listener.rb, line 76
                def notationdecl content
                end
processing_instruction(target, data)

[Source]

# File rexml/sax2listener.rb, line 37
                def processing_instruction target, data
                end
progress(position)

[Source]

# File rexml/sax2listener.rb, line 93
    def progress position
    end
start_document()

[Source]

# File rexml/sax2listener.rb, line 23
                def start_document
                end
start_element(uri, localname, qname, attributes)

[Source]

# File rexml/sax2listener.rb, line 31
                def start_element uri, localname, qname, attributes
                end
start_prefix_mapping(prefix, uri)

[Source]

# File rexml/sax2listener.rb, line 27
                def start_prefix_mapping prefix, uri
                end
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

[Source]

# File rexml/sax2listener.rb, line 87
                def xmldecl version, encoding, standalone
                end


Class: REXML::Source

Class | REXML::Source
In: | 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)

Constructor @param arg must be a String, and should be a valid XML document

[Source]

# File rexml/source.rb, line 31
                def initialize(arg)
                        @orig = @buffer = arg
                        self.encoding = check_encoding( @buffer )
                        @line = 0
                end

Public Instance methods

consume( pattern )

[Source]

# File rexml/source.rb, line 76
                def consume( pattern )
                        @buffer = $' if pattern.match( @buffer )
                end
current_line()

@return the current line in the source

[Source]

# File rexml/source.rb, line 106
                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
empty?()

@return true if the Source is exhausted

[Source]

# File rexml/source.rb, line 97
                def empty?
                        @buffer == ""
                end
encoding=(enc)

Inherited from Encoding Overridden to support optimized en/decoding

[Source]

# File rexml/source.rb, line 39
                def encoding=(enc)
                        super
                        @line_break = encode( '>' )
                        if enc != UTF_8
                                @buffer = decode(@buffer)
                                @to_utf = true
                        else
                                @to_utf = false
                        end
                end
match(pattern, cons=false)

[Source]

# File rexml/source.rb, line 90
                def match(pattern, cons=false)
                        md = pattern.match(@buffer)
                        @buffer = $' if cons and md
                        return md
                end
match_to( char, pattern )

[Source]

# File rexml/source.rb, line 80
                def match_to( char, pattern )
                        return pattern.match(@buffer)
                end
match_to_consume( char, pattern )

[Source]

# File rexml/source.rb, line 84
                def match_to_consume( char, pattern )
                        md = pattern.match(@buffer)
                        @buffer = $'
                        return md
                end
position()

[Source]

# File rexml/source.rb, line 101
    def position
      @orig.index( @buffer )
    end
read()

[Source]

# File rexml/source.rb, line 73
                def read
                end
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.

[Source]

# File rexml/source.rb, line 66
                def scan(pattern, cons=false)
                        return nil if @buffer.nil?
                        rv = @buffer.scan(pattern)
                        @buffer = $' if cons and rv.size>0
                        rv
                end


Class: REXML::SourceFactory

Class | REXML::SourceFactory
In: | 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

[Source]

# File rexml/source.rb, line 9
                def SourceFactory::create_from arg#, slurp=true
                        if arg.kind_of? String
                                source = Source.new(arg)
                        elsif arg.kind_of? IO
                                source = IOSource.new(arg)
                        end
                        source
                end


Module: REXML::StreamListener

Module | REXML::StreamListener
In: | 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 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.

[Source]

# File rexml/streamlistener.rb, line 47
                def attlistdecl element_name, attributes, raw_content
                end
cdata(content)

Called when <![CDATA[ … ]]> is encountered in a document. @p content "…"

[Source]

# File rexml/streamlistener.rb, line 79
                def cdata content
                end
comment(comment)

Called when a comment is encountered. @p comment The content of the comment

[Source]

# File rexml/streamlistener.rb, line 32
                def comment comment
                end
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"

[Source]

# File rexml/streamlistener.rb, line 40
                def doctype name, pub_sys, long_name, uri
                end
elementdecl(content)

<!ELEMENT …>

[Source]

# File rexml/streamlistener.rb, line 50
                def elementdecl content
                end
entity(content)

Called when %foo; is encountered in a doctype declaration. @p content "foo"

[Source]

# File rexml/streamlistener.rb, line 75
                def entity content
                end
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"]

[Source]

# File rexml/streamlistener.rb, line 68
                def entitydecl content
                end
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’"

[Source]

# File rexml/streamlistener.rb, line 28
                def instruction name, instruction
                end
notationdecl(content)

<!NOTATION …>

[Source]

# File rexml/streamlistener.rb, line 71
                def notationdecl content
                end
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

[Source]

# File rexml/streamlistener.rb, line 18
                def tag_end name
                end
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"]])

[Source]

# File rexml/streamlistener.rb, line 13
                def tag_start name, attrs
                end
text(text)

Called when text is encountered in the document @p text the text content.

[Source]

# File rexml/streamlistener.rb, line 22
                def text text
                end
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

[Source]

# File rexml/streamlistener.rb, line 86
                def xmldecl version, encoding, standalone
                end


Class: REXML::SyncEnumerator

Class | REXML::SyncEnumerator
In: | 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.

[Source]

# File rexml/syncenumerator.rb, line 7
    def initialize(*enums)
      @gens = enums
      @biggest = @gens[0]
      @gens.each {|x| @biggest = x if x.size > @biggest.size }
    end

Public Instance methods

each() {|*a[1..-1]| ...}

Enumerates rows of the Enumerable objects.

[Source]

# File rexml/syncenumerator.rb, line 26
    def each
      @biggest.zip( *@gens ) {|a|
        yield(*a[1..-1])
      }
      self
    end
length()

Returns the number of enumerated Enumerable objects, i.e. the size of each row.

[Source]

# File rexml/syncenumerator.rb, line 21
    def length
      @gens.length
    end
size()

Returns the number of enumerated Enumerable objects, i.e. the size of each row.

[Source]

# File rexml/syncenumerator.rb, line 15
    def size
      @gens.size
    end


Class: REXML::Text

Class | REXML::Text
In: | 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.

  Text.new( "<&", false, nil, false ) #-> "&lt;&amp;"
  Text.new( "<&", false, nil, true )  #-> IllegalArgumentException
  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

[Source]

# File rexml/text.rb, line 57
    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
normalize( input, doctype=nil, entity_filter=nil )

Escapes all possible entities

[Source]

# File rexml/text.rb, line 284
    def Text::normalize( input, doctype=nil, entity_filter=nil )
      copy = input.clone
      # Doing it like this rather than in a loop improves the speed
      if doctype
        copy = copy.gsub( EREFERENCE, '&amp;' )
        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
        copy = copy.gsub( EREFERENCE, '&amp;' )
        DocType::DEFAULT_ENTITIES.each_value do |entity|
          copy = copy.gsub(entity.value, "&#{entity.name};" )
        end
      end
      copy
    end
read_with_substitution( input, illegal=nil )

Reads text, substituting entities

[Source]

# File rexml/text.rb, line 258
    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
unnormalize( string, doctype=nil, filter=nil, illegal=nil )

Unescapes all possible entities

[Source]

# File rexml/text.rb, line 304
    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

Public Instance methods

<<( to_append )

Appends text to this text node. The text is appended in the raw mode of this text node.

[Source]

# File rexml/text.rb, line 109
    def <<( to_append )
      @string << to_append.gsub( /\r\n?/, "\n" )
    end
<=>( other )

other a String or a Text returns the result of (to_s <=> arg.to_s)

[Source]

# File rexml/text.rb, line 116
    def <=>( other )
      to_s() <=> other.to_s
    end
clone()

[Source]

# File rexml/text.rb, line 102
    def clone
      return Text.new(self)
    end
empty?()

[Source]

# File rexml/text.rb, line 97
    def empty?
      @string.size==0
    end
indent_text(string, level=1, style="\t", indentfirstline=true)

[Source]

# File rexml/text.rb, line 199
     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
inspect()

[Source]

# File rexml/text.rb, line 147
    def inspect
      @string.inspect
    end
node_type()

[Source]

# File rexml/text.rb, line 93
    def node_type
      :text
    end
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"

[Source]

# File rexml/text.rb, line 134
    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
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.string   #-> "< & sean russell"
  t = Text.new( "< & &s; russell", false, nil, false )
  t.string   #-> "< & sean russell"
  u = Text.new( "sean russell", false, nil, true )
  u.string   #-> "sean russell"

[Source]

# File rexml/text.rb, line 164
    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=( 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>

[Source]

# File rexml/text.rb, line 192
    def value=( val )
      @string = val.gsub( /\r\n?/, "\n" )
      @unnormalized = nil
      @normalized = nil
      @raw = false
    end
wrap(string, width, addnewline=false)

[Source]

# File rexml/text.rb, line 174
     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
write( writer, indent=-1, transitive=false, ie_hack=false )

[Source]

# File rexml/text.rb, line 211
    def write( writer, indent=-1, transitive=false, ie_hack=false )
      s = to_s()
      if not (@parent and @parent.whitespace) then
        s = wrap(s, 60, false) if @parent and @parent.context[:wordwrap] == :all
        if @parent and not @parent.context[:indentstyle].nil? and indent > 0 and s.count("\n") > 0
          s = indent_text(s, indent, @parent.context[:indentstyle], false)
        end
        s.squeeze!(" \n\t") if @parent and !@parent.whitespace
      end
      writer << s
    end
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

[Source]

# File rexml/text.rb, line 245
    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
xpath()

FIXME This probably won’t work properly

[Source]

# File rexml/text.rb, line 225
    def xpath
      path = @parent.xpath
      path += "/text()"
      return path
    end


Module: REXML::Validation

Module | REXML::Validation
In: | rexml/validation/validationexception.rb rexml/validation/validation.rb 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: | rexml/validation/relaxng.rb
Parent: | State

Methods

<< expected inspect matches? new next reset

Public Class methods

new(context)

[Source]

# File rexml/validation/relaxng.rb, line 363
      def initialize context
        super
        @choices = []
      end

Public Instance methods

<<( event )

[Source]

# File rexml/validation/relaxng.rb, line 374
      def <<( event )
        add_event_to_arry( @choices, event )
      end
expected()

[Source]

# File 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()

[Source]

# File rexml/validation/relaxng.rb, line 424
      def inspect
        "< #{to_s} #{@choices.collect{|e| e.collect{|f|f.to_s}.join(', ')}.join(' or ')} >"
      end
matches?( event )

[Source]

# File 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
next( event )

[Source]

# File 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
reset()

[Source]

# File rexml/validation/relaxng.rb, line 368
      def reset
        super
        @events = []
        @choices.each { |c| c.each { |s| s.reset if s.kind_of? State } }
      end


Class: REXML::Validation::Event

Class | REXML::Validation::Event
In: | 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 )

[Source]

# File rexml/validation/validation.rb, line 80
      def initialize(event_type, event_arg=nil )
        @event_type = event_type
        @event_arg = event_arg
      end

Public Instance methods

==( other )

[Source]

# File 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
done?()

[Source]

# File rexml/validation/validation.rb, line 88
      def done?
        @done
      end
inspect()

[Source]

# File rexml/validation/validation.rb, line 150
      def inspect
        "#{@event_type.inspect}( #@event_arg )"
      end
matches?( event )

[Source]

# File 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
single?()

[Source]

# File rexml/validation/validation.rb, line 92
      def single?
        return (@event_type != :start_element and @event_type != :start_attribute)
      end
to_s()

[Source]

# File rexml/validation/validation.rb, line 146
      def to_s
        inspect
      end


Class: REXML::Validation::Interleave

Class | REXML::Validation::Interleave
In: | rexml/validation/relaxng.rb
Parent: | Choice

Methods

expected inspect matches? new next next_current reset

Public Class methods

new(context)

[Source]

# File rexml/validation/relaxng.rb, line 449
      def initialize context
        super
        @choice = 0
      end

Public Instance methods

expected()

[Source]

# File 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()

[Source]

# File rexml/validation/relaxng.rb, line 542
      def inspect
        "< #{to_s} #{@choices.collect{|e| e.collect{|f|f.to_s}.join(', ')}.join(' and ')} >"
      end
matches?( event )

[Source]

# File 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
next( event )

[Source]

# File 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
next_current( event )

[Source]

# File 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
reset()

[Source]

# File rexml/validation/relaxng.rb, line 454
      def reset
        @choice = 0
      end


Class: REXML::Validation::OneOrMore

Class | REXML::Validation::OneOrMore
In: | rexml/validation/relaxng.rb
Parent: | State

Methods

expected matches? new next reset

Public Class methods

new(context)

[Source]

# File rexml/validation/relaxng.rb, line 316
      def initialize context
        super
        @ord = 0
      end

Public Instance methods

expected()

[Source]

# File 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
matches?( event )

[Source]

# File rexml/validation/relaxng.rb, line 347
      def matches?( event )
        @events[@current].matches?(event) ||
        (@current == 0 and @ord > 0 and @previous[-1].matches?(event))
      end
next( event )

[Source]

# File 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
reset()

[Source]

# File rexml/validation/relaxng.rb, line 321
      def reset
        super
        @ord = 0
      end


Class: REXML::Validation::Optional

Class | REXML::Validation::Optional
In: | rexml/validation/relaxng.rb
Parent: | State

Methods

expected matches? next

Public Instance methods

expected()

[Source]

# File rexml/validation/relaxng.rb, line 279
      def expected
        return [ @prior.expected, @events[0] ].flatten if @current == 0
        return [@events[@current]]
      end
matches?(event)

[Source]

# File rexml/validation/relaxng.rb, line 274
      def matches?(event)
        @events[@current].matches?(event) ||
        (@current == 0 and @previous[-1].matches?(event))
      end
next( event )

[Source]

# File 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


Class: REXML::Validation::Ref

Class | REXML::Validation::Ref
In: | rexml/validation/relaxng.rb
Parent: | Object

Methods

inspect new to_s

Public Class methods

new(value)

[Source]

# File rexml/validation/relaxng.rb, line 548
      def initialize value
        @value = value
      end

Public Instance methods

inspect()

[Source]

# File rexml/validation/relaxng.rb, line 554
      def inspect
        "{#{to_s}}"
      end
to_s()

[Source]

# File rexml/validation/relaxng.rb, line 551
      def to_s
        @value
      end


Class: REXML::Validation::RelaxNG

Class | REXML::Validation::RelaxNG
In: | 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

[Source]

# File 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

Public Instance methods

receive(event)

[Source]

# File rexml/validation/relaxng.rb, line 121
      def receive event
        validate( event )
      end


Class: REXML::Validation::Sequence

Class | REXML::Validation::Sequence
In: | rexml/validation/relaxng.rb
Parent: | State

Methods

matches?

Public Instance methods

matches?(event)

[Source]

# File rexml/validation/relaxng.rb, line 257
      def matches?(event)
        @events[@current].matches?( event )
      end


Class: REXML::Validation::State

Class | REXML::Validation::State
In: | rexml/validation/relaxng.rb
Parent: | Object

Methods

<< expected inspect new next previous= reset to_s

Public Class methods

new( context )

[Source]

# File rexml/validation/relaxng.rb, line 127
      def initialize( context )
        @previous = []
        @events = []
        @current = 0
        @count = context.count += 1
        @references = context.references
        @value = false
      end

Public Instance methods

<<( event )

[Source]

# File rexml/validation/relaxng.rb, line 196
      def <<( event )
        add_event_to_arry( @events, event )
      end
expected()

[Source]

# File rexml/validation/relaxng.rb, line 192
      def expected
        return [@events[@current]]
      end
inspect()

[Source]

# File 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
next( event )

[Source]

# File 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
previous=( previous )

[Source]

# File rexml/validation/relaxng.rb, line 142
      def previous=( previous )
        @previous << previous
      end
reset()

[Source]

# File 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
to_s()

[Source]

# File rexml/validation/relaxng.rb, line 177
      def to_s
        # Abbreviated:
        self.class.name =~ /(?:::)(\w)\w+$/
        # Full:
        #self.class.name =~ /(?:::)(\w+)$/
        "#$1.#@count"
      end


Class: REXML::Validation::ValidationException

Class | REXML::Validation::ValidationException
In: | rexml/validation/validationexception.rb
Parent: | RuntimeError

Methods

new

Public Class methods

new(msg)

[Source]

# File rexml/validation/validationexception.rb, line 4
      def initialize msg
        super
      end


Module: REXML::Validation::Validator

Module | REXML::Validation::Validator
In: | rexml/validation/validation.rb

Methods

dump reset validate

Constants

NILEVENT = [ nil ]

Public Instance methods

dump()

[Source]

# File rexml/validation/validation.rb, line 14
      def dump
        puts @root.inspect
      end
reset()

[Source]

# File rexml/validation/validation.rb, line 7
      def reset
        @current = @root
        @root.reset
        @root.previous = true
        @attr_stack = []
        self
      end
validate( event )

[Source]

# File 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


Class: REXML::Validation::ZeroOrMore

Class | REXML::Validation::ZeroOrMore
In: | rexml/validation/relaxng.rb
Parent: | Optional

Methods

expected next

Public Instance methods

expected()

[Source]

# File rexml/validation/relaxng.rb, line 308
      def expected
        return [ @prior.expected, @events[0] ].flatten if @current == 0
        return [@events[@current]]
      end
next( event )

[Source]

# File 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


Class: REXML::XMLDecl

Class | REXML::XMLDecl
In: | 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]

Public Class methods

default()

[Source]

# File rexml/xmldecl.rb, line 83
    def XMLDecl.default
      rv = XMLDecl.new( "1.0" )
      rv.nowrite
      rv
    end
new(version=DEFAULT_VERSION, encoding=nil, standalone=nil)

[Source]

# File 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

Public Instance methods

==( other )

[Source]

# File rexml/xmldecl.rb, line 52
                def ==( other )
                  other.kind_of?(XMLDecl) and
                  other.version == @version and
                  other.encoding == self.encoding and
                  other.standalone == @standalone
                end
clone()

[Source]

# File rexml/xmldecl.rb, line 36
                def clone
                        XMLDecl.new(self)
                end
dowrite()

[Source]

# File rexml/xmldecl.rb, line 93
    def dowrite
      @writethis = true
    end
encoding=( enc )

[Source]

# File rexml/xmldecl.rb, line 72
    def encoding=( enc )
      if enc.nil?
        self.old_enc = "UTF-8"
        @writeencoding = false
      else
        self.old_enc = enc
        @writeencoding = true
      end
      self.dowrite
    end
inspect()

[Source]

# File rexml/xmldecl.rb, line 97
    def inspect
      START.sub(/\\/u, '') + " ... " + STOP.sub(/\\/u, '')
    end
node_type()

[Source]

# File rexml/xmldecl.rb, line 65
                def node_type
                        :xmldecl
                end
nowrite()

[Source]

# File rexml/xmldecl.rb, line 89
    def nowrite
      @writethis = false
    end
write(writer, indent=-1, transitive=false, ie_hack=false)

[Source]

# File rexml/xmldecl.rb, line 40
                def write writer, indent=-1, transitive=false, ie_hack=false
      return nil unless @writethis or writer.kind_of? Output
                        indent( writer, indent )
                        writer << START.sub(/\\/u, '')
      if writer.kind_of? Output
        writer << " #{content writer.encoding}"
      else
        writer << " #{content encoding}"
      end
                        writer << STOP.sub(/\\/u, '')
                end
xmldecl(version, encoding, standalone)

[Source]

# File rexml/xmldecl.rb, line 59
                def xmldecl version, encoding, standalone
                        @version = version
                        self.encoding = encoding
                        @standalone = standalone
                end


Module: REXML::XMLTokens

Module | REXML::XMLTokens
In: | 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: | 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={})

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| ... }

[Source]

# File rexml/xpath.rb, line 45
                def XPath::each element, path=nil, namespaces={}, variables={}, &block
      raise "The namespaces argument, if supplied, must be a hash object." unless 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
first(element, path=nil, namespaces={})

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" } )

[Source]

# File rexml/xpath.rb, line 22
    def XPath::first element, path=nil, namespaces={}, variables={}
      raise "The namespaces argument, if supplied, must be a hash object." unless 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
match(element, path=nil, namespaces={})

Returns an array of nodes matching a given XPath.

[Source]

# File rexml/xpath.rb, line 57
                def XPath::match element, path=nil, namespaces={}, 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


Class: REXML::XPathParser

Class | REXML::XPathParser
In: | 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( )

[Source]

# File rexml/xpath_parser.rb, line 35
    def initialize( )
      @parser = REXML::Parsers::XPathParser.new
      @namespaces = {}
      @variables = {}
    end

Public Instance methods

[]=( variable_name, value )

[Source]

# File rexml/xpath_parser.rb, line 72
    def []=( variable_name, value )
      @variables[ variable_name ] = value
    end
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!

[Source]

# File rexml/xpath_parser.rb, line 81
    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
get_first(path, nodeset)

[Source]

# File rexml/xpath_parser.rb, line 59
    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
match( path_stack, nodeset )

[Source]

# File rexml/xpath_parser.rb, line 122
    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
namespaces=( namespaces={} )

[Source]

# File rexml/xpath_parser.rb, line 41
    def namespaces=( namespaces={} )
      Functions::namespace_context = namespaces
      @namespaces = namespaces
    end
parse(path, nodeset)

[Source]

# File rexml/xpath_parser.rb, line 51
    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
predicate(path, nodeset)

[Source]

# File rexml/xpath_parser.rb, line 67
    def predicate path, nodeset
      path_stack = @parser.parse( path )
      expr( path_stack, nodeset )
    end
variables=( vars={} )

[Source]

# File rexml/xpath_parser.rb, line 46
    def variables=( vars={} )
      Functions::variables = vars
      @variables = vars
    end


Class: Symbol

Class | Symbol
In: | rexml/xpath_parser.rb
Parent: | Object

Methods

dclone

Public Instance methods

dclone()

[Source]

# File rexml/xpath_parser.rb, line 13
  def dclone
    self
  end


File: attlistdecl.rb

attlistdecl.rb

Path: | rexml/attlistdecl.rb
Last Update: | Tue Jun 10 11:31:05 AUS Eastern Standard Time 2003

vim:ts=2 sw=2 noexpandtab:

Required files

rexml/child rexml/source


File: attribute.rb

attribute.rb

Path: | rexml/attribute.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

rexml/namespace rexml/text


File: cdata.rb

cdata.rb

Path: | rexml/cdata.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

rexml/text


File: child.rb

child.rb

Path: | rexml/child.rb
Last Update: | Tue Jun 10 11:31:04 AUS Eastern Standard Time 2003

Required files

rexml/node


File: comment.rb

comment.rb

Path: | rexml/comment.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

rexml/child


File: doctype.rb

doctype.rb

Path: | rexml/doctype.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

rexml/parent rexml/parseexception rexml/namespace rexml/entity rexml/attlistdecl rexml/xmltokens


File: document.rb

document.rb

Path: | rexml/document.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

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: attlistdecl.rb

attlistdecl.rb

Path: | rexml/dtd/attlistdecl.rb
Last Update: | Tue Jun 10 11:31:07 AUS Eastern Standard Time 2003

Required files

rexml/child


File: dtd.rb

dtd.rb

Path: | rexml/dtd/dtd.rb
Last Update: | Tue Jun 10 11:31:07 AUS Eastern Standard Time 2003

Required files

rexml/dtd/elementdecl rexml/dtd/entitydecl rexml/comment rexml/dtd/notationdecl rexml/dtd/attlistdecl rexml/parent


File: elementdecl.rb

elementdecl.rb

Path: | rexml/dtd/elementdecl.rb
Last Update: | Tue Jun 10 11:31:07 AUS Eastern Standard Time 2003

Required files

rexml/child


File: entitydecl.rb

entitydecl.rb

Path: | rexml/dtd/entitydecl.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

rexml/child


File: notationdecl.rb

notationdecl.rb

Path: | rexml/dtd/notationdecl.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

rexml/child


File: element.rb

element.rb

Path: | rexml/element.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

rexml/parent rexml/namespace rexml/attribute rexml/cdata rexml/xpath rexml/parseexception


File: encoding.rb

encoding.rb

Path: | rexml/encoding.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

-*- 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: CP-1252.rb

CP-1252.rb

Path: | rexml/encodings/CP-1252.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

This class was contributed by Mikko Tiihonen mikko DOT tiihonen AT hut DOT fi


File: EUC-JP.rb

EUC-JP.rb

Path: | rexml/encodings/EUC-JP.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

uconv


File: ICONV.rb

ICONV.rb

Path: | rexml/encodings/ICONV.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

iconv


File: ISO-8859-1.rb

ISO-8859-1.rb

Path: | rexml/encodings/ISO-8859-1.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

rexml/encodings/US-ASCII


File: ISO-8859-15.rb

ISO-8859-15.rb

Path: | rexml/encodings/ISO-8859-15.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

This class was contributed by Mikko Tiihonen mikko DOT tiihonen AT hut DOT fi


File: SHIFT-JIS.rb

SHIFT-JIS.rb

Path: | rexml/encodings/SHIFT-JIS.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

uconv


File: SHIFT_JIS.rb

SHIFT_JIS.rb

Path: | rexml/encodings/SHIFT_JIS.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005


File: UNILE.rb

UNILE.rb

Path: | rexml/encodings/UNILE.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005


File: US-ASCII.rb

US-ASCII.rb

Path: | rexml/encodings/US-ASCII.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005


File: UTF-16.rb

UTF-16.rb

Path: | rexml/encodings/UTF-16.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005


File: UTF-8.rb

UTF-8.rb

Path: | rexml/encodings/UTF-8.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005


File: entity.rb

entity.rb

Path: | rexml/entity.rb
Last Update: | Tue Jun 10 11:31:05 AUS Eastern Standard Time 2003

Required files

rexml/child rexml/source rexml/xmltokens


File: functions.rb

functions.rb

Path: | rexml/functions.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005


File: instruction.rb

instruction.rb

Path: | rexml/instruction.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

rexml/child rexml/source


File: node.rb

node.rb

Path: | rexml/light/node.rb
Last Update: | Tue Dec 09 12:41:33 AUS Eastern Daylight Time 2003

Required files

rexml/xmltokens rexml/light/node


File: namespace.rb

namespace.rb

Path: | rexml/namespace.rb
Last Update: | Tue Jun 10 11:31:02 AUS Eastern Standard Time 2003

Required files

rexml/xmltokens


File: node.rb

node.rb

Path: | rexml/node.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

rexml/parseexception


File: output.rb

output.rb

Path: | rexml/output.rb
Last Update: | Tue Dec 09 12:41:33 AUS Eastern Daylight Time 2003

Required files

rexml/encoding


File: parent.rb

parent.rb

Path: | rexml/parent.rb
Last Update: | Tue Jun 10 11:31:05 AUS Eastern Standard Time 2003

Required files

rexml/child


File: parseexception.rb

parseexception.rb

Path: | rexml/parseexception.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005


File: baseparser.rb

baseparser.rb

Path: | rexml/parsers/baseparser.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

rexml/parseexception rexml/source


File: lightparser.rb

lightparser.rb

Path: | rexml/parsers/lightparser.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

rexml/parsers/streamparser rexml/parsers/baseparser rexml/light/node


File: pullparser.rb

pullparser.rb

Path: | rexml/parsers/pullparser.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

forwardable rexml/parseexception rexml/parsers/baseparser rexml/xmltokens


File: sax2parser.rb

sax2parser.rb

Path: | rexml/parsers/sax2parser.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

rexml/parsers/baseparser rexml/parseexception rexml/namespace rexml/text


File: streamparser.rb

streamparser.rb

Path: | rexml/parsers/streamparser.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005


File: treeparser.rb

treeparser.rb

Path: | rexml/parsers/treeparser.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

rexml/validation/validationexception


File: ultralightparser.rb

ultralightparser.rb

Path: | rexml/parsers/ultralightparser.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

rexml/parsers/streamparser rexml/parsers/baseparser


File: xpathparser.rb

xpathparser.rb

Path: | rexml/parsers/xpathparser.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

rexml/namespace rexml/xmltokens


File: quickpath.rb

quickpath.rb

Path: | rexml/quickpath.rb
Last Update: | Sat Oct 11 18:10:07 AUS Eastern Standard Time 2003

Required files

rexml/functions rexml/xmltokens


File: sax2listener.rb

sax2listener.rb

Path: | rexml/sax2listener.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005


File: source.rb

source.rb

Path: | rexml/source.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

rexml/encoding


File: streamlistener.rb

streamlistener.rb

Path: | rexml/streamlistener.rb
Last Update: | Tue Jun 10 11:31:02 AUS Eastern Standard Time 2003


File: syncenumerator.rb

syncenumerator.rb

Path: | rexml/syncenumerator.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005


File: text.rb

text.rb

Path: | rexml/text.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

rexml/entity rexml/doctype rexml/child rexml/doctype rexml/parseexception


File: relaxng.rb

relaxng.rb

Path: | rexml/validation/relaxng.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

Required files

rexml/validation/validation rexml/parsers/baseparser


File: validation.rb

validation.rb

Path: | rexml/validation/validation.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

Required files

rexml/validation/validationexception


File: validationexception.rb

validationexception.rb

Path: | rexml/validation/validationexception.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005


File: xmldecl.rb

xmldecl.rb

Path: | rexml/xmldecl.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

rexml/encoding rexml/source


File: xmltokens.rb

xmltokens.rb

Path: | rexml/xmltokens.rb
Last Update: | Tue Jun 10 11:31:04 AUS Eastern Standard Time 2003


File: xpath.rb

xpath.rb

Path: | rexml/xpath.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

rexml/functions rexml/xpath_parser


File: xpath_parser.rb

xpath_parser.rb

Path: | rexml/xpath_parser.rb
Last Update: | Sat Oct 15 23:44:29 AUS Eastern Standard Time 2005

Required files

rexml/namespace rexml/xmltokens rexml/attribute rexml/syncenumerator rexml/parsers/xpathparser


Module: Rinda

Module | Rinda
In: | rinda/tuplespace.rb rinda/ring.rb 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: | 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.

[Source]

# File rinda/rinda.rb, line 183
    def initialize(uri=nil, ref=nil)
      @drb_uri = uri
      @drb_ref = ref
    end

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.

[Source]

# File 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


Class: Rinda::InvalidHashTupleKey

Class | Rinda::InvalidHashTupleKey
In: | rinda/rinda.rb
Parent: | RindaError

Raised when a hash-based tuple has an invalid key.


Class: Rinda::NotifyTemplateEntry

Class | Rinda::NotifyTemplateEntry
In: | 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.

[Source]

# File 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

Public Instance methods

each( {|event, tuple| ...}

Yields event/tuple pairs until this NotifyTemplateEntry expires.

[Source]

# File rinda/tuplespace.rb, line 272
    def each # :yields: event, tuple
      while !@done
        it = pop
        yield(it)
      end
    rescue
    ensure
      cancel
    end
notify(ev)

Called by TupleSpace to notify this NotifyTemplateEntry of a new event.

[Source]

# File rinda/tuplespace.rb, line 254
    def notify(ev)
      @queue.push(ev)
    end
pop()

Retrieves a notification. Raises RequestExpiredError when this NotifyTemplateEntry expires.

[Source]

# File rinda/tuplespace.rb, line 262
    def pop
      raise RequestExpiredError if @done
      it = @queue.pop
      @done = true if it[0] == 'close'
      return it
    end


Class: Rinda::RequestCanceledError

Class | Rinda::RequestCanceledError
In: | rinda/rinda.rb
Parent: | ThreadError

Raised when trying to use a canceled tuple.


Class: Rinda::RequestExpiredError

Class | Rinda::RequestExpiredError
In: | rinda/rinda.rb
Parent: | ThreadError

Raised when trying to use an expired tuple.


Class: Rinda::RindaError

Class | Rinda::RindaError
In: | rinda/rinda.rb
Parent: | RuntimeError

Rinda error base class


Class: Rinda::RingFinger

Class | Rinda::RingFinger
In: | 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.

[Source]

# File rinda/ring.rb, line 106
    def self.finger
      unless @@finger
        @@finger = self.new
        @@finger.lookup_ring_any
      end
      @@finger
    end
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.

[Source]

# File 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
primary()

Returns the first advertised TupleSpace.

[Source]

# File rinda/ring.rb, line 117
    def self.primary
      finger.primary
    end
to_a()

Contains all discoverd TupleSpaces except for the primary.

[Source]

# File rinda/ring.rb, line 124
    def self.to_a
      finger.to_a
    end

Public Instance methods

each() {|@primary| ...}

Iterates over all discovered TupleSpaces starting with the primary.

[Source]

# File 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(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.

[Source]

# File 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(timeout=5)

Returns the first found remote TupleSpace. Any further recovered TupleSpaces can be found by calling to_a.

[Source]

# File 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
to_a()

Contains all discovered TupleSpaces except for the primary.

[Source]

# File rinda/ring.rb, line 157
    def to_a
      @rings
    end


Class: Rinda::RingProvider

Class | Rinda::RingProvider
In: | 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.

[Source]

# File rinda/ring.rb, line 232
    def initialize(klass, front, desc, renewer = nil)
      @tuple = [:name, klass, front, desc]
      @renewer = renewer || Rinda::SimpleRenewer.new
    end

Public Instance methods

provide()

Advertises this service on the primary remote TupleSpace.

[Source]

# File rinda/ring.rb, line 240
    def provide
      ts = Rinda::RingFinger.primary
      ts.write(@tuple, @renewer)
    end


Class: Rinda::RingServer

Class | Rinda::RingServer
In: | 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.

[Source]

# File 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

Public Instance methods

do_reply()

Pulls lookup tuples out of the TupleSpace and sends their DRb object the address of the local TupleSpace.

[Source]

# File rinda/ring.rb, line 82
    def do_reply
      tuple = @ts.take([:lookup_ring, DRbObject])
      Thread.new { tuple[1].call(@ts) rescue nil}
    rescue
    end
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.

[Source]

# File 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()

Creates a thread that notifies waiting clients from the TupleSpace.

[Source]

# File rinda/ring.rb, line 70
    def reply_service
      Thread.new do
        loop do
          do_reply
        end
      end
    end
write_service()

Creates a thread that picks up UDP packets and passes them to do_write for decoding.

[Source]

# File rinda/ring.rb, line 44
    def write_service
      Thread.new do
        loop do
          msg = @soc.recv(1024)
          do_write(msg)
        end
      end
    end


Class: Rinda::SimpleRenewer

Class | Rinda::SimpleRenewer
In: | 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.

[Source]

# File rinda/rinda.rb, line 270
    def initialize(sec=180)
      @sec = sec
    end

Public Instance methods

renew()

Called by the TupleSpace to check if the object is still alive.

[Source]

# File rinda/rinda.rb, line 277
    def renew
      @sec
    end


Class: Rinda::Template

Class | Rinda::Template
In: | rinda/rinda.rb
Parent: | Tuple

Templates are used to match tuples in Rinda.

Methods

=== match

Public Instance methods

===(tuple)

Alias for match.

[Source]

# File rinda/rinda.rb, line 169
    def ===(tuple)
      match(tuple)
    end
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

[Source]

# File 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


Class: Rinda::TemplateEntry

Class | Rinda::TemplateEntry
In: | 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.

[Source]

# File rinda/tuplespace.rb, line 166
    def match(tuple)
      @tuple.match(tuple)
    end


Class: Rinda::Tuple

Class | Rinda::Tuple
In: | 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.

[Source]

# File 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

Public Instance methods

[](k)

Accessor method for elements of the tuple.

[Source]

# File rinda/rinda.rb, line 69
    def [](k)
      @tuple[k]
    end
each( {|k, v| ...}

Iterate through the tuple, yielding the index or key, and the value, thus ensuring arrays are iterated similarly to hashes.

[Source]

# File 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
fetch(k)

Fetches item k from the tuple.

[Source]

# File rinda/rinda.rb, line 76
    def fetch(k)
      @tuple.fetch(k)
    end
size()

The number of elements in the tuple.

[Source]

# File rinda/rinda.rb, line 62
    def size
      @tuple.size
    end
value()

Return the tuple itself

[Source]

# File rinda/rinda.rb, line 94
    def value
      @tuple
    end


Class: Rinda::TupleBag

Class | Rinda::TupleBag
In: | 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.

[Source]

# File rinda/tuplespace.rb, line 318
    def delete(ary)
      size = ary.size
      @hash.fetch(size, []).delete(ary)
    end
delete_unless_alive()

Delete tuples which dead tuples from the TupleBag, returning the deleted tuples.

[Source]

# File 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
find(template)

Finds a live tuple that matches template.

[Source]

# File 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)

Finds all live tuples that match template.

[Source]

# File 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_all_template(tuple)

Finds all tuples in the TupleBag which when treated as templates, match tuple and are alive.

[Source]

# File 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
has_expires?()

true if the TupleBag to see if it has any expired entries.

[Source]

# File 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(ary)

Add ary to the TupleBag.

[Source]

# File rinda/tuplespace.rb, line 309
    def push(ary)
      size = ary.size
      @hash[size] ||= []
      @hash[size].push(ary)
    end


Class: Rinda::TupleEntry

Class | Rinda::TupleEntry
In: | 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.

[Source]

# File rinda/tuplespace.rb, line 25
    def initialize(ary, sec=nil)
      @cancel = false
      @expires = nil
      @tuple = make_tuple(ary)
      @renewer = nil
      renew(sec)
    end

Public Instance methods

[](key)

Retrieves key from the tuple.

[Source]

# File rinda/tuplespace.rb, line 109
    def [](key)
      @tuple[key]
    end
alive?()

A TupleEntry is dead when it is canceled or expired.

[Source]

# File rinda/tuplespace.rb, line 43
    def alive?
      !canceled? && !expired?
    end
cancel()

Marks this TupleEntry as canceled.

[Source]

# File rinda/tuplespace.rb, line 36
    def cancel
      @cancel = true
    end
canceled?()

Returns the canceled status.

[Source]

# File rinda/tuplespace.rb, line 56
    def canceled?; @cancel; end
expired?()

Has this tuple expired? (true/false).

A tuple has expired when its expiry timer based on the sec argument to initialize runs out.

[Source]

# File 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
fetch(key)

Fetches key from the tuple.

[Source]

# File rinda/tuplespace.rb, line 116
    def fetch(key)
      @tuple.fetch(key)
    end
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)

[Source]

# File 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
make_tuple(ary)

Creates a Rinda::Tuple for ary.

[Source]

# File rinda/tuplespace.rb, line 130
    def make_tuple(ary)
      Rinda::Tuple.new(ary)
    end
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.

[Source]

# File rinda/tuplespace.rb, line 83
    def renew(sec_or_renewer)
      sec, @renewer = get_renewer(sec_or_renewer)
      @expires = make_expires(sec)
    end
size()

The size of the tuple.

[Source]

# File rinda/tuplespace.rb, line 123
    def size
      @tuple.size
    end
value()

Return the object which makes up the tuple itself: the Array or Hash.

[Source]

# File rinda/tuplespace.rb, line 51
    def value; @tuple.value; end


Class: Rinda::TupleSpace

Class | Rinda::TupleSpace
In: | 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.

[Source]

# File 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

Public Instance methods

move(port, tuple, sec=nil) {|template| ...}

Moves tuple to port.

[Source]

# File rinda/tuplespace.rb, line 439
    def move(port, tuple, sec=nil)
      template = WaitTemplateEntry.new(self, tuple, sec)
      yield(template) if block_given?
      start_keeper
      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)
          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
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.

[Source]

# File 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
read(tuple, sec=nil) {|template| ...}

Reads tuple, but does not remove it.

[Source]

# File rinda/tuplespace.rb, line 476
    def read(tuple, sec=nil)
      template = WaitTemplateEntry.new(self, tuple, sec)
      yield(template) if block_given?
      start_keeper
      synchronize do
        entry = @bag.find(template)
        return entry.value if entry
        raise RequestExpiredError if template.expired?

        begin
          @read_waiter.push(template)
          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(tuple)

Returns all tuples matching tuple. Does not remove the found tuples.

[Source]

# File 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
take(tuple, sec=nil, &block)

Removes tuple

[Source]

# File rinda/tuplespace.rb, line 432
    def take(tuple, sec=nil, &block)
      move(nil, tuple, sec, &block)
    end
write(tuple, sec=nil)

Adds tuple

[Source]

# File rinda/tuplespace.rb, line 405
    def write(tuple, sec=nil)
      entry = TupleEntry.new(tuple, sec)
      start_keeper
      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)
          @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


Class: Rinda::TupleSpaceProxy

Class | Rinda::TupleSpaceProxy
In: | 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.

[Source]

# File rinda/rinda.rb, line 213
    def initialize(ts)
      @ts = ts
    end

Public Instance methods

notify(ev, tuple, sec=nil)

Registers for notifications of event ev on the proxied TupleSpace. See TupleSpace#notify

[Source]

# File rinda/rinda.rb, line 252
    def notify(ev, tuple, sec=nil)
      @ts.notify(ev, tuple, sec)
    end
read(tuple, sec=nil, &block)

Reads tuple from the proxied TupleSpace. See TupleSpace#read.

[Source]

# File rinda/rinda.rb, line 236
    def read(tuple, sec=nil, &block)
      @ts.read(tuple, sec, &block)
    end
read_all(tuple)

Reads all tuples matching tuple from the proxied TupleSpace. See TupleSpace#read_all.

[Source]

# File rinda/rinda.rb, line 244
    def read_all(tuple)
      @ts.read_all(tuple)
    end
take(tuple, sec=nil, &block)

Takes tuple from the proxied TupleSpace. See TupleSpace#take.

[Source]

# File rinda/rinda.rb, line 227
    def take(tuple, sec=nil, &block)
      port = []
      @ts.move(DRbObject.new(port), tuple, sec, &block)
      port[0]
    end
write(tuple, sec=nil)

Adds tuple to the proxied TupleSpace. See TupleSpace#write.

[Source]

# File rinda/rinda.rb, line 220
    def write(tuple, sec=nil)
      @ts.write(tuple, sec)
    end


Class: Rinda::WaitTemplateEntry

Class | Rinda::WaitTemplateEntry
In: | rinda/tuplespace.rb
Parent: | TemplateEntry

Documentation?

Methods

cancel new read signal wait

Attributes

found [R]

Public Class methods

new(place, ary, expires=nil)

[Source]

# File rinda/tuplespace.rb, line 185
    def initialize(place, ary, expires=nil)
      super(ary, expires)
      @place = place
      @cond = place.new_cond
      @found = nil
    end

Public Instance methods

cancel()

[Source]

# File rinda/tuplespace.rb, line 192
    def cancel
      super
      signal
    end
read(tuple)

[Source]

# File rinda/tuplespace.rb, line 201
    def read(tuple)
      @found = tuple
      signal
    end
signal()

[Source]

# File rinda/tuplespace.rb, line 206
    def signal
      @place.synchronize do
        @cond.signal
      end
    end
wait()

[Source]

# File rinda/tuplespace.rb, line 197
    def wait
      @cond.wait
    end


File: rinda.rb

rinda.rb

Path: | rinda/rinda.rb
Last Update: | Tue Oct 25 16:35:29 AUS Eastern Standard Time 2005

Required files

drb/drb thread


File: ring.rb

ring.rb

Path: | rinda/ring.rb
Last Update: | Tue Oct 25 16:35:29 AUS Eastern Standard Time 2005

Note: Rinda::Ring API is unstable.

Required files

drb/drb rinda/rinda thread rinda/tuplespace


File: tuplespace.rb

tuplespace.rb

Path: | rinda/tuplespace.rb
Last Update: | Tue Oct 25 16:35:30 AUS Eastern Standard Time 2005

Required files

monitor thread drb/drb rinda/rinda


Module: RSS

Module | RSS
In: | rss/xmlscanner.rb rss/xmlparser.rb rss/xml-stylesheet.rb rss/utils.rb rss/trackback.rb rss/taxonomy.rb rss/syndication.rb rss/rss.rb rss/rexmlparser.rb rss/parser.rb rss/maker.rb rss/maker/trackback.rb rss/maker/syndication.rb rss/maker/image.rb rss/maker/dublincore.rb rss/maker/content.rb rss/maker/base.rb rss/maker/2.0.rb rss/maker/1.0.rb rss/maker/0.9.rb rss/image.rb rss/dublincore.rb rss/converter.rb rss/content.rb rss/2.0.rb rss/1.0.rb rss/0.9.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::TaxonomyModel
Module RSS::TrackBackModel10
Module RSS::TrackBackModel20
Module RSS::TrackBackUtils
Module RSS::Utils
Module RSS::XMLStyleSheetMixin
Class RSS::BaseListener
Class RSS::BaseParser
Class RSS::Channel
Class RSS::ConversionError
Class RSS::Converter
Class RSS::Element
Class RSS::Error
Class RSS::Image
Class RSS::InvalidRSSError
Class RSS::Item
Class RSS::MissingAttributeError
Class RSS::MissingTagError
Class RSS::NSError
Class RSS::NotAvailableValueError
Class RSS::NotExceptedTagError
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::TextInput
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

TRACKBACK_PREFIX | = | 'trackback'
TRACKBACK_URI | = | 'http://madskills.com/public/xml/rss/module/trackback/'
TAXO_PREFIX | = | "taxo"
TAXO_NS | = | "http://purl.org/rss/1.0/modules/taxonomy/"
TAXO_ELEMENTS | = | []
SY_PREFIX | = | 'sy'
SY_URI | = | "http://purl.org/rss/1.0/modules/syndication/"
VERSION | = | "0.1.5"
URI | = | "http://purl.org/rss/1.0/"
DEBUG | = | false
UnknownConvertMethod | = | UnknownConversionMethodError | for backward compatibility
AVAILABLE_PARSER_LIBRARIES | = | [ ["rss/xmlparser", :XMLParserParser], ["rss/xmlscanner", :XMLScanParser], ["rss/rexmlparser", :REXMLParser], ]
AVAILABLE_PARSERS | = | []
IMAGE_PREFIX | = | 'image'
IMAGE_URI | = | 'http://web.resource.org/rss/1.0/modules/image/'
DC_PREFIX | = | 'dc'
DC_URI | = | "http://purl.org/dc/elements/1.1/"
DublincoreModel | = | DublinCoreModel | For backward compatibility
CONTENT_PREFIX | = | 'content'
CONTENT_URI | = | "http://purl.org/rss/1.0/modules/content/"


Module: Enumerable

Module | Enumerable
In: | rss/rss.rb

Methods

sort_by

Public Instance methods

sort_by() {|x| ...}

[Source]

# File rss/rss.rb, line 35
    def sort_by
      collect do |x|
        [yield(x), x]
      end.sort do |x, y|
        x[0] <=> y[0]
      end.collect! do |x|
        x[1]
      end
    end


Class: Hash

Class | Hash
In: | rss/rss.rb
Parent: | Object

Methods

merge

Public Instance methods

merge(other)

[Source]

# File rss/rss.rb, line 49
    def merge(other)
      dup.update(other)
    end


Module: RSS::BaseDublinCoreModel

Module | RSS::BaseDublinCoreModel
In: | rss/dublincore.rb

Methods

append_features

Public Instance methods

append_features(klass)

[Source]

# File 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.module_eval("install_have_children_element(\#{full_name.dump},\n\#{full_plural_name.dump})\n\nremove_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


Class: RSS::BaseListener

Class | RSS::BaseListener
In: | rss/parser.rb
Parent: | Object

Methods

available_tags class_name install_class_name install_get_text_element install_setter register_uri setter uri_registered?

Public Class methods

available_tags(uri)

[Source]

# File rss/parser.rb, line 173
      def available_tags(uri)
        begin
          @@setters[uri].keys
        rescue NameError
          []
        end
      end
class_name(uri, tag_name)

[Source]

# File rss/parser.rb, line 195
      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_class_name(uri, tag_name, class_name)

[Source]

# File rss/parser.rb, line 190
      def install_class_name(uri, tag_name, class_name)
        @@class_names[uri] ||= {}
        @@class_names[uri][tag_name] = class_name
      end
install_get_text_element(uri, name, setter)

[Source]

# File rss/parser.rb, line 203
      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
install_setter(uri, tag_name, setter)

[Source]

# File rss/parser.rb, line 160
      def install_setter(uri, tag_name, setter)
        @@setters[uri] ||= {}
        @@setters[uri][tag_name] = setter
      end
register_uri(uri, name)

[Source]

# File rss/parser.rb, line 181
      def register_uri(uri, name)
        @@registered_uris[name] ||= {}
        @@registered_uris[name][uri] = nil
      end
setter(uri, tag_name)

[Source]

# File rss/parser.rb, line 165
      def setter(uri, tag_name)
        begin
          @@setters[uri][tag_name]
        rescue NameError
          nil
        end
      end
uri_registered?(uri, name)

[Source]

# File rss/parser.rb, line 186
      def uri_registered?(uri, name)
        @@registered_uris[name].has_key?(uri)
      end


Module: RSS::BaseModel

Module | RSS::BaseModel
In: | 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(name, type, disp_name=name)

[Source]

# File rss/rss.rb, line 223
    def install_date_element(name, type, disp_name=name)
      self::ELEMENTS << name
      add_need_initialize_variable(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
install_have_attribute_element(name)

Alias for install_have_child_element

install_have_child_element(name)

[Source]

# File rss/rss.rb, line 161
    def install_have_child_element(name)
      add_need_initialize_variable(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(name, plural_name=nil)

[Source]

# File rss/rss.rb, line 178
    def install_have_children_element(name, plural_name=nil)
      plural_name ||= "#{name}s"
      add_have_children_element(name, plural_name)
      add_plural_form(name, 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(name)

[Source]

# File rss/rss.rb, line 197
    def install_text_element(name)
      self::ELEMENTS << name
      add_need_initialize_variable(name)

      attr_writer 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


Class: RSS::BaseParser

Class | RSS::BaseParser
In: | rss/parser.rb
Parent: | Object

Methods

do_validate do_validate= ignore_unknown_element ignore_unknown_element= new parse rss

Public Class methods

new(rss)

[Source]

# File rss/parser.rb, line 116
    def initialize(rss)
      @listener = listener.new
      @rss = rss
    end

Public Instance methods

do_validate()

[Source]

# File rss/parser.rb, line 133
    def do_validate
      @listener.do_validate
    end
do_validate=(new_value)

[Source]

# File rss/parser.rb, line 137
    def do_validate=(new_value)
      @listener.do_validate = new_value
    end
ignore_unknown_element()

[Source]

# File rss/parser.rb, line 125
    def ignore_unknown_element
      @listener.ignore_unknown_element
    end
ignore_unknown_element=(new_value)

[Source]

# File rss/parser.rb, line 129
    def ignore_unknown_element=(new_value)
      @listener.ignore_unknown_element = new_value
    end
parse()

[Source]

# File rss/parser.rb, line 141
    def parse
      if @listener.rss.nil?
        _parse
      end
      @listener.rss
    end
rss()

[Source]

# File rss/parser.rb, line 121
    def rss
      @listener.rss
    end


Module: RSS::BaseTrackBackModel

Module | RSS::BaseTrackBackModel
In: | rss/trackback.rb

Methods

append_features

Included Modules

TrackBackUtils

Public Instance methods

append_features(klass)

[Source]

# File rss/trackback.rb, line 37
    def append_features(klass)
      super

      unless klass.class == Module
        klass.module_eval {include TrackBackUtils}

        %w(ping).each do |name|
          var_name = "#{TRACKBACK_PREFIX}_#{name}"
          klass_name = name.capitalize
          klass.install_have_child_element(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 = name.capitalize
          klass.install_have_children_element(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


Class: RSS::Channel

Class | RSS::Channel
In: | rss/taxonomy.rb
Parent: | Object


Module: RSS::ContentModel

Module | RSS::ContentModel
In: | rss/content.rb

Methods

append_features content_validate

Constants

ELEMENTS = []

Public Class methods

append_features(klass)

[Source]

# File rss/content.rb, line 16
    def self.append_features(klass)
      super

      klass.module_eval("%w(encoded).each do |name|\ninstall_text_element(\"\\\#{CONTENT_PREFIX}_\\\#{name}\")\nend\n", *get_file_and_line_from_caller(1))
    end

Public Instance methods

content_validate(tags)

[Source]

# File rss/content.rb, line 27
    def content_validate(tags)
      counter = {}
      ELEMENTS.each do |name|
        counter[name] = 0
      end

      tags.each do |tag|
        key = "#{CONTENT_PREFIX}_#{tag}"
        raise UnknownTagError.new(tag, CONTENT_URI) unless counter.has_key?(key)
        counter[key] += 1
        raise TooMuchTagError.new(tag, tag_name) if counter[key] > 1
      end
    end


Class: RSS::ConversionError

Class | RSS::ConversionError
In: | rss/rss.rb
Parent: | Error

Methods

new

Attributes

from | [R]
string | [R]
to | [R]

Public Class methods

new(string, to, from)

[Source]

# File rss/rss.rb, line 140
    def initialize(string, to, from)
      @string = string
      @to = to
      @from = from
      super("can't convert #{@string} to #{to} from #{from}.")
    end


Class: RSS::Converter

Class | RSS::Converter
In: | 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)

[Source]

# File 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

Public Instance methods

convert(value)

[Source]

# File rss/converter.rb, line 25
    def convert(value)
      value
    end
def_convert(depth=0)

[Source]

# File 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_else_enc(to_enc, from_enc)

[Source]

# File rss/converter.rb, line 61
    def def_else_enc(to_enc, from_enc)
      def_iconv_convert(to_enc, from_enc, 0)
    end
def_iconv_convert(to_enc, from_enc, depth=0)

[Source]

# File 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_same_enc()

[Source]

# File rss/converter.rb, line 65
    def def_same_enc()
      def_convert do |value|
        value
      end
    end
def_to_euc_jp_from_iso_2022_jp()

[Source]

# File rss/converter.rb, line 119
    def def_to_euc_jp_from_iso_2022_jp
      require "nkf"
      def_convert do |value|
        "NKF.nkf('-Je', #{value})"
      end
    end
def_to_euc_jp_from_shift_jis()

[Source]

# File rss/converter.rb, line 105
    def def_to_euc_jp_from_shift_jis
      require "nkf"
      def_convert do |value|
        "NKF.nkf('-Se', #{value})"
      end
    end
def_to_euc_jp_from_utf_8()

[Source]

# File rss/converter.rb, line 89
    def def_to_euc_jp_from_utf_8
      def_uconv_convert_if_can('u8toeuc', 'EUC-JP', 'UTF-8')
    end
def_to_iso_2022_jp_from_euc_jp()

[Source]

# File rss/converter.rb, line 126
    def def_to_iso_2022_jp_from_euc_jp
      require "nkf"
      def_convert do |value|
        "NKF.nkf('-Ej', #{value})"
      end
    end
def_to_iso_8859_1_from_utf_8()

[Source]

# File rss/converter.rb, line 139
    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
def_to_shift_jis_from_euc_jp()

[Source]

# File rss/converter.rb, line 112
    def def_to_shift_jis_from_euc_jp
      require "nkf"
      def_convert do |value|
        "NKF.nkf('-Es', #{value})"
      end
    end
def_to_shift_jis_from_utf_8()

[Source]

# File rss/converter.rb, line 97
    def def_to_shift_jis_from_utf_8
      def_uconv_convert_if_can('u8tosjis', 'Shift_JIS', 'UTF-8')
    end
def_to_utf_8_from_euc_jp()

[Source]

# File rss/converter.rb, line 93
    def def_to_utf_8_from_euc_jp
      def_uconv_convert_if_can('euctou8', 'UTF-8', 'EUC-JP')
    end
def_to_utf_8_from_iso_8859_1()

[Source]

# File rss/converter.rb, line 133
    def def_to_utf_8_from_iso_8859_1
      def_convert do |value|
        "#{value}.unpack('C*').pack('U*')"
      end
    end
def_to_utf_8_from_shift_jis()

[Source]

# File rss/converter.rb, line 101
    def def_to_utf_8_from_shift_jis
      def_uconv_convert_if_can('sjistou8', 'UTF-8', 'Shift_JIS')
    end
def_uconv_convert_if_can(meth, to_enc, from_enc)

[Source]

# File rss/converter.rb, line 71
    def def_uconv_convert_if_can(meth, to_enc, from_enc)
      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
        def_iconv_convert(to_enc, from_enc, 1)
      end
    end


Module: RSS::DublinCoreModel

Module | RSS::DublinCoreModel
In: | rss/dublincore.rb

Methods

dc_validate

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

Public Instance methods

dc_validate(tags)

[Source]

# File rss/dublincore.rb, line 137
    def dc_validate(tags)
      tags.each do |tag|
        key = "#{DC_PREFIX}_#{tag}"
        unless DublinCoreModel::ELEMENTS.include?(key)
          raise UnknownTagError.new(tag, DC_URI)
        end
      end
    end


Class: RSS::Element

Class | RSS::Element
In: | rss/rss.rb
Parent: | Object

Methods

convert converter= full_name get_attributes have_children_elements indent_size indent_size inherited install_ns model must_call_validators need_initialize_variables new plural_forms required_prefix required_uri setup_maker tag_name tag_name validate validate_for_stream

Included Modules

Utils

Constants

INDENT | = | " "
MUST_CALL_VALIDATORS | = | {}
MODEL | = | []
GET_ATTRIBUTES | = | []
HAVE_CHILDREN_ELEMENTS | = | []
NEED_INITIALIZE_VARIABLES | = | []
PLURAL_FORMS | = | {}

Attributes

do_validate [RW]

Public Class methods

get_attributes()

[Source]

# File rss/rss.rb, line 387
      def get_attributes
        GET_ATTRIBUTES
      end
have_children_elements()

[Source]

# File rss/rss.rb, line 390
      def have_children_elements
        HAVE_CHILDREN_ELEMENTS
      end
indent_size()

[Source]

# File rss/rss.rb, line 501
      def indent_size
        @indent_size
      end
inherited(klass)

[Source]

# File rss/rss.rb, line 401
      def inherited(klass)
        klass.const_set("MUST_CALL_VALIDATORS", {})
        klass.const_set("MODEL", [])
        klass.const_set("GET_ATTRIBUTES", [])
        klass.const_set("HAVE_CHILDREN_ELEMENTS", [])
        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@indent_size = name.split(/::/).size - 2\n@have_content = false\n\ndef self.must_call_validators\nsuper.merge(MUST_CALL_VALIDATORS)\nend\ndef self.model\nMODEL + super\nend\ndef self.get_attributes\nGET_ATTRIBUTES + super\nend\ndef self.have_children_elements\nHAVE_CHILDREN_ELEMENTS + 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, occurs=nil)\nif m = MODEL.find {|t, o| t == tag}\nm[1] = occurs\nelse\nMODEL << [tag, occurs]\nend\nend\n\ndef self.install_get_attribute(name, uri, required=true)\nattr_writer name\nconvert_attr_reader name\nGET_ATTRIBUTES << [name, uri, required]\nend\n\ndef self.content_setup\nattr_writer :content\nconvert_attr_reader :content\ndef_content_only_to_s\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_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
install_ns(prefix, uri)

[Source]

# File rss/rss.rb, line 490
      def install_ns(prefix, uri)
        if self::NSPOOL.has_key?(prefix)
          raise OverlappedPrefixError.new(prefix)
        end
        self::NSPOOL[prefix] = uri
      end
model()

[Source]

# File rss/rss.rb, line 384
      def model
        MODEL
      end
must_call_validators()

[Source]

# File rss/rss.rb, line 381
      def must_call_validators
        MUST_CALL_VALIDATORS
      end
need_initialize_variables()

[Source]

# File rss/rss.rb, line 393
      def need_initialize_variables
        NEED_INITIALIZE_VARIABLES
      end
new(do_validate=true)

[Source]

# File rss/rss.rb, line 509
    def initialize(do_validate=true)
      @converter = nil
      @do_validate = do_validate
      initialize_variables
    end
plural_forms()

[Source]

# File rss/rss.rb, line 396
      def plural_forms
        PLURAL_FORMS
      end
required_prefix()

[Source]

# File rss/rss.rb, line 482
      def required_prefix
        nil
      end
required_uri()

[Source]

# File rss/rss.rb, line 486
      def required_uri
        nil
      end
tag_name()

[Source]

# File rss/rss.rb, line 497
      def tag_name
        @tag_name
      end

Public Instance methods

convert(value)

[Source]

# File rss/rss.rb, line 538
    def convert(value)
      if @converter
        @converter.convert(value)
      else
        value
      end
    end
converter=(converter)

[Source]

# File rss/rss.rb, line 527
    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
full_name()

[Source]

# File rss/rss.rb, line 519
    def full_name
      tag_name
    end
indent_size()

[Source]

# File rss/rss.rb, line 523
    def indent_size
      self.class.indent_size
    end
setup_maker(maker)

[Source]

# File rss/rss.rb, line 556
    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
tag_name()

[Source]

# File rss/rss.rb, line 515
    def tag_name
      self.class.tag_name
    end
validate()

[Source]

# File rss/rss.rb, line 546
    def validate
      validate_attribute
      __validate
    end
validate_for_stream(tags)

[Source]

# File rss/rss.rb, line 551
    def validate_for_stream(tags)
      validate_attribute
      __validate(tags, false)
    end


Class: RSS::Error

Class | RSS::Error
In: | rss/rss.rb
Parent: | StandardError


Class: RSS::Image

Class | RSS::Image
In: | rss/taxonomy.rb
Parent: | Object


Module: RSS::ImageFaviconModel

Module | RSS::ImageFaviconModel
In: | rss/image.rb

Methods

append_features image_validate

Included Modules

ImageModelUtils

Classes and Modules

Class RSS::ImageFaviconModel::Favicon

Public Class methods

append_features(klass)

[Source]

# File rss/image.rb, line 135
    def self.append_features(klass)
      super

      unless klass.class == Module
        klass.install_have_child_element("#{IMAGE_PREFIX}_favicon")
      end
    end

Public Instance methods

image_validate(tags)

[Source]

# File rss/image.rb, line 143
    def image_validate(tags)
      validate_one_tag_name("favicon", tags)
    end


Class: RSS::ImageFaviconModel::Favicon

Class | RSS::ImageFaviconModel::Favicon
In: | rss/image.rb
Parent: | Element

Methods

full_name new required_prefix required_uri to_s

Included Modules

RSS10 DublinCoreModel

External Aliases

size= | -> | image_size=
size | -> | image_size

Public Class methods

new(about=nil, size=nil)

[Source]

# File rss/image.rb, line 171
      def initialize(about=nil, size=nil)
        super()
        @about = about
        @size = size
      end
required_prefix()

[Source]

# File rss/image.rb, line 152
        def required_prefix
          IMAGE_PREFIX
        end
required_uri()

[Source]

# File rss/image.rb, line 156
        def required_uri
          IMAGE_URI
        end

Public Instance methods

full_name()

[Source]

# File rss/image.rb, line 177
      def full_name
        tag_name_with_prefix(IMAGE_PREFIX)
      end
to_s(need_convert=true, indent=calc_indent)

[Source]

# File rss/image.rb, line 181
      def to_s(need_convert=true, indent=calc_indent)
        rv = tag(indent) do |next_indent|
          [
            other_element(false, next_indent),
          ]
        end
        rv = convert(rv) if need_convert
        rv
      end


Module: RSS::ImageItemModel

Module | RSS::ImageItemModel
In: | rss/image.rb

Methods

append_features image_validate

Included Modules

ImageModelUtils

Classes and Modules

Class RSS::ImageItemModel::Item

Public Class methods

append_features(klass)

[Source]

# File rss/image.rb, line 23
    def self.append_features(klass)
      super

      klass.install_have_child_element("#{IMAGE_PREFIX}_item")
    end

Public Instance methods

image_validate(tags)

[Source]

# File rss/image.rb, line 29
    def image_validate(tags)
      validate_one_tag_name("item", tags)
    end


Class: RSS::ImageItemModel::Item

Class | RSS::ImageItemModel::Item
In: | rss/image.rb
Parent: | Element

Methods

full_name height= image_height= image_width= new required_prefix required_uri to_s width=

Included Modules

RSS10 DublinCoreModel

External Aliases

image_width= | -> | _image_width=
image_height= | -> | _image_height=
image_width | -> | width
image_height | -> | height

Public Class methods

new(about=nil, resource=nil)

[Source]

# File rss/image.rb, line 60
      def initialize(about=nil, resource=nil)
        super()
        @about = about
        @resource = resource
      end
required_prefix()

[Source]

# File rss/image.rb, line 38
        def required_prefix
          IMAGE_PREFIX
        end
required_uri()

[Source]

# File rss/image.rb, line 42
        def required_uri
          IMAGE_URI
        end

Public Instance methods

full_name()

[Source]

# File rss/image.rb, line 66
      def full_name
        tag_name_with_prefix(IMAGE_PREFIX)
      end
height=(new_value)

Alias for image_height=

image_height=(new_value)

[Source]

# File rss/image.rb, line 90
      def image_height=(new_value)
        if @do_validate
          self._image_height = Integer(new_value)
        else
          self._image_height = new_value.to_i
        end
      end
image_width=(new_value)

[Source]

# File rss/image.rb, line 81
      def image_width=(new_value)
        if @do_validate
          self._image_width = Integer(new_value)
        else
          self._image_width = new_value.to_i
        end
      end
to_s(need_convert=true, indent=calc_indent)

[Source]

# File rss/image.rb, line 70
      def to_s(need_convert=true, indent=calc_indent)
        rv = tag(indent) do |next_indent|
          [
            other_element(false, next_indent),
          ]
        end
        rv = convert(rv) if need_convert
        rv
      end
width=(new_value)

Alias for image_width=


Module: RSS::ImageModelUtils

Module | RSS::ImageModelUtils
In: | rss/image.rb

Methods

validate_one_tag_name

Public Instance methods

validate_one_tag_name(name, tags)

[Source]

# File rss/image.rb, line 12
    def validate_one_tag_name(name, tags)
      invalid = tags.find {|tag| tag != name}
      raise UnknownTagError.new(invalid, IMAGE_URI) if invalid
      raise TooMuchTagError.new(name, tag_name) if tags.size > 1
    end


Class: RSS::InvalidRSSError

Class | RSS::InvalidRSSError
In: | rss/rss.rb
Parent: | Error


Class: RSS::Item

Class | RSS::Item
In: | rss/taxonomy.rb
Parent: | Object


Module: RSS::ListenerMixin

Module | RSS::ListenerMixin
In: | rss/parser.rb rss/1.0.rb rss/0.9.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()

[Source]

# File rss/parser.rb, line 245
    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

Public Instance methods

instruction(name, content)

[Source]

# File rss/parser.rb, line 262
    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_end(name)

[Source]

# File rss/parser.rb, line 295
    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
tag_start(name, attributes)

[Source]

# File rss/parser.rb, line 271
    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[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
text(data)

[Source]

# File rss/parser.rb, line 307
    def text(data)
      @text_stack.last << data
    end
xmldecl(version, encoding, standalone)

[Source]

# File rss/parser.rb, line 258
    def xmldecl(version, encoding, standalone)
      @version, @encoding, @standalone = version, encoding, standalone
    end


Module: RSS::Maker

Module | RSS::Maker
In: | rss/maker.rb rss/maker/trackback.rb rss/maker/syndication.rb rss/maker/image.rb rss/maker/dublincore.rb rss/maker/content.rb rss/maker/base.rb rss/maker/2.0.rb rss/maker/1.0.rb rss/maker/0.9.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::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)

[Source]

# File rss/maker.rb, line 18
      def add_maker(version, maker)
        MAKERS[version] = maker
      end
filename_to_version(filename)

[Source]

# File rss/maker.rb, line 22
      def filename_to_version(filename)
        File.basename(filename, ".*")
      end
make(version, &block)

[Source]

# File rss/maker.rb, line 10
      def make(version, &block)
        maker(version).make(&block)
      end
maker(version)

[Source]

# File rss/maker.rb, line 14
      def maker(version)
        MAKERS[version]
      end


Module: RSS::Maker::Base

Module | RSS::Maker::Base
In: | rss/maker/base.rb

Methods

append_features have_required_values? new

Public Class methods

append_features(klass)

[Source]

# File 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(maker)

[Source]

# File rss/maker/base.rb, line 63
      def initialize(maker)
        @maker = maker
        initialize_variables
      end

Public Instance methods

have_required_values?()

[Source]

# File rss/maker/base.rb, line 68
      def have_required_values?
        true
      end


Class: RSS::Maker::ChannelBase

Class | RSS::Maker::ChannelBase
In: | rss/maker/syndication.rb rss/maker/image.rb rss/maker/dublincore.rb rss/maker/base.rb
Parent: | Object

Methods

current_element

Included Modules

SyndicationModel Maker::ImageFaviconModel DublinCoreModel 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)

[Source]

# File rss/maker/base.rb, line 276
      def current_element(rss)
        rss.channel
      end


Class: RSS::Maker::ChannelBase::CategoriesBase

Class | RSS::Maker::ChannelBase::CategoriesBase
In: | 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()

[Source]

# File rss/maker/base.rb, line 359
        def new_category
          category = self.class::Category.new(@maker)
          @categories << category
          category
        end


Class: RSS::Maker::ChannelBase::CategoriesBase::CategoryBase

Class | RSS::Maker::ChannelBase::CategoriesBase::CategoryBase
In: | rss/maker/base.rb
Parent: | Object

Included Modules

Base


Class: RSS::Maker::ChannelBase::CloudBase

Class | RSS::Maker::ChannelBase::CloudBase
In: | rss/maker/base.rb
Parent: | Object

Methods

current_element

Included Modules

Base

Public Instance methods

current_element(rss)

[Source]

# File rss/maker/base.rb, line 348
        def current_element(rss)
          rss.channel.cloud
        end


Class: RSS::Maker::ChannelBase::SkipDaysBase

Class | RSS::Maker::ChannelBase::SkipDaysBase
In: | 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)

[Source]

# File rss/maker/base.rb, line 291
        def current_element(rss)
          rss.channel.skipDays
        end
new_day()

[Source]

# File rss/maker/base.rb, line 285
        def new_day
          day = self.class::Day.new(@maker)
          @days << day
          day
        end


Class: RSS::Maker::ChannelBase::SkipDaysBase::DayBase

Class | RSS::Maker::ChannelBase::SkipDaysBase::DayBase
In: | rss/maker/base.rb
Parent: | Object

Methods

current_element

Included Modules

Base

Public Instance methods

current_element(rss)

[Source]

# File rss/maker/base.rb, line 303
          def current_element(rss)
            rss.channel.skipDays.last
          end


Class: RSS::Maker::ChannelBase::SkipHoursBase

Class | RSS::Maker::ChannelBase::SkipHoursBase
In: | 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)

[Source]

# File rss/maker/base.rb, line 321
        def current_element(rss)
          rss.channel.skipHours
        end
new_hour()

[Source]

# File rss/maker/base.rb, line 315
        def new_hour
          hour = self.class::Hour.new(@maker)
          @hours << hour
          hour
        end


Class: RSS::Maker::ChannelBase::SkipHoursBase::HourBase

Class | RSS::Maker::ChannelBase::SkipHoursBase::HourBase
In: | rss/maker/base.rb
Parent: | Object

Methods

current_element

Included Modules

Base

Public Instance methods

current_element(rss)

[Source]

# File rss/maker/base.rb, line 333
          def current_element(rss)
            rss.channel.skipHours.last
          end


Module: RSS::Maker::ContentModel

Module | RSS::Maker::ContentModel
In: | rss/maker/content.rb

Methods

append_features

Public Class methods

append_features(klass)

[Source]

# File 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


Module: RSS::Maker::DublinCoreModel

Module | RSS::Maker::DublinCoreModel
In: | rss/maker/dublincore.rb

Methods

append_features install_dublin_core

Public Class methods

append_features(klass)

[Source]

# File 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(klass)

[Source]

# File rss/maker/dublincore.rb, line 83
      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


Class: RSS::Maker::ImageBase

Class | RSS::Maker::ImageBase
In: | rss/maker/dublincore.rb rss/maker/base.rb
Parent: | Object

Methods

current_element link

Included Modules

DublinCoreModel Base

Public Instance methods

current_element(rss)

[Source]

# File rss/maker/base.rb, line 388
      def current_element(rss)
        rss.image
      end
link()

[Source]

# File rss/maker/base.rb, line 384
      def link
        @maker.channel.link
      end


Module: RSS::Maker::ImageFaviconModel

Module | RSS::Maker::ImageFaviconModel
In: | rss/maker/image.rb

Methods

append_features

Classes and Modules

Class RSS::Maker::ImageFaviconModel::ImageFaviconBase

Public Class methods

append_features(klass)

[Source]

# File 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


Class: RSS::Maker::ImageFaviconModel::ImageFaviconBase

Class | RSS::Maker::ImageFaviconModel::ImageFaviconBase
In: | 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?()

[Source]

# File rss/maker/image.rb, line 81
        def have_required_values?
          @about and @image_size
        end


Module: RSS::Maker::ImageItemModel

Module | RSS::Maker::ImageItemModel
In: | rss/maker/image.rb

Methods

append_features

Classes and Modules

Class RSS::Maker::ImageItemModel::ImageItemBase

Public Class methods

append_features(klass)

[Source]

# File 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


Class: RSS::Maker::ImageItemModel::ImageItemBase

Class | RSS::Maker::ImageItemModel::ImageItemBase
In: | 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?()

[Source]

# File rss/maker/image.rb, line 43
        def have_required_values?
          @about
        end


Class: RSS::Maker::ItemsBase

Class | RSS::Maker::ItemsBase
In: | rss/maker/trackback.rb rss/maker/image.rb rss/maker/dublincore.rb rss/maker/content.rb 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)

[Source]

# File rss/maker/base.rb, line 400
      def initialize(maker)
        super
        @do_sort = false
        @max_size = -1
      end

Public Instance methods

current_element(rss)

[Source]

# File rss/maker/base.rb, line 414
      def current_element(rss)
        rss.items
      end
new_item()

[Source]

# File rss/maker/base.rb, line 418
      def new_item
        item = self.class::Item.new(@maker)
        @items << item
        item
      end
normalize()

[Source]

# File rss/maker/base.rb, line 406
      def normalize
        if @max_size >= 0
          sort_if_need[0...@max_size]
        else
          sort_if_need[0..@max_size]
        end
      end


Class: RSS::Maker::ItemsBase::ItemBase

Class | RSS::Maker::ItemsBase::ItemBase
In: | rss/maker/trackback.rb rss/maker/image.rb rss/maker/dublincore.rb rss/maker/content.rb rss/maker/base.rb
Parent: | Object

Methods

<=> current_element

Included Modules

TrackBackModel Maker::ImageItemModel DublinCoreModel 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)

[Source]

# File rss/maker/base.rb, line 467
        def <=>(other)
          if date and other.date
            date <=> other.date
          elsif date
            1
          elsif other.date
            -1
          else
            0
          end
        end
current_element(rss)

[Source]

# File rss/maker/base.rb, line 479
        def current_element(rss)
          rss.items.last
        end


Class: RSS::Maker::ItemsBase::ItemBase::EnclosureBase

Class | RSS::Maker::ItemsBase::ItemBase::EnclosureBase
In: | rss/maker/base.rb
Parent: | Object

Included Modules

Base


Class: RSS::Maker::ItemsBase::ItemBase::GuidBase

Class | RSS::Maker::ItemsBase::ItemBase::GuidBase
In: | rss/maker/base.rb
Parent: | Object

Included Modules

Base


Class: RSS::Maker::ItemsBase::ItemBase::SourceBase

Class | RSS::Maker::ItemsBase::ItemBase::SourceBase
In: | rss/maker/base.rb
Parent: | Object

Included Modules

Base


Class: RSS::Maker::RSS09

Class | RSS::Maker::RSS09
In: | rss/maker/trackback.rb rss/maker/image.rb rss/maker/dublincore.rb 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")

[Source]

# File rss/maker/0.9.rb, line 10
      def initialize(rss_version="0.91")
        super
      end


Class: RSS::Maker::RSS09::Channel

Class | RSS::Maker::RSS09::Channel
In: | rss/maker/image.rb rss/maker/dublincore.rb 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?()

[Source]

# File rss/maker/0.9.rb, line 44
        def have_required_values?
          @title and @link and @description and @language
        end
to_rss(rss)

[Source]

# File 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


Class: RSS::Maker::RSS09::Channel::Categories

Class | RSS::Maker::RSS09::Channel::Categories
In: | 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)

[Source]

# File rss/maker/0.9.rb, line 129
          def to_rss(*args)
          end


Class: RSS::Maker::RSS09::Channel::Categories::Category

Class | RSS::Maker::RSS09::Channel::Categories::Category
In: | rss/maker/0.9.rb
Parent: | CategoryBase


Class: RSS::Maker::RSS09::Channel::Cloud

Class | RSS::Maker::RSS09::Channel::Cloud
In: | rss/maker/0.9.rb
Parent: | CloudBase

Methods

to_rss

Public Instance methods

to_rss(*args)

[Source]

# File rss/maker/0.9.rb, line 124
          def to_rss(*args)
          end


Class: RSS::Maker::RSS09::Channel::ImageFavicon

Class | RSS::Maker::RSS09::Channel::ImageFavicon
In: | rss/maker/image.rb
Parent: | ImageFaviconBase

Methods

to_rss

Public Instance methods

to_rss(*args)

[Source]

# File rss/maker/image.rb, line 140
          def to_rss(*args)
          end


Class: RSS::Maker::RSS09::Channel::SkipDays

Class | RSS::Maker::RSS09::Channel::SkipDays
In: | 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)

[Source]

# File 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


Class: RSS::Maker::RSS09::Channel::SkipDays::Day

Class | RSS::Maker::RSS09::Channel::SkipDays::Day
In: | rss/maker/0.9.rb
Parent: | DayBase

Methods

have_required_values? to_rss

Public Instance methods

have_required_values?()

[Source]

# File rss/maker/0.9.rb, line 90
            def have_required_values?
              @content
            end
to_rss(rss, days)

[Source]

# File 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


Class: RSS::Maker::RSS09::Channel::SkipHours

Class | RSS::Maker::RSS09::Channel::SkipHours
In: | 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)

[Source]

# File 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


Class: RSS::Maker::RSS09::Channel::SkipHours::Hour

Class | RSS::Maker::RSS09::Channel::SkipHours::Hour
In: | rss/maker/0.9.rb
Parent: | HourBase

Methods

have_required_values? to_rss

Public Instance methods

have_required_values?()

[Source]

# File rss/maker/0.9.rb, line 117
            def have_required_values?
              @content
            end
to_rss(rss, hours)

[Source]

# File 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


Class: RSS::Maker::RSS09::Image

Class | RSS::Maker::RSS09::Image
In: | rss/maker/dublincore.rb rss/maker/0.9.rb
Parent: | Object

Methods

have_required_values? to_rss

Public Instance methods

have_required_values?()

[Source]

# File rss/maker/0.9.rb, line 148
        def have_required_values?
          @url and @title and link
        end
to_rss(rss)

[Source]

# File 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


Class: RSS::Maker::RSS09::Items

Class | RSS::Maker::RSS09::Items
In: | rss/maker/trackback.rb rss/maker/image.rb rss/maker/dublincore.rb 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)

[Source]

# File 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


Class: RSS::Maker::RSS09::Items::Item

Class | RSS::Maker::RSS09::Items::Item
In: | rss/maker/trackback.rb rss/maker/image.rb rss/maker/dublincore.rb 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)

[Source]

# File 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


Class: RSS::Maker::RSS09::Items::Item::Categories

Class | RSS::Maker::RSS09::Items::Item::Categories
In: | 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)

[Source]

# File rss/maker/0.9.rb, line 194
            def to_rss(*args)
            end


Class: RSS::Maker::RSS09::Items::Item::Categories::Category

Class | RSS::Maker::RSS09::Items::Item::Categories::Category
In: | rss/maker/0.9.rb
Parent: | CategoryBase


Class: RSS::Maker::RSS09::Items::Item::Enclosure

Class | RSS::Maker::RSS09::Items::Item::Enclosure
In: | rss/maker/0.9.rb
Parent: | EnclosureBase

Methods

to_rss

Public Instance methods

to_rss(*args)

[Source]

# File rss/maker/0.9.rb, line 184
            def to_rss(*args)
            end


Class: RSS::Maker::RSS09::Items::Item::Guid

Class | RSS::Maker::RSS09::Items::Item::Guid
In: | rss/maker/0.9.rb
Parent: | GuidBase

Methods

to_rss

Public Instance methods

to_rss(*args)

[Source]

# File rss/maker/0.9.rb, line 179
            def to_rss(*args)
            end


Class: RSS::Maker::RSS09::Items::Item::ImageItem

Class | RSS::Maker::RSS09::Items::Item::ImageItem
In: | rss/maker/image.rb
Parent: | ImageItemBase

Methods

to_rss

Public Instance methods

to_rss(*args)

[Source]

# File rss/maker/image.rb, line 131
            def to_rss(*args)
            end


Class: RSS::Maker::RSS09::Items::Item::Source

Class | RSS::Maker::RSS09::Items::Item::Source
In: | rss/maker/0.9.rb
Parent: | SourceBase

Methods

to_rss

Public Instance methods

to_rss(*args)

[Source]

# File rss/maker/0.9.rb, line 189
            def to_rss(*args)
            end


Class: RSS::Maker::RSS09::Items::Item::TrackBackAbouts

Class | RSS::Maker::RSS09::Items::Item::TrackBackAbouts
In: | rss/maker/trackback.rb
Parent: | TrackBackAboutsBase

Methods

to_rss

Classes and Modules

Class RSS::Maker::RSS09::Items::Item::TrackBackAbouts::About

Public Instance methods

to_rss(*args)

[Source]

# File rss/maker/trackback.rb, line 101
            def to_rss(*args)
            end


Class: RSS::Maker::RSS09::Items::Item::TrackBackAbouts::About

Class | RSS::Maker::RSS09::Items::Item::TrackBackAbouts::About
In: | rss/maker/trackback.rb
Parent: | AboutBase


Class: RSS::Maker::RSS09::Textinput

Class | RSS::Maker::RSS09::Textinput
In: | rss/maker/dublincore.rb rss/maker/0.9.rb
Parent: | Object

Methods

to_rss

Public Instance methods

to_rss(rss)

[Source]

# File 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


Class: RSS::Maker::RSS10

Class | RSS::Maker::RSS10
In: | rss/maker/trackback.rb rss/maker/image.rb rss/maker/dublincore.rb 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()

[Source]

# File rss/maker/1.0.rb, line 10
      def initialize
        super("1.0")
      end


Class: RSS::Maker::RSS10::Channel

Class | RSS::Maker::RSS10::Channel
In: | rss/maker/image.rb rss/maker/dublincore.rb 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?()

[Source]

# File rss/maker/1.0.rb, line 48
        def have_required_values?
          @about and @title and @link and @description
        end
to_rss(rss)

[Source]

# File 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


Class: RSS::Maker::RSS10::Channel::Categories

Class | RSS::Maker::RSS10::Channel::Categories
In: | 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)

[Source]

# File rss/maker/1.0.rb, line 101
          def to_rss(*args)
          end


Class: RSS::Maker::RSS10::Channel::Categories::Category

Class | RSS::Maker::RSS10::Channel::Categories::Category
In: | rss/maker/1.0.rb
Parent: | CategoryBase


Class: RSS::Maker::RSS10::Channel::Cloud

Class | RSS::Maker::RSS10::Channel::Cloud
In: | rss/maker/1.0.rb
Parent: | CloudBase

Methods

to_rss

Public Instance methods

to_rss(*args)

[Source]

# File rss/maker/1.0.rb, line 96
          def to_rss(*args)
          end


Class: RSS::Maker::RSS10::Channel::ImageFavicon

Class | RSS::Maker::RSS10::Channel::ImageFavicon
In: | rss/maker/image.rb
Parent: | ImageFaviconBase

Methods

to_rss

Public Instance methods

to_rss(rss, current)

[Source]

# File rss/maker/image.rb, line 113
          def to_rss(rss, current)
            if @about and @image_size
              args = [@about, @image_size]
              favicon = ::RSS::ImageFaviconModel::Favicon.new(*args)
              setup_values(favicon)
              setup_other_elements(favicon)
              current.image_favicon = favicon
            end
          end


Class: RSS::Maker::RSS10::Channel::SkipDays

Class | RSS::Maker::RSS10::Channel::SkipDays
In: | 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)

[Source]

# File rss/maker/1.0.rb, line 80
          def to_rss(*args)
          end


Class: RSS::Maker::RSS10::Channel::SkipDays::Day

Class | RSS::Maker::RSS10::Channel::SkipDays::Day
In: | rss/maker/1.0.rb
Parent: | DayBase


Class: RSS::Maker::RSS10::Channel::SkipHours

Class | RSS::Maker::RSS10::Channel::SkipHours
In: | 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)

[Source]

# File rss/maker/1.0.rb, line 88
          def to_rss(*args)
          end


Class: RSS::Maker::RSS10::Channel::SkipHours::Hour

Class | RSS::Maker::RSS10::Channel::SkipHours::Hour
In: | rss/maker/1.0.rb
Parent: | HourBase


Class: RSS::Maker::RSS10::Image

Class | RSS::Maker::RSS10::Image
In: | rss/maker/dublincore.rb rss/maker/1.0.rb
Parent: | Object

Methods

have_required_values? to_rss

Public Instance methods

have_required_values?()

[Source]

# File 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)

[Source]

# File 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


Class: RSS::Maker::RSS10::Items

Class | RSS::Maker::RSS10::Items
In: | rss/maker/trackback.rb rss/maker/image.rb rss/maker/dublincore.rb 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)

[Source]

# File 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


Class: RSS::Maker::RSS10::Items::Item

Class | RSS::Maker::RSS10::Items::Item
In: | rss/maker/trackback.rb rss/maker/image.rb rss/maker/dublincore.rb 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?()

[Source]

# File rss/maker/1.0.rb, line 154
          def have_required_values?
            @title and @link
          end
to_rss(rss)

[Source]

# File 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


Class: RSS::Maker::RSS10::Items::Item::Categories

Class | RSS::Maker::RSS10::Items::Item::Categories
In: | 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)

[Source]

# File rss/maker/1.0.rb, line 174
            def to_rss(*args)
            end


Class: RSS::Maker::RSS10::Items::Item::Categories::Category

Class | RSS::Maker::RSS10::Items::Item::Categories::Category
In: | rss/maker/1.0.rb
Parent: | CategoryBase


Class: RSS::Maker::RSS10::Items::Item::Enclosure

Class | RSS::Maker::RSS10::Items::Item::Enclosure
In: | rss/maker/1.0.rb
Parent: | EnclosureBase

Methods

to_rss

Public Instance methods

to_rss(*args)

[Source]

# File rss/maker/1.0.rb, line 164
            def to_rss(*args)
            end


Class: RSS::Maker::RSS10::Items::Item::Guid

Class | RSS::Maker::RSS10::Items::Item::Guid
In: | rss/maker/1.0.rb
Parent: | GuidBase

Methods

to_rss

Public Instance methods

to_rss(*args)

[Source]

# File rss/maker/1.0.rb, line 159
            def to_rss(*args)
            end


Class: RSS::Maker::RSS10::Items::Item::ImageItem

Class | RSS::Maker::RSS10::Items::Item::ImageItem
In: | rss/maker/image.rb
Parent: | ImageItemBase

Methods

to_rss

Public Instance methods

to_rss(rss, current)

[Source]

# File rss/maker/image.rb, line 98
            def to_rss(rss, current)
              if @about
                item = ::RSS::ImageItemModel::Item.new(@about, @resource)
                setup_values(item)
                setup_other_elements(item)
                current.image_item = item
              end
            end


Class: RSS::Maker::RSS10::Items::Item::Source

Class | RSS::Maker::RSS10::Items::Item::Source
In: | rss/maker/1.0.rb
Parent: | SourceBase

Methods

to_rss

Public Instance methods

to_rss(*args)

[Source]

# File rss/maker/1.0.rb, line 169
            def to_rss(*args)
            end


Class: RSS::Maker::RSS10::Items::Item::TrackBackAbouts

Class | RSS::Maker::RSS10::Items::Item::TrackBackAbouts
In: | rss/maker/trackback.rb
Parent: | TrackBackAboutsBase

Classes and Modules

Class RSS::Maker::RSS10::Items::Item::TrackBackAbouts::About


Class: RSS::Maker::RSS10::Items::Item::TrackBackAbouts::About

Class | RSS::Maker::RSS10::Items::Item::TrackBackAbouts::About
In: | rss/maker/trackback.rb
Parent: | AboutBase

Methods

to_rss

Public Instance methods

to_rss(rss, current)

[Source]

# File rss/maker/trackback.rb, line 85
              def to_rss(rss, current)
                if resource
                  about = ::RSS::TrackBackModel10::About.new(resource)
                  current.trackback_abouts << about
                end
              end


Class: RSS::Maker::RSS10::Textinput

Class | RSS::Maker::RSS10::Textinput
In: | rss/maker/dublincore.rb rss/maker/1.0.rb
Parent: | Object

Methods

have_required_values? to_rss

Public Instance methods

have_required_values?()

[Source]

# File 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
to_rss(rss)

[Source]

# File 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


Class: RSS::Maker::RSS20

Class | RSS::Maker::RSS20
In: | rss/maker/trackback.rb 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")

[Source]

# File rss/maker/2.0.rb, line 10
      def initialize(rss_version="2.0")
        super
      end


Class: RSS::Maker::RSS20::Channel

Class | RSS::Maker::RSS20::Channel
In: | 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?()

[Source]

# File rss/maker/2.0.rb, line 16
        def have_required_values?
          @title and @link and @description
        end
required_variable_names()

[Source]

# File rss/maker/2.0.rb, line 20
        def required_variable_names
          %w(title link description)
        end


Class: RSS::Maker::RSS20::Channel::Categories

Class | RSS::Maker::RSS20::Channel::Categories
In: | 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)

[Source]

# File rss/maker/2.0.rb, line 51
          def to_rss(rss, channel)
            @categories.each do |category|
              category.to_rss(rss, channel)
            end
          end


Class: RSS::Maker::RSS20::Channel::Categories::Category

Class | RSS::Maker::RSS20::Channel::Categories::Category
In: | rss/maker/2.0.rb
Parent: | RSS09::Channel::Categories::Category

Methods

have_required_values? to_rss

Public Instance methods

have_required_values?()

[Source]

# File rss/maker/2.0.rb, line 67
            def have_required_values?
              @content
            end
to_rss(rss, channel)

[Source]

# File 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


Class: RSS::Maker::RSS20::Channel::Cloud

Class | RSS::Maker::RSS20::Channel::Cloud
In: | rss/maker/2.0.rb
Parent: | RSS09::Channel::Cloud

Methods

have_required_values? to_rss

Public Instance methods

have_required_values?()

[Source]

# File rss/maker/2.0.rb, line 44
          def have_required_values?
            @domain and @port and @path and
              @registerProcedure and @protocol
          end
to_rss(rss, channel)

[Source]

# File 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


Class: RSS::Maker::RSS20::Channel::SkipDays

Class | RSS::Maker::RSS20::Channel::SkipDays
In: | 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: | rss/maker/2.0.rb
Parent: | RSS09::Channel::SkipDays::Day


Class: RSS::Maker::RSS20::Channel::SkipHours

Class | RSS::Maker::RSS20::Channel::SkipHours
In: | 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: | rss/maker/2.0.rb
Parent: | RSS09::Channel::SkipHours::Hour


Class: RSS::Maker::RSS20::Image

Class | RSS::Maker::RSS20::Image
In: | rss/maker/2.0.rb
Parent: | RSS09::Image


Class: RSS::Maker::RSS20::Items

Class | RSS::Maker::RSS20::Items
In: | rss/maker/trackback.rb 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: | rss/maker/trackback.rb 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?()

[Source]

# File rss/maker/2.0.rb, line 82
          def have_required_values?
            @title or @description
          end


Class: RSS::Maker::RSS20::Items::Item::Categories

Class | RSS::Maker::RSS20::Items::Item::Categories
In: | 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)

[Source]

# File rss/maker/2.0.rb, line 137
            def to_rss(rss, item)
              @categories.each do |category|
                category.to_rss(rss, item)
              end
            end


Class: RSS::Maker::RSS20::Items::Item::Categories::Category

Class | RSS::Maker::RSS20::Items::Item::Categories::Category
In: | rss/maker/2.0.rb
Parent: | RSS09::Items::Item::Categories::Category

Methods

have_required_values? to_rss

Public Instance methods

have_required_values?()

[Source]

# File rss/maker/2.0.rb, line 153
              def have_required_values?
                @content
              end
to_rss(rss, item)

[Source]

# File 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


Class: RSS::Maker::RSS20::Items::Item::Enclosure

Class | RSS::Maker::RSS20::Items::Item::Enclosure
In: | rss/maker/2.0.rb
Parent: | RSS09::Items::Item::Enclosure

Methods

have_required_values? to_rss

Public Instance methods

have_required_values?()

[Source]

# File rss/maker/2.0.rb, line 116
            def have_required_values?
              @url and @length and @type
            end
to_rss(rss, item)

[Source]

# File 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


Class: RSS::Maker::RSS20::Items::Item::Guid

Class | RSS::Maker::RSS20::Items::Item::Guid
In: | rss/maker/2.0.rb
Parent: | RSS09::Items::Item::Guid

Methods

have_required_values? to_rss

Public Instance methods

have_required_values?()

[Source]

# File rss/maker/2.0.rb, line 101
            def have_required_values?
              @content
            end
to_rss(rss, item)

[Source]

# File 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


Class: RSS::Maker::RSS20::Items::Item::Source

Class | RSS::Maker::RSS20::Items::Item::Source
In: | rss/maker/2.0.rb
Parent: | RSS09::Items::Item::Source

Methods

have_required_values? to_rss

Public Instance methods

have_required_values?()

[Source]

# File rss/maker/2.0.rb, line 131
            def have_required_values?
              @url and @content
            end
to_rss(rss, item)

[Source]

# File 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


Class: RSS::Maker::RSS20::Items::Item::TrackBackAbouts

Class | RSS::Maker::RSS20::Items::Item::TrackBackAbouts
In: | rss/maker/trackback.rb
Parent: | TrackBackAboutsBase

Classes and Modules

Class RSS::Maker::RSS20::Items::Item::TrackBackAbouts::About


Class: RSS::Maker::RSS20::Items::Item::TrackBackAbouts::About

Class | RSS::Maker::RSS20::Items::Item::TrackBackAbouts::About
In: | rss/maker/trackback.rb
Parent: | AboutBase

Methods

to_rss

Public Instance methods

to_rss(rss, current)

[Source]

# File rss/maker/trackback.rb, line 115
              def to_rss(rss, current)
                if content
                  about = ::RSS::TrackBackModel20::About.new(content)
                  current.trackback_abouts << about
                end
              end


Class: RSS::Maker::RSS20::Textinput

Class | RSS::Maker::RSS20::Textinput
In: | rss/maker/2.0.rb
Parent: | RSS09::Textinput


Class: RSS::Maker::RSSBase

Class | RSS::Maker::RSSBase
In: | rss/maker/base.rb
Parent: | Object

Methods

make make new to_rss

Included Modules

Base

Attributes

encoding | [RW]
rss_version | [R]
standalone | [RW]
version | [RW]

Public Class methods

make(&block)

[Source]

# File rss/maker/base.rb, line 137
        def make(&block)
          new.make(&block)
        end
new(rss_version)

[Source]

# File 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

Public Instance methods

make() {|self| ...}

[Source]

# File rss/maker/base.rb, line 169
      def make
        if block_given?
          yield(self)
          to_rss
        else
          nil
        end
      end
to_rss()

[Source]

# File 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


Module: RSS::Maker::SyndicationModel

Module | RSS::Maker::SyndicationModel
In: | rss/maker/syndication.rb

Methods

append_features

Public Class methods

append_features(klass)

[Source]

# File 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


Class: RSS::Maker::TextinputBase

Class | RSS::Maker::TextinputBase
In: | rss/maker/dublincore.rb rss/maker/base.rb
Parent: | Object

Methods

current_element

Included Modules

DublinCoreModel Base

Public Instance methods

current_element(rss)

[Source]

# File rss/maker/base.rb, line 523
      def current_element(rss)
        rss.textinput
      end


Module: RSS::Maker::TrackBackModel

Module | RSS::Maker::TrackBackModel
In: | rss/maker/trackback.rb

Methods

append_features

Classes and Modules

Class RSS::Maker::TrackBackModel::TrackBackAboutsBase

Public Class methods

append_features(klass)

[Source]

# File 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


Class: RSS::Maker::TrackBackModel::TrackBackAboutsBase

Class | RSS::Maker::TrackBackModel::TrackBackAboutsBase
In: | rss/maker/trackback.rb
Parent: | Object

Methods

new_about to_rss

Included Modules

Base

Classes and Modules

Class RSS::Maker::TrackBackModel::TrackBackAboutsBase::AboutBase

Public Instance methods

new_about()

[Source]

# File rss/maker/trackback.rb, line 45
        def new_about
          about = self.class::About.new(@maker)
          @abouts << about
          about
        end
to_rss(rss, current)

[Source]

# File rss/maker/trackback.rb, line 51
        def to_rss(rss, current)
          @abouts.each do |about|
            about.to_rss(rss, current)
          end
        end


Class: RSS::Maker::TrackBackModel::TrackBackAboutsBase::AboutBase

Class | RSS::Maker::TrackBackModel::TrackBackAboutsBase::AboutBase
In: | 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?()

[Source]

# File rss/maker/trackback.rb, line 68
          def have_required_values?
            @value
          end


Class: RSS::Maker::XMLStyleSheets

Class | RSS::Maker::XMLStyleSheets
In: | 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()

[Source]

# File rss/maker/base.rb, line 209
      def new_xml_stylesheet
        xss = XMLStyleSheet.new(@maker)
        @xml_stylesheets << xss
        xss
      end
to_rss(rss)

[Source]

# File rss/maker/base.rb, line 203
      def to_rss(rss)
        @xml_stylesheets.each do |xss|
          xss.to_rss(rss)
        end
      end


Class: RSS::Maker::XMLStyleSheets::XMLStyleSheet

Class | RSS::Maker::XMLStyleSheets::XMLStyleSheet
In: | rss/maker/base.rb
Parent: | Object

Methods

have_required_values? to_rss

Included Modules

Base

Public Instance methods

have_required_values?()

[Source]

# File rss/maker/base.rb, line 232
        def have_required_values?
          @href and @type
        end
to_rss(rss)

[Source]

# File rss/maker/base.rb, line 223
        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


Class: RSS::MissingAttributeError

Class | RSS::MissingAttributeError
In: | rss/rss.rb
Parent: | InvalidRSSError

Methods

new

Attributes

attribute | [R]
tag | [R]

Public Class methods

new(tag, attribute)

[Source]

# File rss/rss.rb, line 97
    def initialize(tag, attribute)
      @tag, @attribute = tag, attribute
      super("attribute <#{attribute}> is missing in tag <#{tag}>")
    end


Class: RSS::MissingTagError

Class | RSS::MissingTagError
In: | rss/rss.rb
Parent: | InvalidRSSError

Methods

new

Attributes

parent | [R]
tag | [R]

Public Class methods

new(tag, parent)

[Source]

# File rss/rss.rb, line 81
    def initialize(tag, parent)
      @tag, @parent = tag, parent
      super("tag <#{tag}> is missing in tag <#{parent}>")
    end


Class: RSS::NSError

Class | RSS::NSError
In: | rss/parser.rb
Parent: | InvalidRSSError

Methods

new

Attributes

prefix | [R]
tag | [R]
uri | [R]

Public Class methods

new(tag, prefix, require_uri)

[Source]

# File rss/parser.rb, line 39
    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


Class: RSS::NotAvailableValueError

Class | RSS::NotAvailableValueError
In: | rss/rss.rb
Parent: | InvalidRSSError

Methods

new

Attributes

tag | [R]
value | [R]

Public Class methods

new(tag, value)

[Source]

# File rss/rss.rb, line 121
    def initialize(tag, value)
      @tag, @value = tag, value
      super("value <#{value}> of tag <#{tag}> is not available.")
    end


Class: RSS::NotExceptedTagError

Class | RSS::NotExceptedTagError
In: | rss/rss.rb
Parent: | InvalidRSSError

Methods

new

Attributes

parent | [R]
tag | [R]

Public Class methods

new(tag, parent)

[Source]

# File rss/rss.rb, line 113
    def initialize(tag, parent)
      @tag, @parent = tag, parent
      super("tag <#{tag}> is not expected in tag <#{parent}>")
    end


Class: RSS::NotSetError

Class | RSS::NotSetError
In: | rss/rss.rb
Parent: | Error

Methods

new

Attributes

name | [R]
variables | [R]

Public Class methods

new(name, variables)

[Source]

# File rss/rss.rb, line 150
    def initialize(name, variables)
      @name = name
      @variables = variables
      super("required variables of #{@name} are not set: #{@variables.join(', ')}")
    end


Class: RSS::NotValidXMLParser

Class | RSS::NotValidXMLParser
In: | rss/parser.rb
Parent: | Error

Methods

new

Public Class methods

new(parser)

[Source]

# File rss/parser.rb, line 30
    def initialize(parser)
      super("#{parser} is not available XML parser. " <<
            "available XML parser is " <<
            "#{AVAILABLE_PARSERS.inspect}.")
    end


Class: RSS::NotWellFormedError

Class | RSS::NotWellFormedError
In: | rss/parser.rb
Parent: | Error

Methods

new

Attributes

element | [R]
line | [R]

Public Class methods

new(line=nil, element=nil)

[Source]

# File rss/parser.rb, line 10
    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


Class: RSS::OverlappedPrefixError

Class | RSS::OverlappedPrefixError
In: | rss/rss.rb
Parent: | Error

Methods

new

Attributes

prefix [R]

Public Class methods

new(prefix)

[Source]

# File rss/rss.rb, line 72
    def initialize(prefix)
      @prefix = prefix
    end


Class: RSS::Parser

Class | RSS::Parser
In: | rss/parser.rb
Parent: | Object

Methods

default_parser default_parser= new parse

Public Class methods

default_parser()

[Source]

# File rss/parser.rb, line 54
      def default_parser
        @@default_parser || AVAILABLE_PARSERS.first
      end
default_parser=(new_value)

[Source]

# File rss/parser.rb, line 58
      def default_parser=(new_value)
        if AVAILABLE_PARSERS.include?(new_value)
          @@default_parser = new_value
        else
          raise NotValidXMLParser.new(new_value)
        end
      end
new(rss, parser_class=self.class.default_parser)

[Source]

# File rss/parser.rb, line 80
    def initialize(rss, parser_class=self.class.default_parser)
      @parser = parser_class.new(normalize_rss(rss))
    end
parse(rss, do_validate=true, ignore_unknown_element=true, parser_class=default_parser)

[Source]

# File rss/parser.rb, line 66
      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


Class: RSS::RDF

Class | RSS::RDF
In: | rss/trackback.rb rss/syndication.rb rss/image.rb rss/dublincore.rb rss/content.rb rss/1.0.rb
Parent: | Object

Methods

full_name new required_uri to_s

Included Modules

RSS10 RootElementMixin

Classes and Modules

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)

[Source]

# File rss/1.0.rb, line 55
    def initialize(version=nil, encoding=nil, standalone=nil)
      super('1.0', version, encoding, standalone)
    end
required_uri()

[Source]

# File rss/1.0.rb, line 24
      def required_uri
        URI
      end

Public Instance methods

full_name()

[Source]

# File rss/1.0.rb, line 59
    def full_name
      tag_name_with_prefix(PREFIX)
    end
to_s(need_convert=true, indent=calc_indent)

[Source]

# File rss/1.0.rb, line 63
    def to_s(need_convert=true, indent=calc_indent)
      rv = tag(indent, ns_declarations) do |next_indent|
        [
          channel_element(false, next_indent),
          image_element(false, next_indent),
          item_elements(false, next_indent),
          textinput_element(false, next_indent),
          other_element(false, next_indent),
        ]
      end
      rv = convert(rv) if need_convert
      rv
    end


Class: RSS::RDF::Channel

Class | RSS::RDF::Channel
In: | rss/syndication.rb rss/image.rb rss/dublincore.rb rss/1.0.rb
Parent: | Object

Methods

new required_uri to_s

Included Modules

SyndicationModel ImageFaviconModel DublinCoreModel RSS10

Classes and Modules

Class RSS::RDF::Channel::Image
Class RSS::RDF::Channel::Items
Class RSS::RDF::Channel::Textinput

Public Class methods

new(about=nil)

[Source]

# File rss/1.0.rb, line 232
      def initialize(about=nil)
        super()
        @about = about
      end
required_uri()

[Source]

# File rss/1.0.rb, line 201
        def required_uri
          ::RSS::URI
        end

Public Instance methods

to_s(need_convert=true, indent=calc_indent)

[Source]

# File rss/1.0.rb, line 237
      def to_s(need_convert=true, indent=calc_indent)
        rv = tag(indent) do |next_indent|
          [
            title_element(false, next_indent),
            link_element(false, next_indent),
            description_element(false, next_indent),
            image_element(false, next_indent),
            items_element(false, next_indent),
            textinput_element(false, next_indent),
            other_element(false, next_indent),
          ]
        end
        rv = convert(rv) if need_convert
        rv
      end


Class: RSS::RDF::Channel::Image

Class | RSS::RDF::Channel::Image
In: | rss/1.0.rb
Parent: | Element

Methods

new required_uri to_s

Included Modules

RSS10

Public Class methods

new(resource=nil)

[Source]

# File rss/1.0.rb, line 303
        def initialize(resource=nil)
          super()
          @resource = resource
        end
required_uri()

[Source]

# File rss/1.0.rb, line 291
          def required_uri
            ::RSS::URI
          end

Public Instance methods

to_s(need_convert=true, indent=calc_indent)

[Source]

# File rss/1.0.rb, line 308
        def to_s(need_convert=true, indent=calc_indent)
          rv = tag(indent)
          rv = convert(rv) if need_convert
          rv
        end


Class: RSS::RDF::Channel::Items

Class | RSS::RDF::Channel::Items
In: | rss/1.0.rb
Parent: | Element

Methods

new required_uri to_s

Included Modules

RSS10

Classes and Modules

Class RSS::RDF::Channel::Items::Seq

Constants

Seq = ::RSS::RDF::Seq

Public Class methods

new(seq=Seq.new)

[Source]

# File rss/1.0.rb, line 382
        def initialize(seq=Seq.new)
          super()
          @Seq = seq
        end
required_uri()

[Source]

# File rss/1.0.rb, line 372
          def required_uri
            ::RSS::URI
          end

Public Instance methods

to_s(need_convert=true, indent=calc_indent)

[Source]

# File rss/1.0.rb, line 387
        def to_s(need_convert=true, indent=calc_indent)
          rv = tag(indent) do |next_indent|
            [
              Seq_element(need_convert, next_indent),
              other_element(need_convert, next_indent),
            ]
          end
        end


Class: RSS::RDF::Channel::Items::Seq

Class | RSS::RDF::Channel::Items::Seq
In: | rss/1.0.rb
Parent: | Object

Constants

Li = ::RSS::RDF::Li


Class: RSS::RDF::Channel::Textinput

Class | RSS::RDF::Channel::Textinput
In: | rss/1.0.rb
Parent: | Element

Methods

new required_uri to_s

Included Modules

RSS10

Public Class methods

new(resource=nil)

[Source]

# File rss/1.0.rb, line 340
        def initialize(resource=nil)
          super()
          @resource = resource
        end
required_uri()

[Source]

# File rss/1.0.rb, line 328
          def required_uri
            ::RSS::URI
          end

Public Instance methods

to_s(need_convert=true, indent=calc_indent)

[Source]

# File rss/1.0.rb, line 345
        def to_s(need_convert=true, indent=calc_indent)
          rv = tag(indent)
          rv = convert(rv) if need_convert
          rv
        end


Class: RSS::RDF::Image

Class | RSS::RDF::Image
In: | rss/dublincore.rb rss/1.0.rb
Parent: | Object

Methods

new required_uri to_s

Included Modules

DublinCoreModel RSS10

Public Class methods

new(about=nil)

[Source]

# File rss/1.0.rb, line 446
      def initialize(about=nil)
        super()
        @about = about
      end
required_uri()

[Source]

# File rss/1.0.rb, line 422
        def required_uri
          ::RSS::URI
        end

Public Instance methods

to_s(need_convert=true, indent=calc_indent)

[Source]

# File rss/1.0.rb, line 451
      def to_s(need_convert=true, indent=calc_indent)
        rv = tag(indent) do |next_indent|
          [
            title_element(false, next_indent),
            url_element(false, next_indent),
            link_element(false, next_indent),
            other_element(false, next_indent),
          ]
        end
        rv = convert(rv) if need_convert
        rv
      end


Class: RSS::RDF::Item

Class | RSS::RDF::Item
In: | rss/trackback.rb rss/image.rb rss/dublincore.rb rss/content.rb rss/1.0.rb
Parent: | Object

Methods

new required_uri to_s

Included Modules

TrackBackModel10 ImageItemModel DublinCoreModel ContentModel RSS10

Public Class methods

new(about=nil)

[Source]

# File rss/1.0.rb, line 516
      def initialize(about=nil)
        super()
        @about = about
      end
required_uri()

[Source]

# File rss/1.0.rb, line 492
        def required_uri
          ::RSS::URI
        end

Public Instance methods

to_s(need_convert=true, indent=calc_indent)

[Source]

# File rss/1.0.rb, line 521
      def to_s(need_convert=true, indent=calc_indent)
        rv = tag(indent) do |next_indent|
          [
            title_element(false, next_indent),
            link_element(false, next_indent),
            description_element(false, next_indent),
            other_element(false, next_indent),
          ]
        end
        rv = convert(rv) if need_convert
        rv
      end


Class: RSS::RDF::Li

Class | RSS::RDF::Li
In: | rss/1.0.rb
Parent: | Element

Methods

full_name new required_uri to_s

Included Modules

RSS10

Public Class methods

new(resource=nil)

[Source]

# File rss/1.0.rb, line 171
      def initialize(resource=nil)
        super()
        @resource = resource
      end
required_uri()

[Source]

# File rss/1.0.rb, line 159
        def required_uri
          URI
        end

Public Instance methods

full_name()

[Source]

# File rss/1.0.rb, line 176
      def full_name
        tag_name_with_prefix(PREFIX)
      end
to_s(need_convert=true, indent=calc_indent)

[Source]

# File rss/1.0.rb, line 180
      def to_s(need_convert=true, indent=calc_indent)
        rv = tag(indent)
        rv = convert(rv) if need_convert
        rv
      end


Class: RSS::RDF::Seq

Class | RSS::RDF::Seq
In: | rss/1.0.rb
Parent: | Element

Methods

full_name new required_uri to_s

Included Modules

RSS10

Public Class methods

new(li=[])

[Source]

# File rss/1.0.rb, line 116
      def initialize(li=[])
        super()
        @li = li
      end
required_uri()

[Source]

# File rss/1.0.rb, line 104
        def required_uri
          URI
        end

Public Instance methods

full_name()

[Source]

# File rss/1.0.rb, line 130
      def full_name
        tag_name_with_prefix(PREFIX)
      end
to_s(need_convert=true, indent=calc_indent)

[Source]

# File rss/1.0.rb, line 121
      def to_s(need_convert=true, indent=calc_indent)
        tag(indent) do |next_indent|
          [
            li_elements(need_convert, next_indent),
            other_element(need_convert, next_indent),
          ]
        end
      end


Class: RSS::RDF::Textinput

Class | RSS::RDF::Textinput
In: | rss/dublincore.rb rss/1.0.rb
Parent: | Object

Methods

new required_uri to_s

Included Modules

DublinCoreModel RSS10

Public Class methods

new(about=nil)

[Source]

# File rss/1.0.rb, line 587
      def initialize(about=nil)
        super()
        @about = about
      end
required_uri()

[Source]

# File rss/1.0.rb, line 562
        def required_uri
          ::RSS::URI
        end

Public Instance methods

to_s(need_convert=true, indent=calc_indent)

[Source]

# File rss/1.0.rb, line 592
      def to_s(need_convert=true, indent=calc_indent)
        rv = tag(indent) do |next_indent|
          [
            title_element(false, next_indent),
            description_element(false, next_indent),
            name_element(false, next_indent),
            link_element(false, next_indent),
            other_element(false, next_indent),
          ]
        end
        rv = convert(rv) if need_convert
        rv
      end


Class: RSS::REXMLLikeXMLParser

Class | RSS::REXMLLikeXMLParser
In: | rss/xmlparser.rb
Parent: | ::XML::Parser

Methods

character endElement listener= processingInstruction startElement xmlDecl

Included Modules

::XML::Encoding_ja

Public Instance methods

character(data)

[Source]

# File rss/xmlparser.rb, line 46
    def character(data)
      @listener.text(data)
    end
endElement(name)

[Source]

# File rss/xmlparser.rb, line 42
    def endElement(name)
      @listener.tag_end(name)
    end
listener=(listener)

[Source]

# File rss/xmlparser.rb, line 34
    def listener=(listener)
      @listener = listener
    end
processingInstruction(target, content)

[Source]

# File rss/xmlparser.rb, line 54
    def processingInstruction(target, content)
      @listener.instruction(target, content)
    end
startElement(name, attrs)

[Source]

# File rss/xmlparser.rb, line 38
    def startElement(name, attrs)
      @listener.tag_start(name, attrs)
    end
xmlDecl(version, encoding, standalone)

[Source]

# File rss/xmlparser.rb, line 50
    def xmlDecl(version, encoding, standalone)
      @listener.xmldecl(version, encoding, standalone == 1)
    end


Class: RSS::REXMLListener

Class | RSS::REXMLListener
In: | rss/rexmlparser.rb
Parent: | BaseListener

Methods

xmldecl

Included Modules

REXML::StreamListener ListenerMixin

External Aliases

text -> cdata

Public Instance methods

xmldecl(version, encoding, standalone)

[Source]

# File rss/rexmlparser.rb, line 38
    def xmldecl(version, encoding, standalone)
      super(version, encoding, standalone == "yes")
      # Encoding is converted to UTF-8 when REXML parse XML.
      @encoding = 'UTF-8'
    end


Class: RSS::REXMLParser

Class | RSS::REXMLParser
In: | rss/rexmlparser.rb
Parent: | BaseParser


Module: RSS::RSS09

Module | RSS::RSS09
In: | rss/0.9.rb

Methods

append_features

Constants

NSPOOL | = | {}
ELEMENTS | = | []

Public Class methods

append_features(klass)

[Source]

# File rss/0.9.rb, line 9
    def self.append_features(klass)
      super

      klass.install_must_call_validator('', nil)
    end


Module: RSS::RSS10

Module | RSS::RSS10
In: | rss/1.0.rb

Methods

append_features

Constants

NSPOOL | = | {}
ELEMENTS | = | []

Public Class methods

append_features(klass)

[Source]

# File rss/1.0.rb, line 9
    def self.append_features(klass)
      super

      klass.install_must_call_validator('', ::RSS::URI)
    end


Module: RSS::RootElementMixin

Module | RSS::RootElementMixin
In: | rss/rss.rb

Methods

new output_encoding= setup_maker

Included Modules

XMLStyleSheetMixin

Attributes

output_encoding [R]

Public Class methods

new(rss_version, version=nil, encoding=nil, standalone=nil)

[Source]

# File rss/rss.rb, line 853
    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

Public Instance methods

output_encoding=(enc)

[Source]

# File rss/rss.rb, line 862
    def output_encoding=(enc)
      @output_encoding = enc
      self.converter = Converter.new(@output_encoding, @encoding)
    end
setup_maker(maker)

[Source]

# File rss/rss.rb, line 867
    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


Class: RSS::Rss

Class | RSS::Rss
In: | rss/trackback.rb rss/2.0.rb rss/0.9.rb
Parent: | Object

Methods

image items new textinput to_s

Included Modules

RSS09 RootElementMixin XMLStyleSheetMixin

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)

[Source]

# File rss/0.9.rb, line 34
    def initialize(rss_version, version=nil, encoding=nil, standalone=nil)
      super
    end

Public Instance methods

image()

[Source]

# File rss/0.9.rb, line 46
    def image
      if @channel
        @channel.image
      else
        nil
      end
    end
items()

[Source]

# File rss/0.9.rb, line 38
    def items
      if @channel
        @channel.items
      else
        []
      end
    end
textinput()

[Source]

# File rss/0.9.rb, line 54
    def textinput
      if @channel
        @channel.textInput
      else
        nil
      end
    end
to_s(need_convert=true, indent=calc_indent)

[Source]

# File rss/0.9.rb, line 62
    def to_s(need_convert=true, indent=calc_indent)
      rv = tag(indent, ns_declarations) do |next_indent|
        [
          channel_element(false, next_indent),
          other_element(false, next_indent),
        ]
      end
      rv = convert(rv) if need_convert
      rv
    end


Class: RSS::Rss::Channel

Class | RSS::Rss::Channel
In: | rss/trackback.rb rss/2.0.rb rss/0.9.rb
Parent: | Object

Methods

new other_element to_s ttl=

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

children | -> | children09
_tags | -> | _tags09
pubDate | -> | date
pubDate= | -> | date=

Public Class methods

new()

[Source]

# File rss/0.9.rb, line 145
      def initialize()
        super()
      end

Public Instance methods

other_element(need_convert, indent)

[Source]

# File rss/2.0.rb, line 33
      def other_element(need_convert, indent)
        rv = "\#{category_elements(need_convert, indent)}\n\#{generator_element(need_convert, indent)}\n\#{ttl_element(need_convert, indent)}\n"
        rv << super
      end
to_s(need_convert=true, indent=calc_indent)

[Source]

# File rss/0.9.rb, line 149
      def to_s(need_convert=true, indent=calc_indent)
        rv = tag(indent) do |next_indent|
          [
            title_element(false, next_indent),
            link_element(false, next_indent),
            description_element(false, next_indent),
            language_element(false, next_indent),
            copyright_element(false, next_indent),
            managingEditor_element(false, next_indent),
            webMaster_element(false, next_indent),
            rating_element(false, next_indent),
            pubDate_element(false, next_indent),
            lastBuildDate_element(false, next_indent),
            docs_element(false, next_indent),
            cloud_element(false, next_indent),
            skipDays_element(false, next_indent),
            skipHours_element(false, next_indent),
            image_element(false, next_indent),
            item_elements(false, next_indent),
            textInput_element(false, next_indent),
            other_element(false, next_indent),
          ]
        end
        rv = convert(rv) if need_convert
        rv
      end
ttl=(value)

[Source]

# File rss/2.0.rb, line 15
      def ttl=(value)
        @ttl = value.to_i
      end


Class: RSS::Rss::Channel::Cloud

Class | RSS::Rss::Channel::Cloud
In: | rss/0.9.rb
Parent: | Element

Methods

new to_s

Included Modules

RSS09

Public Class methods

new(domain=nil, port=nil, path=nil, rp=nil, protocol=nil)

[Source]

# File rss/0.9.rb, line 386
        def initialize(domain=nil, port=nil, path=nil, rp=nil, protocol=nil)
          super()
          @domain = domain
          @port = port
          @path = path
          @registerProcedure = rp
          @protocol = protocol
        end

Public Instance methods

to_s(need_convert=true, indent=calc_indent)

[Source]

# File rss/0.9.rb, line 395
        def to_s(need_convert=true, indent=calc_indent)
          rv = tag(indent)
          rv = convert(rv) if need_convert
          rv
        end


Class: RSS::Rss::Channel::Image

Class | RSS::Rss::Channel::Image
In: | rss/0.9.rb
Parent: | Element

Methods

to_s

Included Modules

RSS09

Public Instance methods

to_s(need_convert=true, indent=calc_indent)

[Source]

# File rss/0.9.rb, line 342
        def to_s(need_convert=true, indent=calc_indent)
          rv = tag(indent) do |next_indent|
            [
              url_element(false, next_indent),
              title_element(false, next_indent),
              link_element(false, next_indent),
              width_element(false, next_indent),
              height_element(false, next_indent),
              description_element(false, next_indent),
              other_element(false, next_indent),
            ]
          end
          rv = convert(rv) if need_convert
          rv
        end


Class: RSS::Rss::Channel::Item

Class | RSS::Rss::Channel::Item
In: | rss/trackback.rb rss/2.0.rb rss/0.9.rb
Parent: | Object

Methods

other_element to_s

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=
children | -> | children09
_tags | -> | _tags09
setup_maker_element | -> | _setup_maker_element

Public Instance methods

other_element(need_convert, indent)

[Source]

# File rss/2.0.rb, line 92
        def other_element(need_convert, indent)
          rv = [
            super,
            *%w(author comments pubDate guid).collect do |name|
              __send__("#{name}_element", false, indent)
            end
          ].reject do |value|
            /\A\s*\z/.match(value)
          end
          rv.join("\n")
        end
to_s(need_convert=true, indent=calc_indent)

[Source]

# File rss/0.9.rb, line 439
        def to_s(need_convert=true, indent=calc_indent)
          rv = tag(indent) do |next_indent|
            [
              title_element(false, next_indent),
              link_element(false, next_indent),
              description_element(false, next_indent),
              category_elements(false, next_indent),
              source_element(false, next_indent),
              enclosure_element(false, next_indent),
              other_element(false, next_indent),
            ]
          end
          rv = convert(rv) if need_convert
          rv
        end


Class: RSS::Rss::Channel::Item::Category

Class | RSS::Rss::Channel::Item::Category
In: | rss/0.9.rb
Parent: | Element

Methods

new

Included Modules

RSS09

Public Class methods

new(domain=nil, content=nil)

[Source]

# File rss/0.9.rb, line 582
          def initialize(domain=nil, content=nil)
            super()
            @domain = domain
            @content = content
          end


Class: RSS::Rss::Channel::Item::Enclosure

Class | RSS::Rss::Channel::Item::Enclosure
In: | rss/0.9.rb
Parent: | Element

Methods

new to_s

Included Modules

RSS09

Public Class methods

new(url=nil, length=nil, type=nil)

[Source]

# File rss/0.9.rb, line 537
          def initialize(url=nil, length=nil, type=nil)
            super()
            @url = url
            @length = length
            @type = type
          end

Public Instance methods

to_s(need_convert=true, indent=calc_indent)

[Source]

# File rss/0.9.rb, line 544
          def to_s(need_convert=true, indent=calc_indent)
            rv = tag(indent)
            rv = convert(rv) if need_convert
            rv
          end


Class: RSS::Rss::Channel::Item::Guid

Class | RSS::Rss::Channel::Item::Guid
In: | rss/2.0.rb
Parent: | Element

Methods

new

Included Modules

RSS09

Public Class methods

new(isPermaLink=nil, content=nil)

[Source]

# File rss/2.0.rb, line 137
          def initialize(isPermaLink=nil, content=nil)
            super()
            @isPermaLink = isPermaLink
            @content = content
          end


Class: RSS::Rss::Channel::Item::Source

Class | RSS::Rss::Channel::Item::Source
In: | rss/0.9.rb
Parent: | Element

Methods

new

Included Modules

RSS09

Public Class methods

new(url=nil, content=nil)

[Source]

# File rss/0.9.rb, line 497
          def initialize(url=nil, content=nil)
            super()
            @url = url
            @content = content
          end


Class: RSS::Rss::Channel::SkipDays

Class | RSS::Rss::Channel::SkipDays
In: | rss/0.9.rb
Parent: | Element

Methods

to_s

Included Modules

RSS09

Classes and Modules

Class RSS::Rss::Channel::SkipDays::Day

Public Instance methods

to_s(need_convert=true, indent=calc_indent)

[Source]

# File rss/0.9.rb, line 244
        def to_s(need_convert=true, indent=calc_indent)
          rv = tag(indent) do |next_indent|
            [
              day_elements(false, next_indent)
            ]
          end
          rv = convert(rv) if need_convert
          rv
        end


Class: RSS::Rss::Channel::SkipDays::Day

Class | RSS::Rss::Channel::SkipDays::Day
In: | rss/0.9.rb
Parent: | Element

Methods

new

Included Modules

RSS09

Public Class methods

new(content=nil)

[Source]

# File rss/0.9.rb, line 270
          def initialize(content=nil)
            super()
            @content = content
          end


Class: RSS::Rss::Channel::SkipHours

Class | RSS::Rss::Channel::SkipHours
In: | rss/0.9.rb
Parent: | Element

Methods

to_s

Included Modules

RSS09

Classes and Modules

Class RSS::Rss::Channel::SkipHours::Hour

Public Instance methods

to_s(need_convert=true, indent=calc_indent)

[Source]

# File rss/0.9.rb, line 289
        def to_s(need_convert=true, indent=calc_indent)
          rv = tag(indent) do |next_indent|
            [
              hour_elements(false, next_indent)
            ]
          end
          rv = convert(rv) if need_convert
          rv
        end


Class: RSS::Rss::Channel::SkipHours::Hour

Class | RSS::Rss::Channel::SkipHours::Hour
In: | rss/0.9.rb
Parent: | Element

Methods

content= new

Included Modules

RSS09

Public Class methods

new(content=nil)

[Source]

# File rss/0.9.rb, line 315
          def initialize(content=nil)
            super()
            @content = content
          end

Public Instance methods

content=(value)

[Source]

# File rss/0.9.rb, line 321
          def content=(value)
            @content = value.to_i
          end


Class: RSS::Rss::Channel::TextInput

Class | RSS::Rss::Channel::TextInput
In: | rss/0.9.rb
Parent: | Element

Methods

to_s

Included Modules

RSS09

Public Instance methods

to_s(need_convert=true, indent=calc_indent)

[Source]

# File rss/0.9.rb, line 617
        def to_s(need_convert=true, indent=calc_indent)
          rv = tag(indent) do |next_indent|
            [
              title_element(false, next_indent),
              description_element(false, next_indent),
              name_element(false, next_indent),
              link_element(false, next_indent),
              other_element(false, next_indent),
            ]
          end
          rv = convert(rv) if need_convert
          rv
        end


Module: RSS::SyndicationModel

Module | RSS::SyndicationModel
In: | rss/syndication.rb

Methods

append_features sy_validate

Constants

ELEMENTS | = | []
SY_UPDATEPERIOD_AVAILABLE_VALUES | = | %w(hourly daily weekly monthly yearly)
SY_UPDATEFREQUENCY_AVAILABLE_RE | = | /\A\s*\+?\d+\s*\z/

Public Class methods

append_features(klass)

[Source]

# File rss/syndication.rb, line 16
    def self.append_features(klass)
      super

      klass.module_eval("%w(updatePeriod updateFrequency).each do |name|\ninstall_text_element(\"\\\#{SY_PREFIX}_\\\#{name}\")\nend\n\n%w(updateBase).each do |name|\ninstall_date_element(\"\\\#{SY_PREFIX}_\\\#{name}\", 'w3cdtf', name)\nend\n\nalias_method(:_sy_updatePeriod=, :sy_updatePeriod=)\ndef sy_updatePeriod=(new_value)\nnew_value = new_value.strip\nvalidate_sy_updatePeriod(new_value) if @do_validate\nself._sy_updatePeriod = new_value\nend\n\nalias_method(:_sy_updateFrequency=, :sy_updateFrequency=)\ndef sy_updateFrequency=(new_value)\nvalidate_sy_updateFrequency(new_value) if @do_validate\nself._sy_updateFrequency = new_value.to_i\nend\n", *get_file_and_line_from_caller(1))
    end

Public Instance methods

sy_validate(tags)

[Source]

# File rss/syndication.rb, line 44
    def sy_validate(tags)
      counter = {}
      ELEMENTS.each do |name|
        counter[name] = 0
      end

      tags.each do |tag|
        key = "#{SY_PREFIX}_#{tag}"
        raise UnknownTagError.new(tag, SY_URI)  unless counter.has_key?(key)
        counter[key] += 1
        raise TooMuchTagError.new(tag, tag_name) if counter[key] > 1
      end
    end


Module: RSS::TaxonomyModel

Module | RSS::TaxonomyModel
In: | rss/taxonomy.rb


Class: RSS::TextInput

Class | RSS::TextInput
In: | rss/taxonomy.rb
Parent: | Object


Class: RSS::TooMuchTagError

Class | RSS::TooMuchTagError
In: | rss/rss.rb
Parent: | InvalidRSSError

Methods

new

Attributes

parent | [R]
tag | [R]

Public Class methods

new(tag, parent)

[Source]

# File rss/rss.rb, line 89
    def initialize(tag, parent)
      @tag, @parent = tag, parent
      super("tag <#{tag}> is too much in tag <#{parent}>")
    end


Module: RSS::TrackBackModel10

Module | RSS::TrackBackModel10
In: | rss/trackback.rb

Classes and Modules

Class RSS::TrackBackModel10::About
Class RSS::TrackBackModel10::Ping


Class: RSS::TrackBackModel10::About

Class | RSS::TrackBackModel10::About
In: | rss/trackback.rb
Parent: | Element

Methods

full_name new required_prefix required_uri to_s

Included Modules

RSS10

External Aliases

resource | -> | value
resource= | -> | value=

Public Class methods

new(resource=nil)

[Source]

# File rss/trackback.rb, line 182
      def initialize(resource=nil)
        super()
        @resource = resource
      end
required_prefix()

[Source]

# File rss/trackback.rb, line 163
        def required_prefix
          TRACKBACK_PREFIX
        end
required_uri()

[Source]

# File rss/trackback.rb, line 167
        def required_uri
          TRACKBACK_URI
        end

Public Instance methods

full_name()

[Source]

# File rss/trackback.rb, line 187
      def full_name
        tag_name_with_prefix(TRACKBACK_PREFIX)
      end
to_s(need_convert=true, indent=calc_indent)

[Source]

# File rss/trackback.rb, line 191
      def to_s(need_convert=true, indent=calc_indent)
        rv = tag(indent)
        rv = convert(rv) if need_convert
        rv
      end


Class: RSS::TrackBackModel10::Ping

Class | RSS::TrackBackModel10::Ping
In: | rss/trackback.rb
Parent: | Element

Methods

full_name new required_prefix required_uri to_s

Included Modules

RSS10

External Aliases

resource | -> | value
resource= | -> | value=

Public Class methods

new(resource=nil)

[Source]

# File rss/trackback.rb, line 134
      def initialize(resource=nil)
        super()
        @resource = resource
      end
required_prefix()

[Source]

# File rss/trackback.rb, line 115
        def required_prefix
          TRACKBACK_PREFIX
        end
required_uri()

[Source]

# File rss/trackback.rb, line 119
        def required_uri
          TRACKBACK_URI
        end

Public Instance methods

full_name()

[Source]

# File rss/trackback.rb, line 139
      def full_name
        tag_name_with_prefix(TRACKBACK_PREFIX)
      end
to_s(need_convert=true, indent=calc_indent)

[Source]

# File rss/trackback.rb, line 143
      def to_s(need_convert=true, indent=calc_indent)
        rv = tag(indent)
        rv = convert(rv) if need_convert
        rv
      end


Module: RSS::TrackBackModel20

Module | RSS::TrackBackModel20
In: | rss/trackback.rb

Classes and Modules

Class RSS::TrackBackModel20::About
Class RSS::TrackBackModel20::Ping


Class: RSS::TrackBackModel20::About

Class | RSS::TrackBackModel20::About
In: | 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(content=nil)

[Source]

# File rss/trackback.rb, line 270
      def initialize(content=nil)
        super()
        @content = content
      end
required_prefix()

[Source]

# File rss/trackback.rb, line 257
        def required_prefix
          TRACKBACK_PREFIX
        end
required_uri()

[Source]

# File rss/trackback.rb, line 261
        def required_uri
          TRACKBACK_URI
        end

Public Instance methods

full_name()

[Source]

# File rss/trackback.rb, line 275
      def full_name
        tag_name_with_prefix(TRACKBACK_PREFIX)
      end


Class: RSS::TrackBackModel20::Ping

Class | RSS::TrackBackModel20::Ping
In: | 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(content=nil)

[Source]

# File rss/trackback.rb, line 239
      def initialize(content=nil)
        super()
        @content = content
      end
required_prefix()

[Source]

# File rss/trackback.rb, line 226
        def required_prefix
          TRACKBACK_PREFIX
        end
required_uri()

[Source]

# File rss/trackback.rb, line 230
        def required_uri
          TRACKBACK_URI
        end

Public Instance methods

full_name()

[Source]

# File rss/trackback.rb, line 244
      def full_name
        tag_name_with_prefix(TRACKBACK_PREFIX)
      end


Module: RSS::TrackBackUtils

Module | RSS::TrackBackUtils
In: | rss/trackback.rb


Class: RSS::UnknownConversionMethodError

Class | RSS::UnknownConversionMethodError
In: | rss/rss.rb
Parent: | Error

Methods

new

Attributes

from | [R]
to | [R]

Public Class methods

new(to, from)

[Source]

# File rss/rss.rb, line 129
    def initialize(to, from)
      @to = to
      @from = from
      super("can't convert to #{to} from #{from}.")
    end


Class: RSS::UnknownTagError

Class | RSS::UnknownTagError
In: | rss/rss.rb
Parent: | InvalidRSSError

Methods

new

Attributes

tag | [R]
uri | [R]

Public Class methods

new(tag, uri)

[Source]

# File rss/rss.rb, line 105
    def initialize(tag, uri)
      @tag, @uri = tag, uri
      super("tag <#{tag}> is unknown in namespace specified by uri <#{uri}>")
    end


Module: RSS::Utils

Module | RSS::Utils
In: | rss/utils.rb

Methods

get_file_and_line_from_caller h html_escape new_with_value_if_need to_class_name

Public Instance methods

get_file_and_line_from_caller(i=0)

[Source]

# File rss/utils.rb, line 12
    def get_file_and_line_from_caller(i=0)
      file, line, = caller[i].split(':')
      [file, line.to_i]
    end
h(s)

Alias for html_escape

html_escape(s)

[Source]

# File rss/utils.rb, line 17
    def html_escape(s)
      s.to_s.gsub(/&/, "&amp;").gsub(/\"/, "&quot;").gsub(/>/, "&gt;").gsub(/</, "&lt;")
    end
new_with_value_if_need(klass, value)

[Source]

# File rss/utils.rb, line 22
    def new_with_value_if_need(klass, value)
      if value.is_a?(klass)
        value
      else
        klass.new(value)
      end
    end
to_class_name(name)

[Source]

# File 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


Class: RSS::XMLParserListener

Class | RSS::XMLParserListener
In: | rss/xmlparser.rb
Parent: | BaseListener

Methods

xmldecl

Included Modules

ListenerMixin

Public Instance methods

xmldecl(version, encoding, standalone)

[Source]

# File rss/xmlparser.rb, line 83
    def xmldecl(version, encoding, standalone)
      super
      # Encoding is converted to UTF-8 when XMLParser parses XML.
      @encoding = 'UTF-8'
    end


Class: RSS::XMLParserNotFound

Class | RSS::XMLParserNotFound
In: | rss/parser.rb
Parent: | Error

Methods

new

Public Class methods

new()

[Source]

# File rss/parser.rb, line 23
    def initialize
      super("available XML parser does not found in " <<
            "#{AVAILABLE_PARSER_LIBRARIES.inspect}.")
    end


Class: RSS::XMLParserParser

Class | RSS::XMLParserParser
In: | rss/xmlparser.rb
Parent: | BaseParser


Class: RSS::XMLScanListener

Class | RSS::XMLScanListener
In: | 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)

[Source]

# File rss/xmlscanner.rb, line 85
    def on_attr_charref(code)
      @current_attr << [code].pack('U')
    end
on_attr_charref_hex(code)

Alias for on_attr_charref

on_attr_entityref(ref)

[Source]

# File rss/xmlscanner.rb, line 81
    def on_attr_entityref(ref)
      @current_attr << ENTITIES[ref]
    end
on_attr_value(str)

[Source]

# File rss/xmlscanner.rb, line 77
    def on_attr_value(str)
      @current_attr << str
    end
on_attribute(name)

[Source]

# File rss/xmlscanner.rb, line 73
    def on_attribute(name)
      @attrs[name] = @current_attr = ''
    end
on_charref(code)

[Source]

# File rss/xmlscanner.rb, line 63
    def on_charref(code)
      text([code].pack('U'))
    end
on_charref_hex(code)

Alias for on_charref

on_entityref(ref)

[Source]

# File rss/xmlscanner.rb, line 59
    def on_entityref(ref)
      text(ENTITIES[ref])
    end
on_etag(name)

[Source]

# File rss/xmlscanner.rb, line 55
    def on_etag(name)
      tag_end(name)
    end
on_stag(name)

[Source]

# File rss/xmlscanner.rb, line 69
    def on_stag(name)
      @attrs = {}
    end
on_stag_end(name)

[Source]

# File rss/xmlscanner.rb, line 91
    def on_stag_end(name)
      tag_start(name, @attrs)
    end
on_stag_end_empty(name)

[Source]

# File rss/xmlscanner.rb, line 95
    def on_stag_end_empty(name)
      tag_start(name, @attrs)
      tag_end(name)
    end
on_xmldecl_encoding(str)

[Source]

# File rss/xmlscanner.rb, line 39
    def on_xmldecl_encoding(str)
      @encoding = str
    end
on_xmldecl_end()

[Source]

# File rss/xmlscanner.rb, line 47
    def on_xmldecl_end
      xmldecl(@version, @encoding, @standalone == "yes")
    end
on_xmldecl_standalone(str)

[Source]

# File rss/xmlscanner.rb, line 43
    def on_xmldecl_standalone(str)
      @standalone = str
    end
on_xmldecl_version(str)

[Source]

# File rss/xmlscanner.rb, line 35
    def on_xmldecl_version(str)
      @version = str
    end


Class: RSS::XMLScanParser

Class | RSS::XMLScanParser
In: | rss/xmlscanner.rb
Parent: | BaseParser


Class: RSS::XMLStyleSheet

Class | RSS::XMLStyleSheet
In: | 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)

[Source]

# File rss/xml-stylesheet.rb, line 37
    def initialize(*attrs)
      @do_validate = true
      ATTRIBUTES.each do |attr|
        self.send("#{attr}=", nil)
      end
      vars = ATTRIBUTES.dup
      vars.unshift(:do_validate)
      attrs.each do |name, value|
        if vars.include?(name.to_s)
          self.send("#{name}=", value)
        end
      end
    end

Public Instance methods

alternate=(value)

[Source]

# File 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
href=(value)

[Source]

# File rss/xml-stylesheet.rb, line 66
    def href=(value)
      @href = value
      if @href and @type.nil?
        @type = guess_type(@href)
      end
      @href
    end
setup_maker(maker)

[Source]

# File 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
to_s()

[Source]

# File rss/xml-stylesheet.rb, line 51
    def to_s
      rv = ""
      if @href
        rv << %Q[<?xml-stylesheet]
        ATTRIBUTES.each do |name|
          if self.send(name)
            rv << %Q[ #{name}="#{h self.send(name)}"]
          end
        end
        rv << %Q[?>]
      end
      rv
    end


Module: RSS::XMLStyleSheetMixin

Module | RSS::XMLStyleSheetMixin
In: | rss/xml-stylesheet.rb

Methods

new

Attributes

xml_stylesheets [RW]

Public Class methods

new(*args)

[Source]

# File rss/xml-stylesheet.rb, line 7
    def initialize(*args)
      super
      @xml_stylesheets = []
    end


Class: Time

Class | Time
In: | rss/rss.rb
Parent: | Object

Methods

w3cdtf

External Aliases

iso8601 -> w3cdtf

Public Class methods

w3cdtf(date)

[Source]

# File 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


Module: XML

Module | XML
In: | rss/xmlparser.rb

Classes and Modules

Class XML::Parser


Class: XML::Parser

Class | XML::Parser
In: | rss/xmlparser.rb
Parent: | Object

Constants

Error = ::XMLParserError


Module: XMLEncoding_ja

Module | XMLEncoding_ja
In: | rss/xmlparser.rb

Classes and Modules

Class XMLEncoding_ja::SJISHandler


Class: XMLEncoding_ja::SJISHandler

Class | XMLEncoding_ja::SJISHandler
In: | rss/xmlparser.rb
Parent: | Object

Included Modules

Kconv


File: rss.rb

rss.rb

Path: | rss.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

Copyright © 2003-2005 Kouhei Sutou. You can redistribute it and/or modify it under the same terms as Ruby.

Author: | Kouhei Sutou <kou@cozmixng.org>
Tutorial: | www.cozmixng.org/~rwiki/?cmd=view;name=RSS+Parser%3A%3ATutorial.en

Required files

rss/1.0 rss/2.0 rss/content rss/dublincore rss/image rss/syndication rss/trackback rss/maker


File: 0.9.rb

0.9.rb

Path: | rss/0.9.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

Required files

rss/parser


File: 1.0.rb

1.0.rb

Path: | rss/1.0.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

Required files

rss/parser


File: 2.0.rb

2.0.rb

Path: | rss/2.0.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

Required files

rss/0.9


File: content.rb

content.rb

Path: | rss/content.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

Required files

rss/1.0


File: converter.rb

converter.rb

Path: | rss/converter.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

Required files

rss/utils iconv uconv nkf nkf nkf nkf


File: dublincore.rb

dublincore.rb

Path: | rss/dublincore.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

Required files

rss/1.0


File: image.rb

image.rb

Path: | rss/image.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

Required files

rss/1.0 rss/dublincore


File: maker.rb

maker.rb

Path: | rss/maker.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

Required files

rss/rss rss/maker/1.0 rss/maker/2.0 rss/maker/content rss/maker/dublincore rss/maker/syndication rss/maker/trackback rss/maker/image


File: 0.9.rb

0.9.rb

Path: | rss/maker/0.9.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

Required files

rss/0.9 rss/maker/base


File: 1.0.rb

1.0.rb

Path: | rss/maker/1.0.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

Required files

rss/1.0 rss/maker/base


File: 2.0.rb

2.0.rb

Path: | rss/maker/2.0.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

Required files

rss/2.0 rss/maker/0.9


File: base.rb

base.rb

Path: | rss/maker/base.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

Required files

forwardable rss/rss


File: content.rb

content.rb

Path: | rss/maker/content.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

Required files

rss/content rss/maker/1.0


File: dublincore.rb

dublincore.rb

Path: | rss/maker/dublincore.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

Required files

rss/dublincore rss/maker/1.0


File: image.rb

image.rb

Path: | rss/maker/image.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

Required files

rss/image rss/maker/1.0 rss/maker/dublincore


File: syndication.rb

syndication.rb

Path: | rss/maker/syndication.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

Required files

rss/syndication rss/maker/1.0


File: trackback.rb

trackback.rb

Path: | rss/maker/trackback.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

Required files

rss/trackback rss/maker/1.0 rss/maker/2.0


File: parser.rb

parser.rb

Path: | rss/parser.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

Required files

forwardable open-uri rss/rss


File: rexmlparser.rb

rexmlparser.rb

Path: | rss/rexmlparser.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

Required files

rexml/document rexml/streamlistener


File: rss.rb

rss.rb

Path: | rss/rss.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

Required files

time English rss/utils rss/converter rss/xml-stylesheet


File: syndication.rb

syndication.rb

Path: | rss/syndication.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

Required files

rss/1.0


File: taxonomy.rb

taxonomy.rb

Path: | rss/taxonomy.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

Experimental

Required files

rss/1.0


File: trackback.rb

trackback.rb

Path: | rss/trackback.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

Required files

rss/1.0 rss/2.0


File: utils.rb

utils.rb

Path: | rss/utils.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005


File: xml-stylesheet.rb

xml-stylesheet.rb

Path: | rss/xml-stylesheet.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

Required files

rss/utils


File: xmlparser.rb

xmlparser.rb

Path: | rss/xmlparser.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

Required files

xml/parser xmlparser xml/encoding-ja xmlencoding-ja


File: xmlscanner.rb

xmlscanner.rb

Path: | rss/xmlscanner.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

Required files

xmlscan/scanner


Module: RUNIT

Module | RUNIT
In: | runit/topublic.rb runit/testsuite.rb runit/testresult.rb runit/testcase.rb runit/error.rb runit/cui/testrunner.rb runit/assert.rb
Author: | Nathaniel Talbott.
Copyright: | Copyright © 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: | 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="")

[Source]

# File runit/assert.rb, line 49
    def assert_equal_float(expected, actual, delta, message="")
      assert_in_delta(expected, actual, delta, message)
    end
assert_exception(exception, message="", &block)

[Source]

# File runit/assert.rb, line 57
    def assert_exception(exception, message="", &block)
      assert_raises(exception, message, &block)
    end
assert_fail(message="")

[Source]

# File runit/assert.rb, line 45
    def assert_fail(message="")
      flunk(message)
    end
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

[Source]

# File 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_matches(*args)

[Source]

# File runit/assert.rb, line 41
    def assert_matches(*args)
      assert_match(*args)
    end
assert_no_exception(*args, &block)

[Source]

# File runit/assert.rb, line 15
    def assert_no_exception(*args, &block)
      assert_nothing_raised(*args, &block)
    end
assert_not_match(actual_string, expected_re, message="")

[Source]

# File runit/assert.rb, line 37
    def assert_not_match(actual_string, expected_re, message="")
      assert_no_match(expected_re, actual_string, message)
    end
assert_not_nil(actual, message="")

[Source]

# File runit/assert.rb, line 33
    def assert_not_nil(actual, message="")
      assert(!actual.nil?, message)
    end
assert_respond_to(method, object, message="")

[Source]

# File runit/assert.rb, line 61
    def assert_respond_to(method, object, message="")
      if (called_internally?)
        super
      else
        super(object, method, message)
      end
    end
assert_send(object, method, *args)

[Source]

# File runit/assert.rb, line 53
    def assert_send(object, method, *args)
      super([object, method, *args])
    end
called_internally?()

[Source]

# File runit/assert.rb, line 69
    def called_internally?
      /assertions\.rb/.match(caller[1])
    end
setup_assert()

[Source]

# File runit/assert.rb, line 12
    def setup_assert
    end


Module: RUNIT::CUI

Module | RUNIT::CUI
In: | runit/cui/testrunner.rb

Classes and Modules

Class RUNIT::CUI::TestRunner


Class: RUNIT::CUI::TestRunner

Class | RUNIT::CUI::TestRunner
In: | runit/cui/testrunner.rb
Parent: | Test::Unit::UI::Console::TestRunner

Methods

create_mediator create_result new quiet_mode= run run

Public Class methods

new()

[Source]

# File runit/cui/testrunner.rb, line 17
      def initialize
        super nil
      end
quiet_mode=(boolean)

[Source]

# File runit/cui/testrunner.rb, line 46
      def self.quiet_mode=(boolean)
        @@quiet_mode = boolean
      end
run(suite)

[Source]

# File runit/cui/testrunner.rb, line 13
      def self.run(suite)
        self.new().run(suite)
      end

Public Instance methods

create_mediator(suite)

[Source]

# File 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()

[Source]

# File runit/cui/testrunner.rb, line 42
      def create_result
        return RUNIT::TestResult.new
      end
run(suite, quiet_mode=@@quiet_mode)

[Source]

# File 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


Class: RUNIT::TestCase

Class | RUNIT::TestCase
In: | 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)

[Source]

# File runit/testcase.rb, line 28
    def initialize(test_name, suite_name=self.class.name)
      super(test_name)
    end
suite()

[Source]

# File 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

Public Instance methods

assert_equals(*args)

[Source]

# File runit/testcase.rb, line 32
    def assert_equals(*args)
      assert_equal(*args)
    end
name()

[Source]

# File runit/testcase.rb, line 36
    def name
      super.sub(/^(.*?)\((.*)\)$/, '\2#\1')
    end
run(result, &progress_block)

[Source]

# File runit/testcase.rb, line 40
    def run(result, &progress_block)
      progress_block = proc {} unless (block_given?)
      super(result, &progress_block)
    end


Class: RUNIT::TestResult

Class | RUNIT::TestResult
In: | 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)

[Source]

# File 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_failure(failure)

[Source]

# File runit/testresult.rb, line 25
    def add_failure(failure)
      def failure.at
        return location
      end
      def failure.err
        return message
      end
      super(failure)
    end
error_size()

[Source]

# File runit/testresult.rb, line 19
    def error_size
      return error_count
    end
failure_size()

[Source]

# File runit/testresult.rb, line 13
    def failure_size
      return failure_count
    end
run_asserts()

[Source]

# File runit/testresult.rb, line 16
    def run_asserts
      return assertion_count
    end
run_tests()

[Source]

# File runit/testresult.rb, line 22
    def run_tests
      return run_count
    end
succeed?()

[Source]

# File runit/testresult.rb, line 10
    def succeed?
      return passed?
    end


Class: RUNIT::TestSuite

Class | RUNIT::TestSuite
In: | runit/testsuite.rb
Parent: | Test::Unit::TestSuite

Methods

add add_test count_test_cases run

Public Instance methods

add(*args)

[Source]

# File runit/testsuite.rb, line 13
    def add(*args)
      self.<<(*args)
    end
add_test(*args)

[Source]

# File runit/testsuite.rb, line 9
    def add_test(*args)
      add(*args)
    end
count_test_cases()

[Source]

# File runit/testsuite.rb, line 17
    def count_test_cases
      return size
    end
run(result, &progress_block)

[Source]

# File runit/testsuite.rb, line 21
    def run(result, &progress_block)
      progress_block = proc {} unless (block_given?)
      super(result, &progress_block)
    end


Module: RUNIT::ToPublic

Module | RUNIT::ToPublic
In: | runit/topublic.rb


File: assert.rb

assert.rb

Path: | runit/assert.rb
Last Update: | Sun Oct 05 12:17:07 AUS Eastern Standard Time 2003
Author: | Nathaniel Talbott.
Copyright: | Copyright © 2000-2002 Nathaniel Talbott. All rights reserved.
License: | Ruby license.

Required files

test/unit/assertions runit/error


File: testrunner.rb

testrunner.rb

Path: | runit/cui/testrunner.rb
Last Update: | Fri Dec 19 20:24:24 AUS Eastern Daylight Time 2003
Author: | Nathaniel Talbott.
Copyright: | Copyright © 2000-2002 Nathaniel Talbott. All rights reserved.
License: | Ruby license.

Required files

test/unit/ui/console/testrunner runit/testresult


File: error.rb

error.rb

Path: | runit/error.rb
Last Update: | Wed Feb 12 14:22:38 AUS Eastern Daylight Time 2003
Author: | Nathaniel Talbott.
Copyright: | Copyright © 2000-2002 Nathaniel Talbott. All rights reserved.
License: | Ruby license.

Required files

test/unit/assertionfailederror.rb


File: testcase.rb

testcase.rb

Path: | runit/testcase.rb
Last Update: | Wed Feb 12 14:22:38 AUS Eastern Daylight Time 2003
Author: | Nathaniel Talbott.
Copyright: | Copyright © 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: | runit/testresult.rb
Last Update: | Wed Feb 12 14:22:38 AUS Eastern Daylight Time 2003
Author: | Nathaniel Talbott.
Copyright: | Copyright © 2000-2002 Nathaniel Talbott. All rights reserved.
License: | Ruby license.

Required files

test/unit/testresult


File: testsuite.rb

testsuite.rb

Path: | runit/testsuite.rb
Last Update: | Wed Feb 12 14:22:38 AUS Eastern Daylight Time 2003
Author: | Nathaniel Talbott.
Copyright: | Copyright © 2000-2002 Nathaniel Talbott. All rights reserved.
License: | Ruby license.

Required files

test/unit/testsuite


File: topublic.rb

topublic.rb

Path: | runit/topublic.rb
Last Update: | Wed Feb 12 14:22:38 AUS Eastern Daylight Time 2003
Author: | Nathaniel Talbott.
Copyright: | Copyright © 2000-2002 Nathaniel Talbott. All rights reserved.
License: | Ruby license.


Module: Scanf

Module | Scanf
In: | scanf.rb

Classes and Modules

Module Scanf::Kernel
Class Scanf::FormatSpecifier
Class Scanf::IO
Class Scanf::String


Class: Scanf::FormatSpecifier

Class | Scanf::FormatSpecifier
In: | scanf.rb
Parent: | Object

Methods

count_space? letter match mid_match? new to_re to_s width

Classes and Modules

Class Scanf::FormatSpecifier::FormatString

Attributes

conversion | [R]
matched | [R]
matched_string | [R]
re_string | [R]

Public Class methods

new(str)

[Source]

# File 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

    def to_re
      Regexp.new(@re_string,Regexp::MULTILINE)
    end

    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

    def letter
      /%\*?\d*([a-z\[])/.match(@spec_string).to_a[1]
    end

    def width
      w = /%\*?(\d+)/.match(@spec_string).to_a[1]
      w && w.to_i
    end

    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

  end

Public Instance methods

count_space?()

[Source]

# File scanf.rb, line 327
    def count_space?
      /(?:\A|\S)%\*?\d*c|\[/.match(@spec_string)
    end
letter()

[Source]

# File scanf.rb, line 468
    def letter
      /%\*?\d*([a-z\[])/.match(@spec_string).to_a[1]
    end
match(str)

[Source]

# File 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
mid_match?()

[Source]

# File 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
to_re()

[Source]

# File scanf.rb, line 451
    def to_re
      Regexp.new(@re_string,Regexp::MULTILINE)
    end
to_s()

[Source]

# File scanf.rb, line 323
    def to_s
      @spec_string
    end
width()

[Source]

# File scanf.rb, line 472
    def width
      w = /%\*?(\d+)/.match(@spec_string).to_a[1]
      w && w.to_i
    end


Class: Scanf::FormatSpecifier::FormatString

Class | Scanf::FormatSpecifier::FormatString
In: | 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)

[Source]

# File 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

Public Instance methods

last_spec()

[Source]

# File scanf.rb, line 535
    def last_spec
      @i == spec_count - 1
    end
match(str)

[Source]

# File 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
prune(n=matched_count)

[Source]

# File scanf.rb, line 527
    def prune(n=matched_count)
      n.times { @specs.shift }
    end
spec_count()

[Source]

# File scanf.rb, line 531
    def spec_count
      @specs.size
    end
to_s()

[Source]

# File scanf.rb, line 523
    def to_s
      @specs.join('')
    end


Class: Scanf::IO

Class | Scanf::IO
In: | scanf.rb
Parent: | Object

Methods

scanf

Public Instance methods

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]

[Source]

# File 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


Module: Scanf::Kernel

Module | Scanf::Kernel
In: | scanf.rb


Class: Scanf::String

Class | Scanf::String
In: | scanf.rb
Parent: | Object

Methods

block_scanf scanf

Public Instance methods

block_scanf(fstr) {|current| ...}

[Source]

# File 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
scanf(fstr,&b)

[Source]

# File 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


File: scanf.rb

scanf.rb

Path: | scanf.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

scanf for Ruby

$Revision: 1.2.2.1 $ $Id: scanf.rb,v 1.2.2.1 2004/03/20 11:57:10 dblack Exp $ $Author: dblack $ $Date: 2004/03/20 11:57:10 $

A product of the Austin Ruby Codefest (Austin, Texas, August 2002)


Class: SDBM

Class | SDBM
In: | sdbm/init.c
Parent: | Object

Methods

[] []= clear close closed? delete delete_if each each_key each_pair each_value empty? fetch has_key? has_value? include? index indexes indices invert key? keys length member? new open reject reject! replace select shift size store to_a to_hash update value? values values_at

Included Modules

Enumerable

Public Class methods

new(...)
open(...)

Public Instance methods

[](p1)
[]=(p1, p2)
clear()
close()
closed?()
delete(p1)
delete_if()
each()
each_key()
each_pair()
each_value()
empty?()
fetch(...)
has_key?(p1)
has_value?(p1)
include?(p1)
index(p1)
indexes(...)
indices(...)
invert()
key?(p1)
keys()
length()
member?(p1)
reject()
reject!()
replace(p1)
select(...)
shift()
size()
store(p1, p2)
to_a()
to_hash()
update(p1)
value?(p1)
values()
values_at(...)


Class: SDBMError

Class | SDBMError
In: | sdbm/init.c
Parent: | StandardError


File: _sdbm.c

_sdbm.c

Path: | sdbm/_sdbm.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: init.c

init.c

Path: | sdbm/init.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


Class: Set

Class | Set
In: | 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! 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.

[Source]

# File set.rb, line 55
  def self.[](*ary)
    new(ary)
  end
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.

[Source]

# File 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

Public Instance methods

&(enum)

Returns a new array containing elements common to the set and the given enumerable object.

[Source]

# File 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
+(enum)

Alias for #|

-(enum)

Returns a new set built by duplicating the set, removing every element that appears in the given enumerable object.

[Source]

# File set.rb, line 283
  def -(enum)
    enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
    dup.subtract(enum)
  end
<<(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?.

[Source]

# File 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
^(enum)

Returns a new array containing elements exclusive between the set and the given enumerable object. (set ^ enum) is equivalent to ((set | enum) - (set & enum)).

[Source]

# File set.rb, line 302
  def ^(enum)
    enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
    n = dup
    enum.each { |o| if n.include?(o) then n.delete(o) else n.add(o) end }
    n
  end
add(o)

Adds the given object to the set and returns self. Use merge to add several elements at once.

[Source]

# File set.rb, line 195
  def add(o)
    @hash[o] = true
    self
  end
add?(o)

Adds the given object to the set and returns self. If the object is already in the set, returns nil.

[Source]

# File set.rb, line 203
  def add?(o)
    if include?(o)
      nil
    else
      add(o)
    end
  end
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"}>}

[Source]

# File set.rb, line 342
  def classify # :yields: o
    h = {}

    each { |i|
      x = yield(i)
      (h[x] ||= self.class.new).add(i)
    }

    h
  end
clear()

Removes all elements and returns self.

[Source]

# File set.rb, line 93
  def clear
    @hash.clear
    self
  end
collect!() {|o| ...}

Do collect() destructively.

[Source]

# File set.rb, line 236
  def collect!
    set = self.class.new
    each { |o| set << yield(o) }
    replace(set)
  end
delete(o)

Deletes the given object from the set and returns self. Use subtract to delete several items at once.

[Source]

# File set.rb, line 213
  def delete(o)
    @hash.delete(o)
    self
  end
delete?(o)

Deletes the given object from the set and returns self. If the object is not in the set, returns nil.

[Source]

# File set.rb, line 220
  def delete?(o)
    if include?(o)
      delete(o)
    else
      nil
    end
  end
delete_if() {|o| ...}

Deletes every element of the set for which block evaluates to true, and returns self.

[Source]

# File set.rb, line 230
  def delete_if
    @hash.delete_if { |o,| yield(o) }
    self
  end
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}>}>

[Source]

# File 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
each() {|o| ...}

Calls the given block once for each element in the set, passing the element as parameter.

[Source]

# File set.rb, line 188
  def each
    @hash.each_key { |o| yield(o) }
    self
  end
empty?()

Returns true if the set contains no elements.

[Source]

# File set.rb, line 88
  def empty?
    @hash.empty?
  end
flatten()

Returns a new set that is a copy of the set, flattening each containing set recursively.

[Source]

# File set.rb, line 138
  def flatten
    self.class.new.flatten_merge(self)
  end
flatten!()

Equivalent to Set#flatten, but replaces the receiver with the result in place. Returns nil if no modifications were made.

[Source]

# File set.rb, line 144
  def flatten!
    if detect { |e| e.is_a?(Set) }
      replace(flatten())
    else
      nil
    end
  end
include?(o)

Returns true if the set contains the given object.

[Source]

# File set.rb, line 153
  def include?(o)
    @hash.include?(o)
  end
initialize_copy(orig)

Copy internal hash.

[Source]

# File set.rb, line 77
  def initialize_copy(orig)
    @hash = orig.instance_eval{@hash}.dup
  end
inspect()

Returns a string containing a human-readable representation of the set. ("#<Set: {element1, element2, …}>")

[Source]

# File 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
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.

[Source]

# File 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
proper_subset?(set)

Returns true if the set is a proper subset of the given set.

[Source]

# File 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
proper_superset?(set)

Returns true if the set is a proper superset of the given set.

[Source]

# File 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
reject!() {|o| ...}

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

[Source]

# File set.rb, line 245
  def reject!
    n = size
    delete_if { |o| yield(o) }
    size == n ? nil : self
  end
replace(enum)

Replaces the contents of the set with the contents of the given enumerable object and returns self.

[Source]

# File 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
size()

Returns the number of elements.

[Source]

# File set.rb, line 82
  def size
    @hash.size
  end
subset?(set)

Returns true if the set is a subset of the given set.

[Source]

# File 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
subtract(enum)

Deletes every element that appears in the given enumerable object and returns self.

[Source]

# File 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
superset?(set)

Returns true if the set is a superset of the given set.

[Source]

# File 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
to_a()

Converts the set to an array. The order of elements is uncertain.

[Source]

# File set.rb, line 113
  def to_a
    @hash.keys
  end
union(enum)

Alias for #|

|(enum)

Returns a new set built by merging the set and the elements of the given enumerable object.

[Source]

# File set.rb, line 274
  def |(enum)
    enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
    dup.merge(enum)
  end


Module: Enumerable

Module | Enumerable
In: | set.rb

Methods

to_set

Public Instance methods

to_set(klass = Set, *args, &block)

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

[Source]

# File set.rb, line 523
  def to_set(klass = Set, *args, &block)
    klass.new(self, *args, &block)
  end


Class: SortedSet

Class | SortedSet
In: | 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


File: set.rb

set.rb

Path: | set.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

Copyright © 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,v 1.20.2.7 2005/06/30 06:16:13 matz Exp $

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


Module: Singleton

Module | Singleton
In: | 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

[Source]

# File singleton.rb, line 67
  def clone
    raise TypeError, "can't clone instance of singleton #{self.class}"
  end
dup()

[Source]

# File singleton.rb, line 70
  def dup
    raise TypeError, "can't dup instance of singleton #{self.class}"
  end


Module: SingletonClassMethods

Module | SingletonClassMethods
In: | singleton.rb

Methods

clone

Public Instance methods

clone()

properly clone the Singleton pattern - did you know that duping doesn’t copy class methods?

[Source]

# File singleton.rb, line 130
    def clone
      Singleton.__init__(super)
    end


File: singleton.rb

singleton.rb

Path: | singleton.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

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)

[Source]

# File singleton.rb, line 157
  def __init__(klass)
    klass.instance_eval { @__instance__ = nil }
    class << klass
      define_method(:instance,FirstInstanceCall)
    end
    klass
  end


Module: SOAP

Module | SOAP
In: | soap/wsdlDriver.rb soap/streamHandler.rb soap/soap.rb soap/rpc/standaloneServer.rb soap/rpc/soaplet.rb soap/rpc/rpc.rb soap/rpc/router.rb soap/rpc/proxy.rb soap/rpc/httpserver.rb soap/rpc/element.rb soap/rpc/driver.rb soap/rpc/cgistub.rb soap/property.rb soap/processor.rb soap/parser.rb soap/netHttpClient.rb soap/mimemessage.rb soap/marshal.rb soap/mapping/wsdlliteralregistry.rb soap/mapping/wsdlencodedregistry.rb soap/mapping/typeMap.rb soap/mapping/rubytypeFactory.rb soap/mapping/registry.rb soap/mapping/mapping.rb soap/mapping/factory.rb soap/httpconfigloader.rb soap/header/simplehandler.rb soap/header/handlerset.rb soap/header/handler.rb soap/generator.rb soap/encodingstyle/soapHandler.rb soap/encodingstyle/literalHandler.rb soap/encodingstyle/handler.rb soap/encodingstyle/aspDotNetHandler.rb soap/element.rb soap/baseData.rb soap/attachment.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

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'
NO_PROXY_HOSTS = ['localhost']
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, }

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)

[Source]

# File 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

Public Instance methods

get_content(url, header = {})

[Source]

# File 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
post(url, req_body, header = {})

[Source]

# File 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
proxy=(proxy)

[Source]

# File 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
reset(url)

[Source]

# File soap/netHttpClient.rb, line 78
  def reset(url)
    # no persistent connection.  ignored.
  end
reset_all()

[Source]

# File soap/netHttpClient.rb, line 82
  def reset_all
    # no persistent connection.  ignored.
  end
save_cookie_store(filename)

[Source]

# File soap/netHttpClient.rb, line 74
  def save_cookie_store(filename)
    raise NotImplementedError.new
  end
set_basic_auth(uri, user_id, passwd)

[Source]

# File 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(filename)

[Source]

# File soap/netHttpClient.rb, line 70
  def set_cookie_store(filename)
    raise NotImplementedError.new
  end
test_loopback_response()

[Source]

# File soap/netHttpClient.rb, line 42
  def test_loopback_response
    raise NotImplementedError.new("not supported for now")
  end


Module: Enumerable

Module | Enumerable
In: | soap/property.rb

Methods

inject

Public Instance methods

inject(init) {|result, item| ...}

[Source]

# File soap/property.rb, line 325
    def inject(init)
      result = init
      each do |item|
        result = yield(result, item)
      end
      result
    end


Module: Kernel

Module | Kernel
In: | soap/soap.rb

Methods

warn

Public Instance methods

warn(msg)

[Source]

# File soap/soap.rb, line 136
    def warn(msg)
      STDERR.puts(msg + "\n") unless $VERBOSE.nil?
    end


Class: Object

Class | Object
In: | soap/soap.rb
Parent: | Object

Methods

instance_variable_get instance_variable_set

Public Instance methods

instance_variable_get(ivarname)

[Source]

# File soap/soap.rb, line 123
    def instance_variable_get(ivarname)
      instance_eval(ivarname)
    end
instance_variable_set(ivarname, value)

[Source]

# File soap/soap.rb, line 127
    def instance_variable_set(ivarname, value)
      instance_eval("#{ivarname} = value")
    end


Class: SOAP::ArrayIndexOutOfBoundsError

Class | SOAP::ArrayIndexOutOfBoundsError
In: | soap/soap.rb
Parent: | Error


Class: SOAP::ArrayStoreError

Class | SOAP::ArrayStoreError
In: | soap/soap.rb
Parent: | Error


Class: SOAP::Attachment

Class | SOAP::Attachment
In: | 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)

[Source]

# File 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(obj)

[Source]

# File soap/attachment.rb, line 81
  def self.mime_contentid(obj)
    '<' + contentid(obj) + '>'
  end
new(string_or_readable = nil)

[Source]

# File soap/attachment.rb, line 36
  def initialize(string_or_readable = nil)
    @string_or_readable = string_or_readable
    @contenttype = "application/octet-stream"
    @contentid = nil
  end

Public Instance methods

content()

[Source]

# File 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
contentid()

[Source]

# File soap/attachment.rb, line 42
  def contentid
    @contentid ||= Attachment.contentid(self)
  end
contentid=(contentid)

[Source]

# File soap/attachment.rb, line 46
  def contentid=(contentid)
    @contentid = contentid
  end
mime_contentid()

[Source]

# File soap/attachment.rb, line 50
  def mime_contentid
    '<' + contentid + '>'
  end
save(filename)

[Source]

# File soap/attachment.rb, line 70
  def save(filename)
    File.open(filename, "wb") do |f|
      write(f)
    end
  end
to_s()

[Source]

# File soap/attachment.rb, line 62
  def to_s
    content
  end
write(out)

[Source]

# File soap/attachment.rb, line 66
  def write(out)
    out.write(content)
  end


Class: SOAP::EmptyResponseError

Class | SOAP::EmptyResponseError
In: | soap/soap.rb
Parent: | Error


Module: SOAP::EncodingStyle

Module | SOAP::EncodingStyle
In: | soap/encodingstyle/soapHandler.rb soap/encodingstyle/literalHandler.rb soap/encodingstyle/handler.rb soap/encodingstyle/aspDotNetHandler.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: | 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)

[Source]

# File soap/encodingstyle/aspDotNetHandler.rb, line 20
  def initialize(charset = nil)
    super(charset)
    @textbuf = ''
    @decode_typemap = nil
  end

Public Instance methods

decode_epilogue()

[Source]

# File soap/encodingstyle/aspDotNetHandler.rb, line 147
  def decode_epilogue
  end
decode_parent(parent, node)

[Source]

# File 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
decode_prologue()

[Source]

# File soap/encodingstyle/aspDotNetHandler.rb, line 144
  def decode_prologue
  end
decode_tag(ns, elename, attrs, parent)

[Source]

# File 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(ns, node)

[Source]

# File 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(ns, text)

[Source]

# File soap/encodingstyle/aspDotNetHandler.rb, line 139
  def decode_text(ns, text)
    # @textbuf is set at decode_tag_end.
    @textbuf << text
  end
encode_data(generator, ns, data, parent)

encode interface.

[Source]

# File 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(generator, ns, data, parent)

[Source]

# File 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


Class: SOAP::EncodingStyle::ASPDotNetHandler::SOAPTemporalObject

Class | SOAP::EncodingStyle::ASPDotNetHandler::SOAPTemporalObject
In: | soap/encodingstyle/aspDotNetHandler.rb
Parent: | Object

decode interface.

Methods

new

Attributes

parent [RW]

Public Class methods

new()

[Source]

# File soap/encodingstyle/aspDotNetHandler.rb, line 80
    def initialize
      @parent = nil
    end


Class: SOAP::EncodingStyle::ASPDotNetHandler::SOAPUnknown

Class | SOAP::EncodingStyle::ASPDotNetHandler::SOAPUnknown
In: | soap/encodingstyle/aspDotNetHandler.rb
Parent: | SOAPTemporalObject

Methods

as_nil as_string as_struct new

Public Class methods

new(handler, elename)

[Source]

# File soap/encodingstyle/aspDotNetHandler.rb, line 86
    def initialize(handler, elename)
      super()
      @handler = handler
      @elename = elename
    end

Public Instance methods

as_nil()

[Source]

# File soap/encodingstyle/aspDotNetHandler.rb, line 107
    def as_nil
      o = SOAPNil.decode(@elename)
      o.parent = @parent
      @handler.decode_parent(@parent, o)
      o
    end
as_string()

[Source]

# File soap/encodingstyle/aspDotNetHandler.rb, line 100
    def as_string
      o = SOAPString.decode(@elename)
      o.parent = @parent
      @handler.decode_parent(@parent, o)
      o
    end
as_struct()

[Source]

# File 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


Class: SOAP::EncodingStyle::Handler

Class | SOAP::EncodingStyle::Handler
In: | 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| ...}

[Source]

# File soap/encodingstyle/handler.rb, line 32
    def each
      @@handlers.each do |key, value|
        yield(value)
      end
    end
handler(uri)

[Source]

# File soap/encodingstyle/handler.rb, line 28
    def handler(uri)
      @@handlers[uri]
    end
new(charset)

[Source]

# File soap/encodingstyle/handler.rb, line 51
  def initialize(charset)
    @charset = charset
    @generate_explicit_type = true
    @decode_typemap = nil
  end
uri()

[Source]

# File soap/encodingstyle/handler.rb, line 24
    def uri
      self::Namespace
    end

Public Instance methods

decode_epilogue()

[Source]

# File soap/encodingstyle/handler.rb, line 94
  def decode_epilogue
  end
decode_prologue()

[Source]

# File soap/encodingstyle/handler.rb, line 91
  def decode_prologue
  end
decode_tag(ns, name, attrs, parent)
 decode interface.

Returns SOAP/OM data.

[Source]

# File 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(ns, name)

[Source]

# File 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(ns, text)

[Source]

# File 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_typemap=(definedtypes)

[Source]

# File soap/encodingstyle/handler.rb, line 47
  def decode_typemap=(definedtypes)
    @decode_typemap = definedtypes
  end
encode_data(generator, ns, data, parent)
 encode interface.

Returns a XML instance as a string.

[Source]

# File soap/encodingstyle/handler.rb, line 61
  def encode_data(generator, ns, data, parent)
    raise NotImplementError
  end
encode_data_end(generator, ns, data, parent)

[Source]

# File soap/encodingstyle/handler.rb, line 65
  def encode_data_end(generator, ns, data, parent)
    raise NotImplementError
  end
encode_epilogue()

[Source]

# File soap/encodingstyle/handler.rb, line 72
  def encode_epilogue
  end
encode_prologue()

[Source]

# File soap/encodingstyle/handler.rb, line 69
  def encode_prologue
  end


Class: SOAP::EncodingStyle::Handler::EncodingStyleError

Class | SOAP::EncodingStyle::Handler::EncodingStyleError
In: | soap/encodingstyle/handler.rb
Parent: | Error


Class: SOAP::EncodingStyle::LiteralHandler

Class | SOAP::EncodingStyle::LiteralHandler
In: | 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)

[Source]

# File soap/encodingstyle/literalHandler.rb, line 20
  def initialize(charset = nil)
    super(charset)
    @textbuf = ''
  end

Public Instance methods

decode_attrs(ns, attrs)

[Source]

# File 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_epilogue()

[Source]

# File soap/encodingstyle/literalHandler.rb, line 177
  def decode_epilogue
  end
decode_parent(parent, node)

[Source]

# File 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
decode_prologue()

[Source]

# File soap/encodingstyle/literalHandler.rb, line 174
  def decode_prologue
  end
decode_tag(ns, elename, attrs, parent)

[Source]

# File 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(ns, node)

[Source]

# File 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(ns, text)

[Source]

# File soap/encodingstyle/literalHandler.rb, line 160
  def decode_text(ns, text)
    # @textbuf is set at decode_tag_end.
    @textbuf << text
  end
encode_data(generator, ns, data, parent)

encode interface.

[Source]

# File 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(generator, ns, data, parent)

[Source]

# File 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


Class: SOAP::EncodingStyle::LiteralHandler::SOAPTemporalObject

Class | SOAP::EncodingStyle::LiteralHandler::SOAPTemporalObject
In: | soap/encodingstyle/literalHandler.rb
Parent: | Object

decode interface.

Methods

new

Attributes

parent [RW]

Public Class methods

new()

[Source]

# File soap/encodingstyle/literalHandler.rb, line 99
    def initialize
      @parent = nil
    end


Class: SOAP::EncodingStyle::LiteralHandler::SOAPUnknown

Class | SOAP::EncodingStyle::LiteralHandler::SOAPUnknown
In: | soap/encodingstyle/literalHandler.rb
Parent: | SOAPTemporalObject

Methods

as_element as_nil as_string new

Public Class methods

new(handler, elename, extraattr)

[Source]

# File soap/encodingstyle/literalHandler.rb, line 105
    def initialize(handler, elename, extraattr)
      super()
      @handler = handler
      @elename = elename
      @extraattr = extraattr
    end

Public Instance methods

as_element()

[Source]

# File 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_nil()

[Source]

# File 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
as_string()

[Source]

# File 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


Class: SOAP::EncodingStyle::SOAPHandler

Class | SOAP::EncodingStyle::SOAPHandler
In: | 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)

[Source]

# File soap/encodingstyle/soapHandler.rb, line 20
  def initialize(charset = nil)
    super(charset)
    @refpool = []
    @idpool = []
    @textbuf = ''
    @is_first_top_ele = true
  end

Public Instance methods

decode_epilogue()

[Source]

# File soap/encodingstyle/soapHandler.rb, line 211
  def decode_epilogue
    decode_resolve_id
  end
decode_parent(parent, node)

[Source]

# File 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
decode_prologue()

[Source]

# File soap/encodingstyle/soapHandler.rb, line 205
  def decode_prologue
    @refpool.clear
    @idpool.clear
    @is_first_top_ele = true
  end
decode_tag(ns, elename, attrs, parent)

[Source]

# File 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(ns, node)

[Source]

# File 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(ns, text)

[Source]

# File soap/encodingstyle/soapHandler.rb, line 201
  def decode_text(ns, text)
    @textbuf << text
  end
encode_data(generator, ns, data, parent)

encode interface.

[Source]

# File 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(generator, ns, data, parent)

[Source]

# File 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


Class: SOAP::EncodingStyle::SOAPHandler::SOAPTemporalObject

Class | SOAP::EncodingStyle::SOAPHandler::SOAPTemporalObject
In: | soap/encodingstyle/soapHandler.rb
Parent: | Object

decode interface.

Methods

new

Attributes

id | [RW]
parent | [RW]
position | [RW]
root | [RW]

Public Class methods

new()

[Source]

# File soap/encodingstyle/soapHandler.rb, line 89
    def initialize
      @parent = nil
      @position = nil
      @id = nil
      @root = nil
    end


Class: SOAP::EncodingStyle::SOAPHandler::SOAPUnknown

Class | SOAP::EncodingStyle::SOAPHandler::SOAPUnknown
In: | 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)

[Source]

# File soap/encodingstyle/soapHandler.rb, line 102
    def initialize(handler, elename, type, extraattr)
      super()
      @handler = handler
      @elename = elename
      @type = type
      @extraattr = extraattr
      @definedtype = nil
    end

Public Instance methods

as_nil()

[Source]

# File 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
as_string()

[Source]

# File 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_struct()

[Source]

# File 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


Module: SOAP::Env

Module | SOAP::Env
In: | 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)

[Source]

# File soap/soap.rb, line 108
  def self.getenv(name)
    ENV[name.downcase] || ENV[name.upcase]
  end


Class: SOAP::Error

Class | SOAP::Error
In: | soap/soap.rb
Parent: | StandardError


Class: SOAP::FaultError

Class | SOAP::FaultError
In: | soap/soap.rb
Parent: | Error

Methods

new to_s

Attributes

detail | [RW]
faultactor | [R]
faultcode | [R]
faultstring | [R]

Public Class methods

new(fault)

[Source]

# File 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

Public Instance methods

to_s()

[Source]

# File 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


Module: SOAP::HTTPConfigLoader

Module | SOAP::HTTPConfigLoader
In: | 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)

[Source]

# File soap/httpconfigloader.rb, line 109
  def cert_from_file(filename)
    OpenSSL::X509::Certificate.new(File.open(filename) { |f| f.read })
  end
key_from_file(filename)

[Source]

# File soap/httpconfigloader.rb, line 113
  def key_from_file(filename)
    OpenSSL::PKey::RSA.new(File.open(filename) { |f| f.read })
  end
set_basic_auth(client, basic_auth)

[Source]

# File 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_options(client, options)

[Source]

# File 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_ssl_config(client, ssl_config)

[Source]

# File 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(value)

[Source]

# File 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


Class: SOAP::HTTPStreamError

Class | SOAP::HTTPStreamError
In: | soap/soap.rb
Parent: | StreamError


Class: SOAP::HTTPStreamHandler

Class | SOAP::HTTPStreamHandler
In: | 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)

[Source]

# File 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

Public Instance methods

accept_encoding_gzip=(allow)

[Source]

# File soap/streamHandler.rb, line 99
  def accept_encoding_gzip=(allow)
    @accept_encoding_gzip = allow
  end
inspect()

[Source]

# File soap/streamHandler.rb, line 103
  def inspect
    "#<#{self.class}>"
  end
reset(endpoint_url = nil)

[Source]

# File 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
send(endpoint_url, conn_data, soapaction = nil, charset = @charset)

[Source]

# File 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
test_loopback_response()

[Source]

# File soap/streamHandler.rb, line 95
  def test_loopback_response
    @client.test_loopback_response
  end


Module: SOAP::Header

Module | SOAP::Header
In: | soap/header/simplehandler.rb soap/header/handlerset.rb soap/header/handler.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: | 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)

[Source]

# File soap/header/handler.rb, line 21
  def initialize(elename)
    @elename = elename
    @mustunderstand = false
    @encodingstyle = nil
  end

Public Instance methods

on_inbound(header, mustunderstand = false)

Given header is a SOAPHeaderItem or nil.

[Source]

# File soap/header/handler.rb, line 33
  def on_inbound(header, mustunderstand = false)
    # do something.
  end
on_inbound_headeritem(header)

[Source]

# File soap/header/handler.rb, line 50
  def on_inbound_headeritem(header)
    on_inbound(header.element, header.mustunderstand)
  end
on_outbound()

Should return a SOAP/OM, a SOAPHeaderItem or nil.

[Source]

# File soap/header/handler.rb, line 28
  def on_outbound
    nil
  end
on_outbound_headeritem()

[Source]

# File 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


Class: SOAP::Header::HandlerSet

Class | SOAP::Header::HandlerSet
In: | soap/header/handlerset.rb
Parent: | Object

Methods

<< add delete dup include? new on_inbound on_outbound

Public Class methods

new()

[Source]

# File soap/header/handlerset.rb, line 17
  def initialize
    @store = XSD::NamedElements.new
  end

Public Instance methods

<<(handler)

Alias for add

add(handler)

[Source]

# File soap/header/handlerset.rb, line 27
  def add(handler)
    @store << handler
  end
delete(handler)

[Source]

# File soap/header/handlerset.rb, line 32
  def delete(handler)
    @store.delete(handler)
  end
dup()

[Source]

# File soap/header/handlerset.rb, line 21
  def dup
    obj = HandlerSet.new
    obj.store = @store.dup
    obj
  end
include?(handler)

[Source]

# File soap/header/handlerset.rb, line 36
  def include?(handler)
    @store.include?(handler)
  end
on_inbound(headers)

headers: SOAPHeaderItem enumerable object

[Source]

# File 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
on_outbound()

returns: Array of SOAPHeaderItem

[Source]

# File soap/header/handlerset.rb, line 41
  def on_outbound
    @store.collect { |handler|
      handler.on_outbound_headeritem
    }.compact
  end


Class: SOAP::Header::SimpleHandler

Class | SOAP::Header::SimpleHandler
In: | 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)

[Source]

# File soap/header/simplehandler.rb, line 18
  def initialize(elename)
    super(elename)
  end

Public Instance methods

on_inbound(header, mustunderstand)

[Source]

# File 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
on_outbound()

[Source]

# File soap/header/simplehandler.rb, line 31
  def on_outbound
    h = on_simple_outbound
    h ? SOAPElement.from_obj(h, elename.namespace) : nil
  end
on_simple_inbound(header, mustunderstand)

Given header is a Hash, String or nil.

[Source]

# File soap/header/simplehandler.rb, line 28
  def on_simple_inbound(header, mustunderstand)
  end
on_simple_outbound()

Should return a Hash, String or nil.

[Source]

# File soap/header/simplehandler.rb, line 23
  def on_simple_outbound
    nil
  end


Class: SOAP::MIMEMessage

Class | SOAP::MIMEMessage
In: | 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()

[Source]

# File soap/mimemessage.rb, line 148
  def initialize
    @parts = []
    @headers = Headers.new
    @root = nil
  end
parse(head, str)

[Source]

# File soap/mimemessage.rb, line 154
  def self.parse(head, str)
    new.parse(head, str)
  end

Public Instance methods

add_attachment(attach)

[Source]

# File 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
add_part(content)

[Source]

# File 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
boundary()

[Source]

# File soap/mimemessage.rb, line 192
  def boundary
    if @boundary == nil
      @boundary = "----=Part_" + __id__.to_s + rand.to_s
    end
    @boundary
  end
close()

[Source]

# File soap/mimemessage.rb, line 160
  def close
    @headers.add(
      "Content-Type",
      "multipart/related; type=\"text/xml\"; boundary=\"#{boundary}\"; start=\"#{@parts[0].contentid}\""
    )
  end
content_str()

[Source]

# File 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
has_parts?()

[Source]

# File soap/mimemessage.rb, line 216
  def has_parts?
    (@parts.length > 0)
  end
headers_str()

[Source]

# File soap/mimemessage.rb, line 220
  def headers_str
    @headers.to_s
  end
parse(head, str)

[Source]

# File 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()

[Source]

# File 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
to_s()

[Source]

# File soap/mimemessage.rb, line 234
  def to_s
    str = headers_str + "\r\n\r\n" + conent_str
  end


Class: SOAP::MIMEMessage::Header

Class | SOAP::MIMEMessage::Header
In: | soap/mimemessage.rb
Parent: | Object

Methods

[] []= new to_s

Attributes

key | [RW]
root | [RW]
str | [RW]

Public Class methods

new()

[Source]

# File soap/mimemessage.rb, line 28
    def initialize
      @attrs = {}
    end

Public Instance methods

[](key)

[Source]

# File soap/mimemessage.rb, line 32
    def [](key)
      @attrs[key]
    end
[]=(key, value)

[Source]

# File soap/mimemessage.rb, line 36
    def []=(key, value)
      @attrs[key] = value
    end
to_s()

[Source]

# File soap/mimemessage.rb, line 40
    def to_s
      @key + ": " + @str
    end


Class: SOAP::MIMEMessage::Headers

Class | SOAP::MIMEMessage::Headers
In: | soap/mimemessage.rb
Parent: | Hash

Methods

add parse parse parse_line parse_rhs to_s

Public Class methods

parse(str)

[Source]

# File soap/mimemessage.rb, line 46
    def self.parse(str)
      new.parse(str)
    end

Public Instance methods

add(key, value)

[Source]

# File 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
parse(str)

[Source]

# File 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(line)

[Source]

# File 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(str)

[Source]

# File 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
to_s()

[Source]

# File soap/mimemessage.rb, line 101
    def to_s
      self.values.collect { |hdr|
        hdr.to_s
      }.join("\r\n")
    end


Class: SOAP::MIMEMessage::MIMEMessageError

Class | SOAP::MIMEMessage::MIMEMessageError
In: | soap/mimemessage.rb
Parent: | StandardError


Class: SOAP::MIMEMessage::Part

Class | SOAP::MIMEMessage::Part
In: | 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()

[Source]

# File soap/mimemessage.rb, line 111
    def initialize
      @headers = Headers.new
      @headers.add("Content-Transfer-Encoding", "8bit")
      @body = nil
      @contentid = nil
    end
parse(str)

[Source]

# File soap/mimemessage.rb, line 118
    def self.parse(str)
      new.parse(str)
    end

Public Instance methods

contentid()

[Source]

# File 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
parse(str)

[Source]

# File 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
to_s()

[Source]

# File soap/mimemessage.rb, line 143
    def to_s
      @headers.to_s + "\r\n\r\n" + @body
    end


Class: SOAP::MPostUnavailableError

Class | SOAP::MPostUnavailableError
In: | soap/soap.rb
Parent: | HTTPStreamError


Module: SOAP::Mapping

Module | SOAP::Mapping
In: | soap/mapping/wsdlliteralregistry.rb soap/mapping/wsdlencodedregistry.rb soap/mapping/rubytypeFactory.rb soap/mapping/registry.rb soap/mapping/mapping.rb soap/mapping/factory.rb 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)

[Source]

# File 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(node, registry, klass = nil)

[Source]

# File 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
ary2md(ary, rank, type_ns = XSD::Namespace, typename = XSD::AnyTypeLiteral, registry = nil, opt = EMPTY_OPT)

[Source]

# File 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
ary2soap(ary, type_ns = XSD::Namespace, typename = XSD::AnyTypeLiteral, registry = nil, opt = EMPTY_OPT)

[Source]

# File 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
class2element(klass)

[Source]

# File 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
class2qname(klass)

[Source]

# File 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
class_from_name(name, lenient = false)

[Source]

# File 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
const_from_name(name, lenient = false)

[Source]

# File 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
create_empty_object(klass)

ruby/1.7 or later.

[Source]

# File soap/mapping/mapping.rb, line 151
    def self.create_empty_object(klass)
      klass.allocate
    end
create_empty_object(klass)

[Source]

# File 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
define_attr_accessor(obj, name, getterproc, setterproc = nil)

[Source]

# File 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
define_singleton_method(obj, name, &block)

[Source]

# File 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
elename2name(name)

[Source]

# File 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
fault2exception(fault, registry = nil)

[Source]

# File 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
get_attribute(obj, attr_name)

[Source]

# File 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
module_from_name(name, lenient = false)

[Source]

# File 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
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

[Source]

# File 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
obj2element(obj)

[Source]

# File 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
obj2soap(obj, registry = nil, type = nil, opt = EMPTY_OPT)

[Source]

# File 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
schema_attribute_definition(klass)

[Source]

# File soap/mapping/mapping.rb, line 342
  def self.schema_attribute_definition(klass)
    class_schema_variable(:schema_attribute, klass)
  end
schema_element_definition(klass)

[Source]

# File 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_ns_definition(klass)

[Source]

# File soap/mapping/mapping.rb, line 322
  def self.schema_ns_definition(klass)
    class_schema_variable(:schema_ns, klass)
  end
schema_type_definition(klass)

[Source]

# File soap/mapping/mapping.rb, line 318
  def self.schema_type_definition(klass)
    class_schema_variable(:schema_type, klass)
  end
set_attributes(obj, values)

[Source]

# File 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
soap2obj(node, registry = nil, klass = nil, opt = EMPTY_OPT)

[Source]

# File 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


Class: SOAP::Mapping::ArrayFactory_

Class | SOAP::Mapping::ArrayFactory_
In: | soap/mapping/factory.rb
Parent: | Factory

Methods

new obj2soap soap2obj

Public Class methods

new(allow_original_mapping = false)

[Source]

# File soap/mapping/factory.rb, line 206
  def initialize(allow_original_mapping = false)
    super()
    @allow_original_mapping = allow_original_mapping
  end

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.

[Source]

# File 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(obj_class, node, info, map)

[Source]

# File 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


Class: SOAP::Mapping::AttachmentFactory

Class | SOAP::Mapping::AttachmentFactory
In: | soap/attachment.rb
Parent: | SOAP::Mapping::Factory

Methods

obj2soap soap2obj

Public Instance methods

obj2soap(soap_class, obj, info, map)

[Source]

# File 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(obj_class, node, info, map)

[Source]

# File soap/attachment.rb, line 95
    def soap2obj(obj_class, node, info, map)
      obj = node.data
      mark_unmarshalled_obj(node, obj)
      return true, obj
    end


Class: SOAP::Mapping::Base64Factory_

Class | SOAP::Mapping::Base64Factory_
In: | soap/mapping/factory.rb
Parent: | Factory

Methods

obj2soap soap2obj

Public Instance methods

obj2soap(soap_class, obj, info, map)

[Source]

# File 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(obj_class, node, info, map)

[Source]

# File 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


Class: SOAP::Mapping::BasetypeFactory_

Class | SOAP::Mapping::BasetypeFactory_
In: | soap/mapping/factory.rb
Parent: | Factory

Methods

new obj2soap soap2obj

Public Class methods

new(allow_original_mapping = false)

[Source]

# File soap/mapping/factory.rb, line 114
  def initialize(allow_original_mapping = false)
    super()
    @allow_original_mapping = allow_original_mapping
  end

Public Instance methods

obj2soap(soap_class, obj, info, map)

[Source]

# File 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(obj_class, node, info, map)

[Source]

# File 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


Class: SOAP::Mapping::DateTimeFactory_

Class | SOAP::Mapping::DateTimeFactory_
In: | soap/mapping/factory.rb
Parent: | Factory

Methods

new obj2soap soap2obj

Public Class methods

new(allow_original_mapping = false)

[Source]

# File soap/mapping/factory.rb, line 144
  def initialize(allow_original_mapping = false)
    super()
    @allow_original_mapping = allow_original_mapping
  end

Public Instance methods

obj2soap(soap_class, obj, info, map)

[Source]

# File 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(obj_class, node, info, map)

[Source]

# File 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


Class: SOAP::Mapping::Factory

Class | SOAP::Mapping::Factory
In: | soap/mapping/factory.rb
Parent: | Object

Methods

new obj2soap setiv2obj setiv2soap soap2obj

Included Modules

TraverseSupport

Public Class methods

new()

[Source]

# File soap/mapping/factory.rb, line 16
  def initialize
    # nothing to do
  end

Public Instance methods

obj2soap(soap_class, obj, info, map)

[Source]

# File soap/mapping/factory.rb, line 20
  def obj2soap(soap_class, obj, info, map)
    raise NotImplementError.new
    # return soap_obj
  end
setiv2obj(obj, node, map)

[Source]

# File 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(node, obj, map)

[Source]

# File 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
soap2obj(obj_class, node, info, map)

[Source]

# File soap/mapping/factory.rb, line 25
  def soap2obj(obj_class, node, info, map)
    raise NotImplementError.new
    # return convert_succeeded_or_not, obj
  end


Class: SOAP::Mapping::HashFactory_

Class | SOAP::Mapping::HashFactory_
In: | soap/mapping/factory.rb
Parent: | Factory

Methods

new obj2soap soap2obj

Public Class methods

new(allow_original_mapping = false)

[Source]

# File soap/mapping/factory.rb, line 304
  def initialize(allow_original_mapping = false)
    super()
    @allow_original_mapping = allow_original_mapping
  end

Public Instance methods

obj2soap(soap_class, obj, info, map)

[Source]

# File 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(obj_class, node, info, map)

[Source]

# File 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


Module: SOAP::Mapping::MappedException

Module | SOAP::Mapping::MappedException
In: | soap/mapping/registry.rb


Class: SOAP::Mapping::MappingError

Class | SOAP::Mapping::MappingError
In: | soap/mapping/registry.rb
Parent: | Error


Class: SOAP::Mapping::Object

Class | SOAP::Mapping::Object
In: | 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()

[Source]

# File soap/mapping/registry.rb, line 65
  def initialize
    @__xmlele_type = {}
    @__xmlele = []
    @__xmlattr = {}
  end

Public Instance methods

[](qname)

[Source]

# File 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
[]=(qname, value)

[Source]

# File 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(qname, value)

[Source]

# File 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
__xmlattr()

[Source]

# File soap/mapping/registry.rb, line 76
  def __xmlattr
    @__xmlattr
  end
__xmlele()

[Source]

# File soap/mapping/registry.rb, line 80
  def __xmlele
    @__xmlele
  end
inspect()

[Source]

# File 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


Class: SOAP::Mapping::Registry

Class | SOAP::Mapping::Registry
In: | 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 = {})

[Source]

# File 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

Public Instance methods

add(obj_class, soap_class, factory, info = nil)

[Source]

# File soap/mapping/registry.rb, line 414
  def add(obj_class, soap_class, factory, info = nil)
    @map.add(obj_class, soap_class, factory, info)
  end
find_mapped_obj_class(soap_class)

[Source]

# File soap/mapping/registry.rb, line 441
  def find_mapped_obj_class(soap_class)
    @map.find_mapped_obj_class(soap_class)
  end
find_mapped_soap_class(obj_class)

[Source]

# File soap/mapping/registry.rb, line 437
  def find_mapped_soap_class(obj_class)
    @map.find_mapped_soap_class(obj_class)
  end
obj2soap(obj, type_qname = nil)

general Registry ignores type_qname

[Source]

# File 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
set(obj_class, soap_class, factory, info = nil)

Alias for add

soap2obj(node, klass = nil)

[Source]

# File 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


Class: SOAP::Mapping::Registry::Map

Class | SOAP::Mapping::Registry::Map
In: | 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)

[Source]

# File soap/mapping/registry.rb, line 179
    def initialize(registry)
      @obj2soap = {}
      @soap2obj = {}
      @registry = registry
    end

Public Instance methods

add(obj_class, soap_class, factory, info)

Give priority to latter entry.

[Source]

# File 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()

[Source]

# File soap/mapping/registry.rb, line 236
    def clear
      @obj2soap.clear
      @soap2obj.clear
    end
find_mapped_obj_class(target_soap_class)

[Source]

# File 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
find_mapped_soap_class(target_obj_class)

[Source]

# File 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
init(init_map = [])

Give priority to former entry.

[Source]

# File 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
obj2soap(obj)

[Source]

# File 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(node, klass = nil)

[Source]

# File 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


Class: SOAP::Mapping::RubytypeFactory

Class | SOAP::Mapping::RubytypeFactory
In: | 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 = {})

[Source]

# File 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

Public Instance methods

obj2soap(soap_class, obj, info, map)

[Source]

# File 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(obj_class, node, info, map)

[Source]

# File 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


Class: SOAP::Mapping::SOAPException

Class | SOAP::Mapping::SOAPException
In: | 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)

[Source]

# File soap/mapping/registry.rb, line 38
  def initialize(e)
    @excn_type_name = Mapping.name2elename(e.class.to_s)
    @cause = e
  end

Public Instance methods

to_e()

[Source]

# File 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


Class: SOAP::Mapping::StringFactory_

Class | SOAP::Mapping::StringFactory_
In: | soap/mapping/factory.rb
Parent: | Factory

Methods

new obj2soap soap2obj

Public Class methods

new(allow_original_mapping = false)

[Source]

# File soap/mapping/factory.rb, line 80
  def initialize(allow_original_mapping = false)
    super()
    @allow_original_mapping = allow_original_mapping
  end

Public Instance methods

obj2soap(soap_class, obj, info, map)

[Source]

# File 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(obj_class, node, info, map)

[Source]

# File 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


Module: SOAP::Mapping::TraverseSupport

Module | SOAP::Mapping::TraverseSupport
In: | 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)

[Source]

# File 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(node, obj)

[Source]

# File 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


Class: SOAP::Mapping::TypedArrayFactory_

Class | SOAP::Mapping::TypedArrayFactory_
In: | soap/mapping/factory.rb
Parent: | Factory

Methods

new obj2soap soap2obj

Public Class methods

new(allow_original_mapping = false)

[Source]

# File soap/mapping/factory.rb, line 242
  def initialize(allow_original_mapping = false)
    super()
    @allow_original_mapping = allow_original_mapping
  end

Public Instance methods

obj2soap(soap_class, obj, info, map)

[Source]

# File 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(obj_class, node, info, map)

[Source]

# File 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


Class: SOAP::Mapping::TypedStructFactory_

Class | SOAP::Mapping::TypedStructFactory_
In: | soap/mapping/factory.rb
Parent: | Factory

Methods

obj2soap soap2obj

Public Instance methods

obj2soap(soap_class, obj, info, map)

[Source]

# File 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(obj_class, node, info, map)

[Source]

# File 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


Class: SOAP::Mapping::URIFactory_

Class | SOAP::Mapping::URIFactory_
In: | soap/mapping/factory.rb
Parent: | Factory

Methods

obj2soap soap2obj

Public Instance methods

obj2soap(soap_class, obj, info, map)

[Source]

# File 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(obj_class, node, info, map)

[Source]

# File 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


Class: SOAP::Mapping::WSDLEncodedRegistry

Class | SOAP::Mapping::WSDLEncodedRegistry
In: | 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)

[Source]

# File 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

Public Instance methods

obj2soap(obj, qname = nil)

[Source]

# File 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(node, obj_class = nil)

map anything for now: must refer WSDL while mapping. [ToDo]

[Source]

# File 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


Class: SOAP::Mapping::WSDLLiteralRegistry

Class | SOAP::Mapping::WSDLLiteralRegistry
In: | 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)

[Source]

# File 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

Public Instance methods

obj2soap(obj, qname)

[Source]

# File 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(node, obj_class = nil)

node should be a SOAPElement

[Source]

# File 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


Module: SOAP::Marshal

Module | SOAP::Marshal
In: | 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)

[Source]

# File soap/marshal.rb, line 28
    def dump(obj, io = nil)
      marshal(obj, MarshalMappingRegistry, io)
    end
load(stream)

[Source]

# File soap/marshal.rb, line 32
    def load(stream)
      unmarshal(stream, MarshalMappingRegistry)
    end
marshal(obj, mapping_registry = MarshalMappingRegistry, io = nil)

[Source]

# File 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(stream, mapping_registry = MarshalMappingRegistry)

[Source]

# File 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


Module: SOAP::Marshallable

Module | SOAP::Marshallable
In: | soap/mapping/registry.rb


Class: SOAP::NetHttpClient

Class | SOAP::NetHttpClient
In: | soap/netHttpClient.rb
Parent: | Object

Constants

SSLEnabled = begin require 'net/https'


Class: SOAP::Parser

Class | SOAP::Parser
In: | 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 = {})

[Source]

# File 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

Public Instance methods

characters(text)

[Source]

# File 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
charset()

[Source]

# File soap/parser.rb, line 80
  def charset
    @parser.charset
  end
end_element(name)

[Source]

# File 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
parse(string_or_readable)

[Source]

# File 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(name, attrs)

[Source]

# File 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


Class: SOAP::Parser::FormatDecodeError

Class | SOAP::Parser::FormatDecodeError
In: | soap/parser.rb
Parent: | ParseError


Class: SOAP::Parser::ParseError

Class | SOAP::Parser::ParseError
In: | soap/parser.rb
Parent: | Error


Class: SOAP::Parser::ParseFrame

Class | SOAP::Parser::ParseFrame
In: | 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)

[Source]

# File soap/parser.rb, line 49
    def initialize(ns, name, node, encodingstyle)
      @ns = ns
      @name = name
      self.node = node
      @encodingstyle = encodingstyle
    end

Public Instance methods

node=(node)

[Source]

# File soap/parser.rb, line 56
    def node=(node)
      @node = NodeContainer.new(node)
    end


Class: SOAP::Parser::ParseFrame::NodeContainer

Class | SOAP::Parser::ParseFrame::NodeContainer
In: | soap/parser.rb
Parent: | Object

Methods

new node replace_node

Public Class methods

new(node)

[Source]

# File soap/parser.rb, line 34
      def initialize(node)
        @node = node
      end

Public Instance methods

node()

[Source]

# File soap/parser.rb, line 38
      def node
        @node
      end
replace_node(node)

[Source]

# File soap/parser.rb, line 42
      def replace_node(node)
        @node = node
      end


Class: SOAP::Parser::UnexpectedElementError

Class | SOAP::Parser::UnexpectedElementError
In: | soap/parser.rb
Parent: | ParseError


Class: SOAP::PostUnavailableError

Class | SOAP::PostUnavailableError
In: | soap/soap.rb
Parent: | HTTPStreamError


Module: SOAP::Processor

Module | SOAP::Processor
In: | soap/processor.rb

Methods

default_parser_option default_parser_option= marshal unmarshal

Public Class methods

default_parser_option()

[Source]

# File soap/processor.rb, line 46
    def default_parser_option
      @@default_parser_option
    end
default_parser_option=(rhs)

[Source]

# File soap/processor.rb, line 42
    def default_parser_option=(rhs)
      @@default_parser_option = rhs
    end
marshal(env, opt = {}, io = nil)

[Source]

# File 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(stream, opt = {})

[Source]

# File soap/processor.rb, line 37
    def unmarshal(stream, opt = {})
      parser = create_parser(opt)
      parser.parse(stream)
    end


Class: SOAP::Property

Class | SOAP::Property
In: | 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 each empty? keys load load loadproperty loadproperty 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)

[Source]

# File soap/property.rb, line 51
  def self.load(stream)
    new.load(stream)
  end
loadproperty(propname)

[Source]

# File soap/property.rb, line 55
  def self.loadproperty(propname)
    new.loadproperty(propname)
  end
new()

[Source]

# File soap/property.rb, line 59
  def initialize
    @store = Hash.new
    @hook = Hash.new
    @self_hook = Array.new
    @locked = false
  end

Public Instance methods

<<(value)

value: an Object key is generated by property

[Source]

# File soap/property.rb, line 122
  def <<(value)
    self[generate_new_key] = value
  end
[](name)

name: a Symbol, String or an Array

[Source]

# File soap/property.rb, line 105
  def [](name)
    referent(name_to_a(name))
  end
[]=(name, value)

name: a Symbol, String or an Array value: an Object

[Source]

# File 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
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

[Source]

# File 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() {|key, value| ...}

[Source]

# File soap/property.rb, line 138
  def each
    @store.each do |key, value|
      yield(key, value)
    end
  end
empty?()

[Source]

# File soap/property.rb, line 144
  def empty?
    @store.empty?
  end
keys()

[Source]

# File soap/property.rb, line 148
  def keys
    @store.keys
  end
load(stream)

[Source]

# File 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(propname)

find property from $:.

[Source]

# File 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
lock(cascade = false)

[Source]

# File soap/property.rb, line 156
  def lock(cascade = false)
    if cascade
      each_key do |key|
        key.lock(cascade)
      end
    end
    @locked = true
    self
  end
locked?()

[Source]

# File soap/property.rb, line 176
  def locked?
    @locked
  end
unlock(cascade = false)

[Source]

# File soap/property.rb, line 166
  def unlock(cascade = false)
    @locked = false
    if cascade
      each_key do |key|
        key.unlock(cascade)
      end
    end
    self
  end
values()

[Source]

# File soap/property.rb, line 152
  def values
    @store.values
  end


Module: SOAP::Property::Util

Module | SOAP::Property::Util
In: | soap/property.rb

Methods

const_from_name require_from_name

Public Instance methods

const_from_name(fqname)

[Source]

# File soap/property.rb, line 40
    def const_from_name(fqname)
      fqname.split("::").inject(Kernel) { |klass, name| klass.const_get(name) }
    end
require_from_name(fqname)

[Source]

# File soap/property.rb, line 45
    def require_from_name(fqname)
      require File.join(fqname.split("::").collect { |ele| ele.downcase })
    end


Module: SOAP::RPC

Module | SOAP::RPC
In: | soap/rpc/standaloneServer.rb soap/rpc/soaplet.rb soap/rpc/rpc.rb soap/rpc/router.rb soap/rpc/proxy.rb soap/rpc/httpserver.rb soap/rpc/element.rb soap/rpc/driver.rb soap/rpc/cgistub.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)

[Source]

# File 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


Class: SOAP::RPC::CGIStub

Class | SOAP::RPC::CGIStub
In: | 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)

[Source]

# File 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

Public Instance methods

add_document_operation(receiver, soapaction, name, param_def, opt = {})

[Source]

# File 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
add_headerhandler(obj)

[Source]

# File soap/rpc/cgistub.rb, line 115
  def add_headerhandler(obj)
    @router.add_headerhandler(obj)
  end
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

[Source]

# File 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(obj, name, name_as, *param)

[Source]

# File 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(namespace, obj, name, *param)

[Source]

# File 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(namespace, obj, name, name_as, *param)

[Source]

# File 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(receiver, qname, soapaction, name, param_def, opt = {})

[Source]

# File 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_rpc_servant(obj, namespace = @default_namespace)

servant entry interface

[Source]

# File soap/rpc/cgistub.rb, line 110
  def add_rpc_servant(obj, namespace = @default_namespace)
    @router.add_rpc_servant(obj, namespace)
  end
add_servant(obj, namespace = @default_namespace)

Alias for add_rpc_servant

generate_explicit_type()

[Source]

# File soap/rpc/cgistub.rb, line 100
  def generate_explicit_type
    @router.generate_explicit_type
  end
generate_explicit_type=(generate_explicit_type)

[Source]

# File soap/rpc/cgistub.rb, line 104
  def generate_explicit_type=(generate_explicit_type)
    @router.generate_explicit_type = generate_explicit_type
  end
mapping_registry()

[Source]

# File soap/rpc/cgistub.rb, line 92
  def mapping_registry
    @router.mapping_registry
  end
mapping_registry=(value)

[Source]

# File soap/rpc/cgistub.rb, line 96
  def mapping_registry=(value)
    @router.mapping_registry = value
  end
on_init()

[Source]

# File soap/rpc/cgistub.rb, line 88
  def on_init
    # do extra initialization in a derived class if needed.
  end
set_fcgi_request(request)

[Source]

# File soap/rpc/cgistub.rb, line 153
  def set_fcgi_request(request)
    @fcgi = request
  end


Class: SOAP::RPC::CGIStub::SOAPFCGIRequest

Class | SOAP::RPC::CGIStub::SOAPFCGIRequest
In: | soap/rpc/cgistub.rb
Parent: | SOAPRequest

Methods

[] meta_vars new

Attributes

body [R]

Public Class methods

new(request)

[Source]

# File soap/rpc/cgistub.rb, line 61
    def initialize(request)
      @request = request
      @body = @request.in.read
    end

Public Instance methods

[](var)

[Source]

# File soap/rpc/cgistub.rb, line 66
    def [](var)
      @request.env[var.gsub(/-/, '_').upcase]
    end
meta_vars()

[Source]

# File soap/rpc/cgistub.rb, line 70
    def meta_vars
      {
        'HTTP_SOAPACTION' => @request.env['HTTP_SOAPAction']
      }
    end


Class: SOAP::RPC::CGIStub::SOAPRequest

Class | SOAP::RPC::CGIStub::SOAPRequest
In: | soap/rpc/cgistub.rb
Parent: | Object

Methods

[] meta_vars

Attributes

body [R]

Public Instance methods

[](var)

[Source]

# File soap/rpc/cgistub.rb, line 34
    def [](var); end
meta_vars()

[Source]

# File soap/rpc/cgistub.rb, line 36
    def meta_vars; end


Class: SOAP::RPC::CGIStub::SOAPStdinRequest

Class | SOAP::RPC::CGIStub::SOAPStdinRequest
In: | soap/rpc/cgistub.rb
Parent: | SOAPRequest

Methods

[] meta_vars new

Attributes

body [R]

Public Class methods

new(stream)

[Source]

# File soap/rpc/cgistub.rb, line 42
    def initialize(stream)
      size = ENV['CONTENT_LENGTH'].to_i || 0
      @body = stream.read(size)
    end

Public Instance methods

[](var)

[Source]

# File soap/rpc/cgistub.rb, line 47
    def [](var)
      ENV[var.gsub(/-/, '_').upcase]
    end
meta_vars()

[Source]

# File soap/rpc/cgistub.rb, line 51
    def meta_vars
      {
        'HTTP_SOAPACTION' => ENV['HTTP_SOAPAction']
      }
    end


Class: SOAP::RPC::Driver

Class | SOAP::RPC::Driver
In: | 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)

[Source]

# File 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(symbol, assignable = false)

[Source]

# File 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
new(endpoint_url, namespace = nil, soapaction = nil)

[Source]

# File 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

Public Instance methods

add_document_method(name, soapaction, req_qname, res_qname)

[Source]

# File 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_document_operation(soapaction, name, param_def, opt = {})

[Source]

# File 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
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)

[Source]

# File 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(name, name_as, *params)

[Source]

# File 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(name, soapaction, *params)

[Source]

# File 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(name, name_as, soapaction, *params)

[Source]

# File 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_rpc_operation(qname, soapaction, name, param_def, opt = {})

[Source]

# File 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
call(name, *params)

[Source]

# File soap/rpc/driver.rb, line 178
  def call(name, *params)
    set_wiredump_file_base(name)
    @proxy.call(name, *params)
  end
httpproxy()

[Source]

# File soap/rpc/driver.rb, line 78
  def httpproxy
    options["protocol.http.proxy"]
  end
httpproxy=(httpproxy)

[Source]

# File soap/rpc/driver.rb, line 82
  def httpproxy=(httpproxy)
    options["protocol.http.proxy"] = httpproxy
  end
inspect()

[Source]

# File soap/rpc/driver.rb, line 74
  def inspect
    "#<#{self.class}:#{@proxy.inspect}>"
  end
invoke(headers, body)

[Source]

# File 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
loadproperty(propertyname)

[Source]

# File soap/rpc/driver.rb, line 118
  def loadproperty(propertyname)
    unless options.loadproperty(propertyname)
      raise LoadError.new("No such property to load -- #{propertyname}")
    end
  end
mandatorycharset()

[Source]

# File soap/rpc/driver.rb, line 94
  def mandatorycharset
    options["protocol.mandatorycharset"]
  end
mandatorycharset=(mandatorycharset)

[Source]

# File soap/rpc/driver.rb, line 98
  def mandatorycharset=(mandatorycharset)
    options["protocol.mandatorycharset"] = mandatorycharset
  end
wiredump_dev()

[Source]

# File soap/rpc/driver.rb, line 86
  def wiredump_dev
    options["protocol.http.wiredump_dev"]
  end
wiredump_dev=(wiredump_dev)

[Source]

# File soap/rpc/driver.rb, line 90
  def wiredump_dev=(wiredump_dev)
    options["protocol.http.wiredump_dev"] = wiredump_dev
  end
wiredump_file_base()

[Source]

# File soap/rpc/driver.rb, line 102
  def wiredump_file_base
    options["protocol.wiredump_file_base"]
  end
wiredump_file_base=(wiredump_file_base)

[Source]

# File soap/rpc/driver.rb, line 106
  def wiredump_file_base=(wiredump_file_base)
    options["protocol.wiredump_file_base"] = wiredump_file_base
  end


Class: SOAP::RPC::HTTPServer

Class | SOAP::RPC::HTTPServer
In: | 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)

[Source]

# File 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

Public Instance methods

add_document_method(obj, soapaction, name, req_qnames, res_qnames)

[Source]

# File 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_document_operation(receiver, soapaction, name, param_def, opt = {})

[Source]

# File 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(factory, soapaction, name, param_def, opt = {})

[Source]

# File 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
add_headerhandler(obj)

[Source]

# File soap/rpc/httpserver.rb, line 79
  def add_headerhandler(obj)
    @router.add_headerhandler(obj)
  end
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)

[Source]

# File soap/rpc/httpserver.rb, line 75
  def add_request_headerhandler(factory)
    @router.add_request_headerhandler(factory)
  end
add_rpc_headerhandler(obj)

Alias for add_headerhandler

add_rpc_method(obj, name, *param)

method entry interface

[Source]

# File 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(obj, name, name_as, *param)

[Source]

# File 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_rpc_operation(receiver, qname, soapaction, name, param_def, opt = {})

[Source]

# File 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(factory, qname, soapaction, name, param_def, opt = {})

[Source]

# File 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_rpc_request_servant(factory, namespace = @default_namespace)

servant entry interface

[Source]

# File 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(obj, namespace = @default_namespace)

[Source]

# File soap/rpc/httpserver.rb, line 71
  def add_rpc_servant(obj, namespace = @default_namespace)
    @router.add_rpc_servant(obj, namespace)
  end
generate_explicit_type()

[Source]

# File soap/rpc/httpserver.rb, line 57
  def generate_explicit_type
    @router.generate_explicit_type
  end
generate_explicit_type=(generate_explicit_type)

[Source]

# File soap/rpc/httpserver.rb, line 61
  def generate_explicit_type=(generate_explicit_type)
    @router.generate_explicit_type = generate_explicit_type
  end
mapping_registry()

[Source]

# File soap/rpc/httpserver.rb, line 49
  def mapping_registry
    @router.mapping_registry
  end
mapping_registry=(mapping_registry)

[Source]

# File soap/rpc/httpserver.rb, line 53
  def mapping_registry=(mapping_registry)
    @router.mapping_registry = mapping_registry
  end
on_init()

[Source]

# File soap/rpc/httpserver.rb, line 37
  def on_init
    # do extra initialization in a derived class if needed.
  end
shutdown()

[Source]

# File soap/rpc/httpserver.rb, line 45
  def shutdown
    @server.shutdown if @server
  end
status()

[Source]

# File soap/rpc/httpserver.rb, line 41
  def status
    @server.status if @server
  end


Class: SOAP::RPC::MethodDefinitionError

Class | SOAP::RPC::MethodDefinitionError
In: | soap/rpc/element.rb
Parent: | RPCError


Class: SOAP::RPC::ParameterError

Class | SOAP::RPC::ParameterError
In: | soap/rpc/element.rb
Parent: | RPCError


Class: SOAP::RPC::Proxy

Class | SOAP::RPC::Proxy
In: | 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)

[Source]

# File 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

Public Instance methods

add_document_method(soapaction, name, param_def, opt = {})

Alias for add_document_operation

add_document_operation(soapaction, name, param_def, opt = {})

[Source]

# File 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
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 = {})

[Source]

# File 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
call(name, *params)

[Source]

# File 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
check_fault(body)

[Source]

# File soap/rpc/proxy.rb, line 178
  def check_fault(body)
    if body.fault
      raise SOAP::FaultError.new(body.fault)
    end
  end
endpoint_url()

[Source]

# File soap/rpc/proxy.rb, line 60
  def endpoint_url
    @endpoint_url
  end
endpoint_url=(endpoint_url)

[Source]

# File soap/rpc/proxy.rb, line 64
  def endpoint_url=(endpoint_url)
    @endpoint_url = endpoint_url
    reset_stream
  end
inspect()

[Source]

# File soap/rpc/proxy.rb, line 56
  def inspect
    "#<#{self.class}:#{@endpoint_url}>"
  end
invoke(req_header, req_body, opt = nil)

[Source]

# File 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
reset_stream()

[Source]

# File soap/rpc/proxy.rb, line 69
  def reset_stream
    @streamhandler.reset(@endpoint_url)
  end
route(req_header, req_body, reqopt, resopt)

[Source]

# File 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
set_wiredump_file_base(wiredump_file_base)

[Source]

# File 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()

[Source]

# File soap/rpc/proxy.rb, line 77
  def test_loopback_response
    @streamhandler.test_loopback_response
  end


Class: SOAP::RPC::Proxy::Operation

Class | SOAP::RPC::Proxy::Operation
In: | 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)

[Source]

# File 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

Public Instance methods

raise_fault(e, mapping_registry, literal_mapping_registry)

[Source]

# File 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
request_body(values, mapping_registry, literal_mapping_registry, opt)

[Source]

# File 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
request_default_encodingstyle()

[Source]

# File soap/rpc/proxy.rb, line 328
    def request_default_encodingstyle
      (@request_use == :encoded) ? EncodingNamespace : LiteralNamespace
    end
response_default_encodingstyle()

[Source]

# File soap/rpc/proxy.rb, line 332
    def response_default_encodingstyle
      (@response_use == :encoded) ? EncodingNamespace : LiteralNamespace
    end
response_obj(body, mapping_registry, literal_mapping_registry, opt)

[Source]

# File 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


Class: SOAP::RPC::RPCError

Class | SOAP::RPC::RPCError
In: | soap/rpc/element.rb
Parent: | Error


Class: SOAP::RPC::Router

Class | SOAP::RPC::Router
In: | 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)

[Source]

# File 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

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 = {})

[Source]

# File 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(factory, soapaction, name, param_def, opt = {})

[Source]

# File 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
add_headerhandler(handler)

[Source]

# File soap/rpc/router.rb, line 55
  def add_headerhandler(handler)
    @headerhandler.add(handler)
  end
add_method(receiver, qname, soapaction, name, param_def, opt = {})

Alias for add_rpc_operation

add_request_headerhandler(factory)

header handler interface

[Source]

# File 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_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

[Source]

# File 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(factory, qname, soapaction, name, param_def, opt = {})

[Source]

# File 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_rpc_request_servant(factory, namespace)

servant definition interface

[Source]

# File 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(obj, namespace)

[Source]

# File 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_servant(obj, namespace)

Alias for add_rpc_servant

create_fault_response(e)

Create fault response string.

[Source]

# File 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
route(conn_data)

[Source]

# File 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


Class: SOAP::RPC::Router::ApplicationScopeOperation

Class | SOAP::RPC::Router::ApplicationScopeOperation
In: | soap/rpc/router.rb
Parent: | Operation

Methods

new

Public Class methods

new(soapaction, receiver, name, param_def, opt)

[Source]

# File soap/rpc/router.rb, line 563
    def initialize(soapaction, receiver, name, param_def, opt)
      super(soapaction, name, param_def, opt)
      @receiver = receiver
    end


Class: SOAP::RPC::Router::Operation

Class | SOAP::RPC::Router::Operation
In: | 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)

[Source]

# File 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

Public Instance methods

call(body, mapping_registry, literal_mapping_registry, opt)

[Source]

# File 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
request_default_encodingstyle()

[Source]

# File soap/rpc/router.rb, line 381
    def request_default_encodingstyle
      (@request_use == :encoded) ? EncodingNamespace : LiteralNamespace
    end
response_default_encodingstyle()

[Source]

# File soap/rpc/router.rb, line 385
    def response_default_encodingstyle
      (@response_use == :encoded) ? EncodingNamespace : LiteralNamespace
    end


Class: SOAP::RPC::Router::RequestScopeOperation

Class | SOAP::RPC::Router::RequestScopeOperation
In: | soap/rpc/router.rb
Parent: | Operation

Methods

new

Public Class methods

new(soapaction, receiver_factory, name, param_def, opt)

[Source]

# File 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


Class: SOAP::RPC::SOAPMethod

Class | SOAP::RPC::SOAPMethod
In: | 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)

[Source]

# File 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_rpc_param_def(param_names)

[Source]

# File 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
derive_rpc_param_def(obj, name, *param)

[Source]

# File 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
new(qname, param_def = nil)

[Source]

# File 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
param_count(param_def, *type)

[Source]

# File 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

Public Instance methods

have_outparam?()

[Source]

# File soap/rpc/element.rb, line 103
  def have_outparam?
    @outparam_names.size > 0
  end
input_params()

[Source]

# File soap/rpc/element.rb, line 107
  def input_params
    collect_params(IN, INOUT)
  end
output_params()

[Source]

# File soap/rpc/element.rb, line 111
  def output_params
    collect_params(OUT, INOUT)
  end
set_outparam(params)

[Source]

# File soap/rpc/element.rb, line 123
  def set_outparam(params)
    params.each do |param, data|
      @outparam[param] = data
      data.elename.name = param
    end
  end
set_param(params)

[Source]

# File 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


Class: SOAP::RPC::SOAPMethodRequest

Class | SOAP::RPC::SOAPMethodRequest
In: | 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)

[Source]

# File 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(qname, param_def = nil, soapaction = nil)

[Source]

# File soap/rpc/element.rb, line 237
  def initialize(qname, param_def = nil, soapaction = nil)
    check_elename(qname)
    super(qname, param_def)
    @soapaction = soapaction
  end

Public Instance methods

create_method_response(response_name = nil)

[Source]

# File 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
dup()

[Source]

# File soap/rpc/element.rb, line 252
  def dup
    req = self.class.new(@elename.dup, @param_def, @soapaction)
    req.encodingstyle = @encodingstyle
    req
  end
each() {|name, @inparam[name]| ...}

[Source]

# File 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


Class: SOAP::RPC::SOAPMethodResponse

Class | SOAP::RPC::SOAPMethodResponse
In: | soap/rpc/element.rb
Parent: | SOAPMethod

Methods

each new retval=

Public Class methods

new(qname, param_def = nil)

[Source]

# File soap/rpc/element.rb, line 277
  def initialize(qname, param_def = nil)
    super(qname, param_def)
    @retval = nil
  end

Public Instance methods

each() {|@retval_name, @retval| ...}

[Source]

# File 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
retval=(retval)

[Source]

# File 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


Class: SOAP::RPC::SOAPVoid

Class | SOAP::RPC::SOAPVoid
In: | 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()

[Source]

# File soap/rpc/element.rb, line 315
  def initialize()
    @elename = Name
    @id = nil
    @precedents = []
    @parent = nil
  end


Class: SOAP::RPC::SOAPlet

Class | SOAP::RPC::SOAPlet
In: | 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)

[Source]

# File soap/rpc/soaplet.rb, line 45
  def initialize(router = nil)
    @router = router || ::SOAP::RPC::Router.new(self.class.name)
    @options = {}
    @config = {}
  end

Public Instance methods

add_servant(obj, namespace)

for backward compatibility

[Source]

# File soap/rpc/soaplet.rb, line 57
  def add_servant(obj, namespace)
    @router.add_rpc_servant(obj, namespace)
  end
allow_content_encoding_gzip=(allow)

[Source]

# File soap/rpc/soaplet.rb, line 61
  def allow_content_encoding_gzip=(allow)
    @options[:allow_content_encoding_gzip] = allow
  end
app_scope_router()

for backward compatibility

[Source]

# File soap/rpc/soaplet.rb, line 52
  def app_scope_router
    @router
  end
do_GET(req, res)

[Source]

# File 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(req, res)

[Source]

# File 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
get_instance(config, *options)

Servlet interfaces for WEBrick.

[Source]

# File soap/rpc/soaplet.rb, line 68
  def get_instance(config, *options)
    @config = config
    self
  end
require_path_info?()

[Source]

# File soap/rpc/soaplet.rb, line 73
  def require_path_info?
    false
  end


Class: SOAP::RPC::StandaloneServer

Class | SOAP::RPC::StandaloneServer
In: | 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)

[Source]

# File 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


Class: SOAP::RPCRoutingError

Class | SOAP::RPCRoutingError
In: | soap/soap.rb
Parent: | Error


Class: SOAP::Response

Class | SOAP::Response
In: | soap/netHttpClient.rb
Parent: | Object

Methods

new

Attributes

content | [R]
contenttype | [R]
reason | [R]
status | [R]

Public Class methods

new(res)

[Source]

# File soap/netHttpClient.rb, line 180
    def initialize(res)
      @status = res.code.to_i
      @reason = res.message
      @contenttype = res['content-type']
      @content = res.body
    end


Class: SOAP::ResponseFormatError

Class | SOAP::ResponseFormatError
In: | soap/soap.rb
Parent: | Error


Class: SOAP::SOAPAnySimpleType

Class | SOAP::SOAPAnySimpleType
In: | soap/baseData.rb
Parent: | XSD::XSDAnySimpleType

Basic datatypes.

Included Modules

SOAPBasetype


Class: SOAP::SOAPAnyURI

Class | SOAP::SOAPAnyURI
In: | soap/baseData.rb
Parent: | XSD::XSDAnyURI

Included Modules

SOAPBasetype


Class: SOAP::SOAPArray

Class | SOAP::SOAPArray
In: | 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

[Source]

# File 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(type = nil, rank = 1, arytype = nil)

[Source]

# File 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

Public Instance methods

[](*idxary)

[Source]

# File 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
[]=(*idxary)

[Source]

# File 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
add(value)

[Source]

# File soap/baseData.rb, line 725
  def add(value)
    self[*(@offset)] = value
  end
deep_map(ary, &block)

[Source]

# File 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
each() {|data| ...}

[Source]

# File soap/baseData.rb, line 771
  def each
    @data.each do |data|
      yield(data)
    end
  end
include?(var)

[Source]

# File 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
offset=(var)

[Source]

# File soap/baseData.rb, line 720
  def offset=(var)
    @offset = var
    @sparse = true
  end
position()

[Source]

# File soap/baseData.rb, line 839
  def position
    @position
  end
replace() {|ele| ...}

[Source]

# File soap/baseData.rb, line 781
  def replace
    @data = deep_map(@data) do |ele|
      yield(ele)
    end
  end
soap2array(ary) {|v| ...}

[Source]

# File 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
to_a()

[Source]

# File soap/baseData.rb, line 777
  def to_a
    @data.dup
  end
traverse() {|v| ...}

[Source]

# File 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


Class: SOAP::SOAPAttachment

Class | SOAP::SOAPAttachment
In: | soap/attachment.rb
Parent: | SOAPExternalReference

Methods

new

Attributes

data [R]

Public Class methods

new(value)

[Source]

# File soap/attachment.rb, line 19
  def initialize(value)
    super()
    @data = value
  end


Class: SOAP::SOAPBase64

Class | SOAP::SOAPBase64
In: | 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.

[Source]

# File soap/baseData.rb, line 304
  def initialize(value = nil)
    super(value)
    @type = Type
  end

Public Instance methods

as_xsd()

[Source]

# File soap/baseData.rb, line 309
  def as_xsd
    @type = XSD::XSDBase64Binary::Type
  end


Module: SOAP::SOAPBasetype

Module | SOAP::SOAPBasetype
In: | soap/baseData.rb

for SOAP base type

Methods

new

Included Modules

SOAPType SOAP

Public Class methods

new(*arg)

[Source]

# File soap/baseData.rb, line 84
  def initialize(*arg)
    super
  end


Class: SOAP::SOAPBody

Class | SOAP::SOAPBody
In: | soap/rpc/element.rb soap/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)

[Source]

# File 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

Public Instance methods

encode(generator, ns, attrs = {}) {|@data| ...}

[Source]

# File 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
fault()

[Source]

# File soap/rpc/element.rb, line 49
  def fault
    if @is_fault
      self['fault']
    else
      nil
    end
  end
fault=(fault)

[Source]

# File soap/rpc/element.rb, line 57
  def fault=(fault)
    @is_fault = true
    add_member('fault', fault)
  end
outparams()

[Source]

# File 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
request()

[Source]

# File soap/rpc/element.rb, line 18
  def request
    root_node
  end
response()

[Source]

# File 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
root_node()

[Source]

# File 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


Class: SOAP::SOAPBoolean

Class | SOAP::SOAPBoolean
In: | soap/baseData.rb
Parent: | XSD::XSDBoolean

Included Modules

SOAPBasetype


Class: SOAP::SOAPByte

Class | SOAP::SOAPByte
In: | soap/baseData.rb
Parent: | XSD::XSDByte

Included Modules

SOAPBasetype


Module: SOAP::SOAPCompoundtype

Module | SOAP::SOAPCompoundtype
In: | soap/baseData.rb

for SOAP compound type

Methods

new

Included Modules

SOAPType SOAP

Public Class methods

new(*arg)

[Source]

# File soap/baseData.rb, line 97
  def initialize(*arg)
    super
  end


Class: SOAP::SOAPDate

Class | SOAP::SOAPDate
In: | soap/baseData.rb
Parent: | XSD::XSDDate

Included Modules

SOAPBasetype


Class: SOAP::SOAPDateTime

Class | SOAP::SOAPDateTime
In: | soap/baseData.rb
Parent: | XSD::XSDDateTime

Included Modules

SOAPBasetype


Class: SOAP::SOAPDecimal

Class | SOAP::SOAPDecimal
In: | soap/baseData.rb
Parent: | XSD::XSDDecimal

Included Modules

SOAPBasetype


Class: SOAP::SOAPDouble

Class | SOAP::SOAPDouble
In: | soap/baseData.rb
Parent: | XSD::XSDDouble

Included Modules

SOAPBasetype


Class: SOAP::SOAPDuration

Class | SOAP::SOAPDuration
In: | soap/baseData.rb
Parent: | XSD::XSDDuration

Included Modules

SOAPBasetype


Class: SOAP::SOAPElement

Class | SOAP::SOAPElement
In: | 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)

[Source]

# File soap/baseData.rb, line 610
  def self.decode(elename)
    o = SOAPElement.new(elename)
    o
  end
from_obj(obj, namespace = nil)

[Source]

# File 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
new(elename, text = nil)

[Source]

# File 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
to_elename(obj, namespace = nil)

[Source]

# File 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

Public Instance methods

[](idx)

[Source]

# File soap/baseData.rb, line 554
  def [](idx)
    if @array.include?(idx)
      @data[@array.index(idx)]
    else
      nil
    end
  end
[]=(idx, data)

[Source]

# File 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
add(value)

Element interfaces.

[Source]

# File soap/baseData.rb, line 550
  def add(value)
    add_member(value.elename.name, value)
  end
each() {|@array[idx], @data[idx]| ...}

[Source]

# File soap/baseData.rb, line 602
  def each
    idx = 0
    while idx < @array.length
      yield(@array[idx], @data[idx])
      idx += 1
    end
  end
inspect()

[Source]

# File soap/baseData.rb, line 541
  def inspect
    sprintf("#<%s:0x%x %s>", self.class.name, __id__, self.elename)
  end
key?(name)

[Source]

# File soap/baseData.rb, line 571
  def key?(name)
    @array.include?(name)
  end
members()

[Source]

# File soap/baseData.rb, line 575
  def members
    @array
  end
to_obj()

[Source]

# File 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


Class: SOAP::SOAPEnvelope

Class | SOAP::SOAPEnvelope
In: | 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)

[Source]

# File 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

Public Instance methods

body=(body)

[Source]

# File soap/element.rb, line 236
  def body=(body)
    body.parent = self
    @body = body
  end
encode(generator, ns, attrs = {}) {|@header| ...}

[Source]

# File 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
header=(header)

[Source]

# File soap/element.rb, line 231
  def header=(header)
    header.parent = self
    @header = header
  end
to_ary()

[Source]

# File soap/element.rb, line 252
  def to_ary
    [header, body]
  end


Module: SOAP::SOAPEnvelopeElement

Module | SOAP::SOAPEnvelopeElement
In: | soap/element.rb

SOAP elements


Class: SOAP::SOAPExternalReference

Class | SOAP::SOAPExternalReference
In: | soap/baseData.rb
Parent: | XSD::NSDBase

Methods

new referred refidstr

Included Modules

SOAPBasetype

Public Class methods

new()

[Source]

# File soap/baseData.rb, line 179
  def initialize
    super()
    @type = XSD::QName::EMPTY
  end

Public Instance methods

referred()

[Source]

# File soap/baseData.rb, line 184
  def referred
    rootnode.external_content[external_contentid] = self
  end
refidstr()

[Source]

# File soap/baseData.rb, line 188
  def refidstr
    'cid:' + external_contentid
  end


Class: SOAP::SOAPFault

Class | SOAP::SOAPFault
In: | 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)

[Source]

# File 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

Public Instance methods

detail()

[Source]

# File soap/element.rb, line 39
  def detail
    self['detail']
  end
detail=(rhs)

[Source]

# File soap/element.rb, line 55
  def detail=(rhs)
    self['detail'] = rhs
  end
encode(generator, ns, attrs = {}) {|self.faultcode| ...}

[Source]

# File 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
faultactor()

[Source]

# File soap/element.rb, line 35
  def faultactor
    self['faultactor']
  end
faultactor=(rhs)

[Source]

# File soap/element.rb, line 51
  def faultactor=(rhs)
    self['faultactor'] = rhs
  end
faultcode()

[Source]

# File soap/element.rb, line 27
  def faultcode
    self['faultcode']
  end
faultcode=(rhs)

[Source]

# File soap/element.rb, line 43
  def faultcode=(rhs)
    self['faultcode'] = rhs
  end
faultstring()

[Source]

# File soap/element.rb, line 31
  def faultstring
    self['faultstring']
  end
faultstring=(rhs)

[Source]

# File soap/element.rb, line 47
  def faultstring=(rhs)
    self['faultstring'] = rhs
  end


Class: SOAP::SOAPFloat

Class | SOAP::SOAPFloat
In: | soap/baseData.rb
Parent: | XSD::XSDFloat

Included Modules

SOAPBasetype


Class: SOAP::SOAPGDay

Class | SOAP::SOAPGDay
In: | soap/baseData.rb
Parent: | XSD::XSDGDay

Included Modules

SOAPBasetype


Class: SOAP::SOAPGMonth

Class | SOAP::SOAPGMonth
In: | soap/baseData.rb
Parent: | XSD::XSDGMonth

Included Modules

SOAPBasetype


Class: SOAP::SOAPGMonthDay

Class | SOAP::SOAPGMonthDay
In: | soap/baseData.rb
Parent: | XSD::XSDGMonthDay

Included Modules

SOAPBasetype


Class: SOAP::SOAPGYear

Class | SOAP::SOAPGYear
In: | soap/baseData.rb
Parent: | XSD::XSDGYear

Included Modules

SOAPBasetype


Class: SOAP::SOAPGYearMonth

Class | SOAP::SOAPGYearMonth
In: | soap/baseData.rb
Parent: | XSD::XSDGYearMonth

Included Modules

SOAPBasetype


Class: SOAP::SOAPGenerator

Class | SOAP::SOAPGenerator
In: | 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)

[Source]

# File 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(opt = {})

[Source]

# File 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

Public Instance methods

add_reftarget(name, node)

[Source]

# File 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
element_local?(element)

[Source]

# File soap/generator.rb, line 209
  def element_local?(element)
    element.elename.namespace.nil?
  end
element_qualified?(element)

[Source]

# File 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
encode_child(ns, child, parent)

[Source]

# File 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_data(ns, obj, parent)

[Source]

# File 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
encode_element(ns, obj, parent)

[Source]

# File 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(ns, data, attrs)

[Source]

# File 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(ns, data)

[Source]

# File 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_rawstring(str)

[Source]

# File soap/generator.rb, line 181
  def encode_rawstring(str)
    @buf << str
  end
encode_string(str)

[Source]

# File 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
encode_tag(elename, attrs = nil)

[Source]

# File 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(elename, cr = nil)

[Source]

# File soap/generator.rb, line 173
  def encode_tag_end(elename, cr = nil)
    if cr
      @buf << "\n#{ @indent }</#{ elename }>"
    else
      @buf << "</#{ elename }>"
    end
  end
generate(obj, io = nil)

[Source]

# File 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


Class: SOAP::SOAPGenerator::FormatEncodeError

Class | SOAP::SOAPGenerator::FormatEncodeError
In: | soap/generator.rb
Parent: | Error


Class: SOAP::SOAPHeader

Class | SOAP::SOAPHeader
In: | soap/element.rb
Parent: | SOAPStruct

Methods

add encode length new size

Included Modules

SOAPEnvelopeElement

Public Class methods

new()

[Source]

# File soap/element.rb, line 182
  def initialize
    super(nil)
    @elename = EleHeaderName
    @encodingstyle = nil
  end

Public Instance methods

add(name, value)

[Source]

# File 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
encode(generator, ns, attrs = {}) {|data| ...}

[Source]

# File 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
length()

[Source]

# File soap/element.rb, line 204
  def length
    @data.length
  end
size()

Alias for length


Class: SOAP::SOAPHeaderItem

Class | SOAP::SOAPHeaderItem
In: | 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)

[Source]

# File 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

Public Instance methods

encode(generator, ns, attrs = {}) {|@element| ...}

[Source]

# File 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


Class: SOAP::SOAPHexBinary

Class | SOAP::SOAPHexBinary
In: | soap/baseData.rb
Parent: | XSD::XSDHexBinary

Included Modules

SOAPBasetype


Class: SOAP::SOAPInt

Class | SOAP::SOAPInt
In: | soap/baseData.rb
Parent: | XSD::XSDInt

Included Modules

SOAPBasetype


Class: SOAP::SOAPInteger

Class | SOAP::SOAPInteger
In: | soap/baseData.rb
Parent: | XSD::XSDInteger

Included Modules

SOAPBasetype


Class: SOAP::SOAPLong

Class | SOAP::SOAPLong
In: | soap/baseData.rb
Parent: | XSD::XSDLong

Included Modules

SOAPBasetype


Module: SOAP::SOAPModuleUtils

Module | SOAP::SOAPModuleUtils
In: | soap/baseData.rb

Mix-in module for SOAP base type classes.

Methods

decode

Included Modules

SOAP

Public Instance methods

decode(elename)

[Source]

# File soap/baseData.rb, line 24
  def decode(elename)
    d = self.new
    d.elename = elename
    d
  end


Class: SOAP::SOAPNegativeInteger

Class | SOAP::SOAPNegativeInteger
In: | soap/baseData.rb
Parent: | XSD::XSDNegativeInteger

Included Modules

SOAPBasetype


Class: SOAP::SOAPNil

Class | SOAP::SOAPNil
In: | soap/baseData.rb
Parent: | XSD::XSDNil

Included Modules

SOAPBasetype


Class: SOAP::SOAPNonNegativeInteger

Class | SOAP::SOAPNonNegativeInteger
In: | soap/baseData.rb
Parent: | XSD::XSDNonNegativeInteger

Included Modules

SOAPBasetype


Class: SOAP::SOAPNonPositiveInteger

Class | SOAP::SOAPNonPositiveInteger
In: | soap/baseData.rb
Parent: | XSD::XSDNonPositiveInteger

Included Modules

SOAPBasetype


Class: SOAP::SOAPPositiveInteger

Class | SOAP::SOAPPositiveInteger
In: | soap/baseData.rb
Parent: | XSD::XSDPositiveInteger

Included Modules

SOAPBasetype


Class: SOAP::SOAPQName

Class | SOAP::SOAPQName
In: | soap/baseData.rb
Parent: | XSD::XSDQName

Included Modules

SOAPBasetype


Class: SOAP::SOAPRawString

Class | SOAP::SOAPRawString
In: | 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: | 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)

[Source]

# File soap/baseData.rb, line 156
  def self.create_refid(obj)
    'id' + obj.__id__.to_s
  end
decode(elename, refidstr)

[Source]

# File 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(obj = nil)

Override the definition in SOAPBasetype.

[Source]

# File soap/baseData.rb, line 115
  def initialize(obj = nil)
    super()
    @type = XSD::QName::EMPTY
    @refid = nil
    @obj = nil
    __setobj__(obj) if obj
  end

Public Instance methods

__getobj__()

[Source]

# File soap/baseData.rb, line 123
  def __getobj__
    @obj
  end
__setobj__(obj)

[Source]

# File 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(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…

[Source]

# File soap/baseData.rb, line 144
  def method_missing(msg_id, *params)
    if @obj
      @obj.send(msg_id, *params)
    else
      nil
    end
  end
refidstr()

[Source]

# File soap/baseData.rb, line 152
  def refidstr
    '#' + @refid
  end


Class: SOAP::SOAPShort

Class | SOAP::SOAPShort
In: | soap/baseData.rb
Parent: | XSD::XSDShort

Included Modules

SOAPBasetype


Class: SOAP::SOAPString

Class | SOAP::SOAPString
In: | soap/baseData.rb
Parent: | XSD::XSDString

Included Modules

SOAPBasetype


Class: SOAP::SOAPStruct

Class | SOAP::SOAPStruct
In: | 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)

[Source]

# File soap/baseData.rb, line 486
  def self.decode(elename, type)
    s = SOAPStruct.new(type)
    s.elename = elename
    s
  end
new(type = nil)

[Source]

# File soap/baseData.rb, line 400
  def initialize(type = nil)
    super()
    @type = type || XSD::QName::EMPTY
    @array = []
    @data = []
  end

Public Instance methods

[](idx)

[Source]

# File 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
[]=(idx, data)

[Source]

# File 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
add(name, value)

[Source]

# File soap/baseData.rb, line 415
  def add(name, value)
    add_member(name, value)
  end
each() {|@array[idx], @data[idx]| ...}

[Source]

# File soap/baseData.rb, line 472
  def each
    idx = 0
    while idx < @array.length
      yield(@array[idx], @data[idx])
      idx += 1
    end
  end
key?(name)

[Source]

# File soap/baseData.rb, line 445
  def key?(name)
    @array.include?(name)
  end
members()

[Source]

# File soap/baseData.rb, line 449
  def members
    @array
  end
replace() {|self[member]| ...}

[Source]

# File soap/baseData.rb, line 480
  def replace
    members.each do |member|
      self[member] = yield(self[member])
    end
  end
to_obj()

[Source]

# File 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
to_s()

[Source]

# File soap/baseData.rb, line 407
  def to_s()
    str = ''
    self.each do |key, data|
      str << "#{key}: #{data}\n"
    end
    str
  end


Class: SOAP::SOAPTime

Class | SOAP::SOAPTime
In: | soap/baseData.rb
Parent: | XSD::XSDTime

Included Modules

SOAPBasetype


Module: SOAP::SOAPType

Module | SOAP::SOAPType
In: | 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)

[Source]

# File 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

Public Instance methods

inspect()

[Source]

# File 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()

[Source]

# File soap/baseData.rb, line 67
  def rootnode
    node = self
    while node = node.parent
      break if SOAPEnvelope === node
    end
    node
  end


Class: SOAP::SOAPUnsignedByte

Class | SOAP::SOAPUnsignedByte
In: | soap/baseData.rb
Parent: | XSD::XSDUnsignedByte

Included Modules

SOAPBasetype


Class: SOAP::SOAPUnsignedInt

Class | SOAP::SOAPUnsignedInt
In: | soap/baseData.rb
Parent: | XSD::XSDUnsignedInt

Included Modules

SOAPBasetype


Class: SOAP::SOAPUnsignedLong

Class | SOAP::SOAPUnsignedLong
In: | soap/baseData.rb
Parent: | XSD::XSDUnsignedLong

Included Modules

SOAPBasetype


Class: SOAP::SOAPUnsignedShort

Class | SOAP::SOAPUnsignedShort
In: | soap/baseData.rb
Parent: | XSD::XSDUnsignedShort

Included Modules

SOAPBasetype


Class: SOAP::SessionManager

Class | SOAP::SessionManager
In: | soap/netHttpClient.rb
Parent: | Object

Attributes

connect_timeout | [RW]
receive_timeout | [RW]
send_timeout | [RW]


Class: SOAP::StreamError

Class | SOAP::StreamError
In: | soap/soap.rb
Parent: | Error


Class: SOAP::StreamHandler

Class | SOAP::StreamHandler
In: | 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)

[Source]

# File soap/streamHandler.rb, line 52
  def self.create_media_type(charset)
    "#{ MediaType }; charset=#{ charset }"
  end
parse_media_type(str)

[Source]

# File 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


Class: SOAP::StreamHandler::ConnectionData

Class | SOAP::StreamHandler::ConnectionData
In: | 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)

[Source]

# File 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


Class: SOAP::UnhandledMustUnderstandHeaderError

Class | SOAP::UnhandledMustUnderstandHeaderError
In: | soap/soap.rb
Parent: | Error


Class: SOAP::WSDLDriver

Class | SOAP::WSDLDriver
In: | 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)

[Source]

# File 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(symbol, assignable = false)

[Source]

# File 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
new(wsdl, port, logdev)

[Source]

# File soap/wsdlDriver.rb, line 240
  def initialize(wsdl, port, logdev)
    @servant = Servant__.new(self, wsdl, port, logdev)
  end

Public Instance methods

httpproxy()

[Source]

# File soap/wsdlDriver.rb, line 208
  def httpproxy
    @servant.options["protocol.http.proxy"]
  end
httpproxy=(httpproxy)

[Source]

# File soap/wsdlDriver.rb, line 212
  def httpproxy=(httpproxy)
    @servant.options["protocol.http.proxy"] = httpproxy
  end
inspect()

[Source]

# File soap/wsdlDriver.rb, line 244
  def inspect
    "#<#{self.class}:#{@servant.port.name}>"
  end
mandatorycharset()

[Source]

# File soap/wsdlDriver.rb, line 224
  def mandatorycharset
    @servant.options["protocol.mandatorycharset"]
  end
mandatorycharset=(mandatorycharset)

[Source]

# File soap/wsdlDriver.rb, line 228
  def mandatorycharset=(mandatorycharset)
    @servant.options["protocol.mandatorycharset"] = mandatorycharset
  end
reset_stream()

[Source]

# File soap/wsdlDriver.rb, line 248
  def reset_stream
    @servant.reset_stream
  end
wiredump_dev()

[Source]

# File soap/wsdlDriver.rb, line 216
  def wiredump_dev
    @servant.options["protocol.http.wiredump_dev"]
  end
wiredump_dev=(wiredump_dev)

[Source]

# File soap/wsdlDriver.rb, line 220
  def wiredump_dev=(wiredump_dev)
    @servant.options["protocol.http.wiredump_dev"] = wiredump_dev
  end
wiredump_file_base()

[Source]

# File soap/wsdlDriver.rb, line 232
  def wiredump_file_base
    @servant.options["protocol.wiredump_file_base"]
  end
wiredump_file_base=(wiredump_file_base)

[Source]

# File soap/wsdlDriver.rb, line 236
  def wiredump_file_base=(wiredump_file_base)
    @servant.options["protocol.wiredump_file_base"] = wiredump_file_base
  end


Class: SOAP::WSDLDriver::Servant__

Class | SOAP::WSDLDriver::Servant__
In: | 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)

[Source]

# File 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

Public Instance methods

document_send(name, header_obj, body_obj)

req_header: [[element, mustunderstand, encodingstyle(QName/String)], …] req_body: SOAPBasetype/SOAPCompoundtype

[Source]

# File 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
endpoint_url()

[Source]

# File soap/wsdlDriver.rb, line 306
    def endpoint_url
      @proxy.endpoint_url
    end
endpoint_url=(endpoint_url)

[Source]

# File soap/wsdlDriver.rb, line 310
    def endpoint_url=(endpoint_url)
      @proxy.endpoint_url = endpoint_url
    end
headerhandler()

[Source]

# File soap/wsdlDriver.rb, line 314
    def headerhandler
      @proxy.headerhandler
    end
inspect()

[Source]

# File soap/wsdlDriver.rb, line 302
    def inspect
      "#<#{self.class}:#{@proxy.inspect}>"
    end
reset_stream()

[Source]

# File soap/wsdlDriver.rb, line 326
    def reset_stream
      @proxy.reset_stream
    end
rpc_call(name, *values)

[Source]

# File 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
streamhandler()

[Source]

# File soap/wsdlDriver.rb, line 318
    def streamhandler
      @proxy.streamhandler
    end
test_loopback_response()

[Source]

# File soap/wsdlDriver.rb, line 322
    def test_loopback_response
      @proxy.test_loopback_response
    end


Class: SOAP::WSDLDriverFactory

Class | SOAP::WSDLDriverFactory
In: | 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)

[Source]

# File soap/wsdlDriver.rb, line 27
  def initialize(wsdl)
    @wsdl = import(wsdl)
    @methoddefcreator = WSDL::SOAP::MethodDefCreator.new(@wsdl)
  end

Public Instance methods

createDriver(servicename = nil, portname = nil)

Alias for create_driver

create_driver(servicename = nil, portname = nil)

depricated old interface

[Source]

# File 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
create_rpc_driver(servicename = nil, portname = nil)

[Source]

# File 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
inspect()

[Source]

# File soap/wsdlDriver.rb, line 32
  def inspect
    "#<#{self.class}:#{@wsdl.name}>"
  end


Class: SOAP::WSDLDriverFactory::FactoryError

Class | SOAP::WSDLDriverFactory::FactoryError
In: | soap/wsdlDriver.rb
Parent: | StandardError


Module: WEBrick

Module | WEBrick
In: | soap/rpc/soaplet.rb

Classes and Modules

Class WEBrick::Log


Class: WEBrick::Log

Class | WEBrick::Log
In: | soap/rpc/soaplet.rb
Parent: | BasicLog

Methods

debug

External Aliases

debug -> __debug

Public Instance methods

debug(msg = nil) {|| ...}

[Source]

# File soap/rpc/soaplet.rb, line 26
    def debug(msg = nil)
      if block_given? and msg.nil?
        __debug(yield)
      else
        __debug(msg)
      end
    end


File: attachment.rb

attachment.rb

Path: | soap/attachment.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

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: | soap/baseData.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

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: | soap/element.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

SOAP4R - SOAP elements library Copyright (C) 2000, 2001, 2003-2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/qname soap/baseData


File: aspDotNetHandler.rb

aspDotNetHandler.rb

Path: | soap/encodingstyle/aspDotNetHandler.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

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: | soap/encodingstyle/handler.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

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: | soap/encodingstyle/literalHandler.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

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: | soap/encodingstyle/soapHandler.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

SOAP4R - SOAP EncodingStyle handler library Copyright (C) 2001, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

soap/encodingstyle/handler


File: generator.rb

generator.rb

Path: | soap/generator.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

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: handler.rb

handler.rb

Path: | soap/header/handler.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

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: | soap/header/handlerset.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

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: | soap/header/simplehandler.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

SOAP4R - SOAP Simple header item handler Copyright (C) 2003-2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

soap/header/handler soap/baseData


File: httpconfigloader.rb

httpconfigloader.rb

Path: | soap/httpconfigloader.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

SOAP4R - HTTP config loader. Copyright (C) 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

soap/property


File: mapping.rb

mapping.rb

Path: | soap/mapping.rb
Last Update: | Tue Nov 25 17:31:29 AUS Eastern Daylight Time 2003

SOAP4R - Ruby type mapping utility. Copyright (C) 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

soap/mapping/mapping soap/mapping/registry


File: factory.rb

factory.rb

Path: | soap/mapping/factory.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

SOAP4R - Mapping factory. Copyright (C) 2000, 2001, 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.


File: mapping.rb

mapping.rb

Path: | soap/mapping/mapping.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

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: | soap/mapping/registry.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

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: | soap/mapping/rubytypeFactory.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

SOAP4R - Ruby type mapping factory. Copyright (C) 2000-2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.


File: typeMap.rb

typeMap.rb

Path: | soap/mapping/typeMap.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

SOAP4R - Base type mapping definition Copyright (C) 2000, 2001, 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.


File: wsdlencodedregistry.rb

wsdlencodedregistry.rb

Path: | soap/mapping/wsdlencodedregistry.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

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: | soap/mapping/wsdlliteralregistry.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

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: marshal.rb

marshal.rb

Path: | soap/marshal.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

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: | soap/mimemessage.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

SOAP4R - MIME Message implementation. Copyright (C) 2002 Jamie Herre.

Required files

soap/attachment


File: netHttpClient.rb

netHttpClient.rb

Path: | soap/netHttpClient.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

SOAP4R - net/http wrapper Copyright (C) 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

net/http


File: parser.rb

parser.rb

Path: | soap/parser.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

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: | soap/processor.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

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: | soap/property.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

soap/property.rb: SOAP4R - Property implementation. Copyright (C) 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.


File: cgistub.rb

cgistub.rb

Path: | soap/rpc/cgistub.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

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: | soap/rpc/driver.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

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: | soap/rpc/element.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

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: | soap/rpc/httpserver.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

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: | soap/rpc/proxy.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

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: | soap/rpc/router.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

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: | soap/rpc/rpc.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

SOAP4R - RPC utility. Copyright (C) 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.


File: soaplet.rb

soaplet.rb

Path: | soap/rpc/soaplet.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

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: | soap/rpc/standaloneServer.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

SOAP4R - WEBrick Server Copyright (C) 2003 by NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

soap/rpc/httpserver


File: soap.rb

soap.rb

Path: | soap/soap.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

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: | soap/streamHandler.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

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: | soap/wsdlDriver.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

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


Class: Socket

Class | Socket
In: | socket/socket.c
Parent: | BasicSocket

Methods

accept bind connect getaddrinfo gethostbyaddr gethostbyname gethostname getnameinfo getservbyname listen new pack_sockaddr_in pack_sockaddr_un pair recvfrom sockaddr_in sockaddr_un socketpair sysaccept unpack_sockaddr_in unpack_sockaddr_un

Classes and Modules

Module Socket::Constants

Public Class methods

getaddrinfo(...)
gethostbyaddr(...)
gethostbyname(p1)
gethostname()
getnameinfo(...)
getservbyname(...)
new(p1, p2, p3)
pack_sockaddr_in(p1, p2)
pack_sockaddr_un(p1)
pair(p1, p2, p3)
sockaddr_in(p1, p2)
sockaddr_un(p1)
socketpair(p1, p2, p3)
unpack_sockaddr_in(p1)
unpack_sockaddr_un(p1)

Public Instance methods

accept()
bind(p1)
connect(p1)
listen(p1)
recvfrom(...)
sysaccept()


Class: BasicSocket

Class | BasicSocket
In: | socket/socket.c
Parent: | IO

Methods

close_read close_write do_not_reverse_lookup do_not_reverse_lookup= for_fd getpeername getsockname getsockopt recv send setsockopt shutdown

Public Class methods

do_not_reverse_lookup()
do_not_reverse_lookup=(p1)
for_fd(p1)

Public Instance methods

close_read()
close_write()
getpeername()
getsockname()
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"

[Source]

/*
 * 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(...)
send(...)
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)

[Source]

/*
 * 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);
}
shutdown(...)


Class: IPSocket

Class | IPSocket
In: | socket/socket.c
Parent: | BasicSocket

Methods

addr getaddress peeraddr recvfrom

Public Class methods

getaddress(p1)

Public Instance methods

addr()
peeraddr()
recvfrom(...)


Class: SOCKSSocket

Class | SOCKSSocket
In: | socket/socket.c
Parent: | TCPSocket

Methods

close new

Public Class methods

new(p1, p2)

Public Instance methods

close()


Module: Socket::Constants

Module | Socket::Constants
In: | socket/socket.c


Class: SocketError

Class | SocketError
In: | socket/socket.c
Parent: | StandardError


Class: TCPServer

Class | TCPServer
In: | socket/socket.c
Parent: | TCPSocket

Methods

accept listen new sysaccept

Public Class methods

new(...)

Public Instance methods

accept()
listen(p1)
sysaccept()


Class: TCPSocket

Class | TCPSocket
In: | socket/socket.c
Parent: | IPSocket

Methods

gethostbyname new

Public Class methods

gethostbyname(p1)
new(...)


Class: UDPSocket

Class | UDPSocket
In: | socket/socket.c
Parent: | IPSocket

Methods

bind connect new send

Public Class methods

new(...)

Public Instance methods

bind(p1, p2)
connect(p1, p2)
send(...)


Class: UNIXServer

Class | UNIXServer
In: | socket/socket.c
Parent: | UNIXSocket

Methods

accept listen new sysaccept

Public Class methods

new(p1)

Public Instance methods

accept()
listen(p1)
sysaccept()


Class: UNIXSocket

Class | UNIXSocket
In: | socket/socket.c
Parent: | BasicSocket

Methods

addr new pair path peeraddr recv_io recvfrom send_io socketpair

Public Class methods

new(p1)
pair(...)
socketpair(...)

Public Instance methods

addr()
path()
peeraddr()
recv_io(...)
recvfrom(...)
send_io(p1)


File: getaddrinfo.c

getaddrinfo.c

Path: | socket/getaddrinfo.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: getnameinfo.c

getnameinfo.c

Path: | socket/getnameinfo.c
Last Update: | Sat Oct 15 23:43:57 AUS Eastern Standard Time 2005


File: socket.c

socket.c

Path: | socket/socket.c
Last Update: | Sat Oct 15 23:43:58 AUS Eastern Standard Time 2005


Class: StringIO

Class | StringIO
In: | stringio/stringio.c
Parent: | Data

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? fcntl fileno flush fsync getc gets initialize_copy isatty length lineno lineno= new open path pid pos pos= print printf putc puts read readchar readline readlines reopen rewind seek size string string= sync sync= sysread syswrite tell truncate tty? ungetc write

Included Modules

Enumerable

Public Class methods

StringIO.new(string=""[, mode])

Creates new StringIO instance from with string and mode.

[Source]

/*
 * 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);
    VALUE string, mode;
    int trunc = Qfalse;

    if (!ptr) {
    DATA_PTR(self) = ptr = strio_alloc();
    }
    rb_call_super(0, 0);
    switch (rb_scan_args(argc, argv, "02", &string, &mode)) {
      case 2:
    if (FIXNUM_P(mode)) {
        int flags = FIX2INT(mode);
        ptr->flags = rb_io_modenum_flags(flags);
        trunc = flags & O_TRUNC;
    }
    else {
        const char *m = StringValueCStr(mode);
        ptr->flags = rb_io_mode_flags(m);
        trunc = *m == 'w';
    }
    StringValue(string);
    if ((ptr->flags & FMODE_WRITABLE) && OBJ_FROZEN(string)) {
        errno = EACCES;
        rb_sys_fail(0);
    }
    if (trunc) {
        rb_str_resize(string, 0);
    }
    break;
      case 1:
    StringValue(string);
    ptr->flags = OBJ_FROZEN(string) ? FMODE_READABLE : FMODE_READWRITE;
    break;
      case 0:
    string = rb_str_new("", 0);
    ptr->flags = FMODE_READWRITE;
    break;
    }
    ptr->string = string;
    return self;
}
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.

[Source]

/*
 * 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);
}

Public Instance methods

<<(p1)
binmode()
strio.close → nil

Closes strio. The strio is unavailable for any further data operations; an IOError is raised if such an attempt is made.

[Source]

/*
 * 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;
}
strio.close_read → nil

Closes the read end of a StringIO. Will raise an IOError if the strio is not readable.

[Source]

/*
 * 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;
}
strio.close_write → nil

Closes the write end of a StringIO. Will raise an IOError if the strio is not writeable.

[Source]

/*
 * 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;
}
strio.closed? → true or false

Returns true if strio is completely closed, false otherwise.

[Source]

/*
 * 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;
}
strio.closed_read? → true or false

Returns true if strio is not readable, false otherwise.

[Source]

/*
 * 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;
}
strio.closed_write? → true or false

Returns true if strio is not writable, false otherwise.

[Source]

/*
 * 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;
}
strio.each(sep_string=$/) {|line| block } → strio
strio.each_line(sep_string=$/) {|line| block } → strio

See IO#each.

[Source]

/*
 * 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;
}
strio.each_byte {|byte| block } → strio

See IO#each_byte.

[Source]

/*
 * 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;
}
strio.each(sep_string=$/) {|line| block } → strio
strio.each_line(sep_string=$/) {|line| block } → strio

See IO#each.

[Source]

/*
 * 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;
}
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.

[Source]

/*
 * 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;
}
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.

[Source]

/*
 * 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(...)
fileno()
flush()
fsync()
strio.getc → fixnum or nil

See IO#getc.

[Source]

/*
 * 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);
}
strio.gets(sep_string=$/) → string or nil

See IO#gets.

[Source]

/*
 * 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;
}
initialize_copy(p1)

:nodoc:

[Source]

/* :nodoc: */
static VALUE
strio_copy(copy, orig)
    VALUE copy, orig;
{
    struct StringIO *ptr;

    orig = rb_convert_type(orig, T_DATA, "StringIO", "to_strio");
    if (copy == orig) return copy;
    ptr = StringIO(orig);
    if (check_strio(copy)) {
    strio_free(DATA_PTR(copy));
    }
    DATA_PTR(copy) = ptr;
    OBJ_INFECT(copy, orig);
    ++ptr->count;
    return copy;
}
isatty()
strio.size → integer

Returns the size of the buffer string.

[Source]

/*
 * 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);
}
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.

[Source]

/*
 * 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);
}
strio.lineno = integer → integer

Manually sets the current line number to the given value. $. is updated only on the next read.

[Source]

/*
 * 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;
}
path()
pid()
strio.pos → integer
strio.tell → integer

Returns the current offset (in bytes) of strio.

[Source]

/*
 * 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);
}
strio.pos = integer → integer

Seeks to the given position (in bytes) in strio.

[Source]

/*
 * 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;
}
print(...)
printf(...)
strio.putc(obj) → obj

See IO#putc.

[Source]

/*
 * 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;
}
puts(...)
strio.read([length [, buffer]]) → string, buffer, or nil

See IO#read.

[Source]

/*
 * 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;
}
strio.readchar → fixnum

See IO#readchar.

[Source]

/*
 * 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;
}
strio.readline(sep_string=$/) → string

See IO#readline.

[Source]

/*
 * 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;
}
strio.readlines(sep_string=$/) → array

See IO#readlines.

[Source]

/*
 * 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;
}
strio.reopen(other_StrIO) → strio
strio.reopen(string, mode) → strio

Reinitializes strio with the given other_StrIO or string and mode (see StringIO#new).

[Source]

/*
 * 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);
    }
    return strio_initialize(argc, argv, self);
}
strio.rewind → 0

Positions strio to the beginning of input, resetting lineno to zero.

[Source]

/*
 * 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);
}
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).

[Source]

/*
 * 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);
}
strio.size → integer

Returns the size of the buffer string.

[Source]

/*
 * 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);
}
strio.string → string

Returns underlying String object, the subject of IO.

[Source]

/*
 * 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;
}
strio.string = string → string

Changes underlying String object, the subject of IO.

[Source]

/*
 * 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;
}
strio.sync → true

Returns true always.

[Source]

/*
 * call-seq:
 *   strio.sync    -> true
 *
 * Returns +true+ always.
 */
static VALUE
strio_get_sync(self)
    VALUE self;
{
    StringIO(self);
    return Qtrue;
}
sync=(p1)
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.

[Source]

/*
 * 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;
}
syswrite(p1)
tell()
strio.truncate(integer) → 0

Truncates the buffer string to at most integer bytes. The strio must be opened for writing.

[Source]

/*
 * 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;
}
tty?()
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.

[Source]

/*
 * 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;
}
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.

[Source]

/*
 * 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);
}


File: stringio.c

stringio.c

Path: | stringio/stringio.c
Last Update: | Sat Oct 15 23:43:58 AUS Eastern Standard Time 2005


Class: StringScanner

Class | StringScanner
In: | 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
  • getbyte
  • scan
  • scan_until
  • skip
  • skip_until

Looking Ahead

  • check
  • check_until
  • exist?
  • match?
  • peek

Finding Where we Are

  • 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? bol? check check_until clear concat empty? eos? exist? get_byte getbyte getch 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.

[Source]

/*
 * call-seq: StringScanner.must_C_version
 *
 * This method is defined for backward compatibility.
 */
static VALUE
strscan_s_mustc(self)
    VALUE self;
{
    return self;
}
StringScanner.new(string, dup = false)

Creates a new StringScanner object to scan over the given string. dup argument is obsolete and not used now.

[Source]

/*
 * 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(argc, argv, self)
    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;
}

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"

[Source]

/*
 * 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(self, str)
    VALUE self, str;
{
    struct strscanner *p;

    GET_SCANNER(self, p);
    StringValue(str);
    rb_str_append(p->str, str);
    return self;
}
[](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                        # -> ""

[Source]

/*
 * 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(self, idx)
    VALUE self, 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]);
}
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

[Source]

/*
 * 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(self)
    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;
}
bol?()

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

[Source]

/*
 * 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(self)
    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;
}
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.

[Source]

/*
 * 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(self, re)
    VALUE self, re;
{
    return strscan_do_scan(self, re, 0, 1, 1);
}
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.

[Source]

/*
 * 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(self, re)
    VALUE self, re;
{
    return strscan_do_scan(self, re, 0, 1, 0);
}
clear()

Equivalent to terminate. This method is obsolete; use terminate instead.

[Source]

/*
 * Equivalent to #terminate.
 * This method is obsolete; use #terminate instead.
 */
static VALUE
strscan_clear(self)
    VALUE self;
{
    rb_warning("StringScanner#clear is obsolete; use #terminate instead");
    return strscan_terminate(self);
}
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"

[Source]

/*
 * 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(self, str)
    VALUE self, str;
{
    struct strscanner *p;

    GET_SCANNER(self, p);
    StringValue(str);
    rb_str_append(p->str, str);
    return self;
}
empty?()

Equivalent to eos?. This method is obsolete, use eos? instead.

[Source]

/*
 * Equivalent to #eos?.
 * This method is obsolete, use #eos? instead.
 */
static VALUE
strscan_empty_p(self)
    VALUE self;
{
    rb_warning("StringScanner#empty? is obsolete; use #eos? instead");
    return strscan_eos_p(self);
}
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

[Source]

/*
 * 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(self)
    VALUE self;
{
    struct strscanner *p;

    GET_SCANNER(self, p);
    if (EOS_P(p))
        return Qtrue;
    else
        return Qfalse;
}
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

[Source]

/*
 * 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(self, re)
    VALUE self, re;
{
    return strscan_do_scan(self, re, 0, 0, 0);
}
get_byte()

Scans one byte and returns it. Similar to, but not the same as, getch.

 s = StringScanner.new('ab')
 s.get_byte         # => "a"
 s.get_byte         # => "b"
 s.get_byte         # => nil

[Source]

/*
 * Scans one byte and returns it.  Similar to, but not the same as, #getch.
 *
 *  s = StringScanner.new('ab')
 *  s.get_byte         # => "a"
 *  s.get_byte         # => "b"
 *  s.get_byte         # => nil
 */
static VALUE
strscan_get_byte(self)
    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()

Equivalent to get_byte. This method is obsolete; use get_byte instead.

[Source]

/*
 * Equivalent to #get_byte.
 * This method is obsolete; use #get_byte instead.
 */
static VALUE
strscan_getbyte(self)
    VALUE self;
{
    rb_warning("StringScanner#getbyte is obsolete; use #get_byte instead");
    return strscan_get_byte(self);
}
getch()

Scans one character and returns it.

  s = StringScanner.new('ab')
  s.getch           # => "a"
  s.getch           # => "b"
  s.getch           # => nil

[Source]

/*
 * Scans one character and returns it.
 *
 *   s = StringScanner.new('ab')
 *   s.getch           # => "a"
 *   s.getch           # => "b"
 *   s.getch           # => nil
 */
static VALUE
strscan_getch(self)
    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]);
}
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…">’

[Source]

/*
 * 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(self)
    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);
}
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

[Source]

/*
 * 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(self, re)
    VALUE self, re;
{
    return strscan_do_scan(self, re, 0, 0, 1);
}
matched()

Returns the last matched string.

  s = StringScanner.new('test string')
  s.match?(/\w+/)     # -> 4
  s.matched           # -> "test"

[Source]

/*
 * Returns the last matched string.
 *
 *   s = StringScanner.new('test string')
 *   s.match?(/\w+/)     # -> 4
 *   s.matched           # -> "test"
 */
static VALUE
strscan_matched(self)
    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?()

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

[Source]

/*
 * 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(self)
    VALUE self;
{
    struct strscanner *p;

    GET_SCANNER(self, p);
    if (MATCHED_P(p))
        return Qtrue;
    else
        return Qfalse;
}
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

[Source]

/*
 * 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(self)
    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()

Equivalent to matched_size. This method is obsolete; use matched_size instead.

[Source]

/*
 * Equivalent to #matched_size.
 * This method is obsolete; use #matched_size instead.
 */
static VALUE
strscan_matchedsize(self)
    VALUE self;
{
    rb_warning("StringScanner#matchedsize is obsolete; use #matched_size instead");
    return strscan_matched_size(self);
}
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"

[Source]

/*
 * 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(self, vlen)
    VALUE self, 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(p1)

Equivalent to peek. This method is obsolete; use peek instead.

[Source]

/*
 * Equivalent to #peek.
 * This method is obsolete; use #peek instead.
 */
static VALUE
strscan_peep(self, vlen)
    VALUE self, vlen;
{
    rb_warning("StringScanner#peep is obsolete; use #peek instead");
    return strscan_peek(self, vlen);
}
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 1-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

[Source]

/*
 * 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 1-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(self)
    VALUE self;
{
    struct strscanner *p;

    GET_SCANNER(self, p);
    return INT2FIX(p->curr);
}
pos=(n)

Modify the scan pointer.

  s = StringScanner.new('test string')
  s.pos = 7            # -> 7
  s.rest               # -> "ring"

[Source]

/*
 * 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(self, v)
    VALUE self, 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);
}
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 1-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

[Source]

/*
 * 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 1-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(self)
    VALUE self;
{
    struct strscanner *p;

    GET_SCANNER(self, p);
    return INT2FIX(p->curr);
}
pos=(n)

Modify the scan pointer.

  s = StringScanner.new('test string')
  s.pos = 7            # -> 7
  s.rest               # -> "ring"

[Source]

/*
 * 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(self, v)
    VALUE self, 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);
}
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"

[Source]

/*
 * 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(self)
    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));
}
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"

[Source]

/*
 * 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(self)
    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]);
}
reset()

Reset the scan pointer (index 0) and clear matching data.

[Source]

/*
 * Reset the scan pointer (index 0) and clear matching data.
 */
static VALUE
strscan_reset(self)
    VALUE self;
{
    struct strscanner *p;

    GET_SCANNER(self, p);
    p->curr = 0;
    CLEAR_MATCH_STATUS(p);
    return self;
}
rest()

Returns the "rest" of the string (i.e. everything after the scan pointer). If there is no more data (eos? = true), it returns "".

[Source]

/*
 * 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(self)
    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?()

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.

[Source]

/*
 * 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(self)
    VALUE self;
{
    struct strscanner *p;

    GET_SCANNER(self, p);
    if (EOS_P(p))
        return Qfalse;
    else
        return Qtrue;
}
rest_size()

s.rest_size is equivalent to s.rest.size.

[Source]

/*
 * <tt>s.rest_size</tt> is equivalent to <tt>s.rest.size</tt>.
 */
static VALUE
strscan_rest_size(self)
    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()

s.restsize is equivalent to s.rest_size. This method is obsolete; use rest_size instead.

[Source]

/*
 * <tt>s.restsize</tt> is equivalent to <tt>s.rest_size</tt>.
 * This method is obsolete; use #rest_size instead.
 */
static VALUE
strscan_restsize(self)
    VALUE self;
{
    rb_warning("StringScanner#restsize is obsolete; use #rest_size instead");
    return strscan_rest_size(self);
}
scan(pattern)

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

[Source]

/*
 * call-seq: scan(pattern)
 *
 * 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(self, re)
    VALUE self, re;
{
    return strscan_do_scan(self, re, 1, 1, 1);
}
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".

[Source]

/*
 * 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(self, re, s, f)
    VALUE self, re, s, f;
{
    return strscan_do_scan(self, re, RTEST(s), RTEST(f), 1);
}
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

[Source]

/*
 * 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(self, re)
    VALUE self, re;
{
    return strscan_do_scan(self, re, 1, 1, 0);
}
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.

[Source]

/*
 * 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(self, re, s, f)
    VALUE self, re, s, f;
{
    return strscan_do_scan(self, re, RTEST(s), RTEST(f), 0);
}
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

[Source]

/*
 * 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(self, re)
    VALUE self, re;
{
    return strscan_do_scan(self, re, 1, 0, 1);
}
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                           #

[Source]

/*
 * 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(self, re)
    VALUE self, re;
{
    return strscan_do_scan(self, re, 1, 0, 0);
}
string()

Returns the string being scanned.

[Source]

/*
 * Returns the string being scanned.
 */
static VALUE
strscan_get_string(self)
    VALUE self;
{
    struct strscanner *p;

    GET_SCANNER(self, p);
    return p->str;
}
string=(str)

Changes the string being scanned to str and resets the scanner. Returns str.

[Source]

/*
 * call-seq: string=(str)
 *
 * Changes the string being scanned to +str+ and resets the scanner.
 * Returns +str+.
 */
static VALUE
strscan_set_string(self, str)
    VALUE self, 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;
}
terminate
clear

Set the scan pointer to the end of the string and clear matching data.

[Source]

/*
 * call-seq:
 *   terminate
 *   clear
 *
 * Set the scan pointer to the end of the string and clear matching data.
 */
static VALUE
strscan_terminate(self)
    VALUE self;
{
    struct strscanner *p;

    GET_SCANNER(self, p);
    p->curr = S_LEN(p);
    CLEAR_MATCH_STATUS(p);
    return self;
}
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: can't unscan: prev match had failed

[Source]

/*
 * 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: can't unscan: prev match had failed
 */
static VALUE
strscan_unscan(self)
    VALUE self;
{
    struct strscanner *p;

    GET_SCANNER(self, p);
    if (! MATCHED_P(p))
        rb_raise(ScanError, "can't unscan: prev match had failed");

    p->curr = p->prev;
    CLEAR_MATCH_STATUS(p);
    return self;
}


Class: StringScanner::Error

Class | StringScanner::Error
In: | strscan/strscan.c
Parent: | StandardError


File: strscan.c

strscan.c

Path: | strscan/strscan.c
Last Update: | Sat Oct 15 23:43:58 AUS Eastern Standard Time 2005


Module: YAML

Module | YAML
In: | syck/rubyext.c

Classes and Modules

Module YAML::Syck
Class YAML::DomainType
Class YAML::Object
Class YAML::PrivateType


Class: YAML::DomainType

Class | YAML::DomainType
In: | syck/rubyext.c
Parent: | Object

Methods

new

Public Class methods

new(p1, p2, p3)

YAML::DomainType.initialize

[Source]

/*
 * YAML::DomainType.initialize
 */
VALUE
syck_domaintype_initialize( self, domain, type_id, val )
    VALUE self, domain, type_id, val;
{
    rb_iv_set( self, "@domain", domain );
    rb_iv_set( self, "@type_id", type_id );
    rb_iv_set( self, "@value", val );
    return self;
}


Class: YAML::Object

Class | YAML::Object
In: | syck/rubyext.c
Parent: | Object

Methods

new yaml_initialize

Public Class methods

new(p1, p2)

YAML::Object.initialize

[Source]

/*
 * YAML::Object.initialize
 */
VALUE
syck_yobject_initialize( self, klass, ivars )
    VALUE self, klass, ivars;
{
    rb_iv_set( self, "@class", klass );
    rb_iv_set( self, "@ivars", ivars );
    return self;
}

Public Instance methods

yaml_initialize(p1, p2)

YAML::Object.initialize

[Source]

/*
 * YAML::Object.initialize
 */
VALUE
syck_yobject_initialize( self, klass, ivars )
    VALUE self, klass, ivars;
{
    rb_iv_set( self, "@class", klass );
    rb_iv_set( self, "@ivars", ivars );
    return self;
}


Class: YAML::PrivateType

Class | YAML::PrivateType
In: | syck/rubyext.c
Parent: | Object

Methods

new

Public Class methods

new(p1, p2)

YAML::PrivateType.initialize

[Source]

/*
 * YAML::PrivateType.initialize
 */
VALUE
syck_privatetype_initialize( self, type_id, val )
    VALUE self, type_id, val;
{
    rb_iv_set( self, "@type_id", type_id );
    rb_iv_set( self, "@value", val );
    return self;
}


Module: YAML::Syck

Module | YAML::Syck
In: | syck/rubyext.c

Methods

compile

Classes and Modules

Class YAML::Syck::BadAlias
Class YAML::Syck::DefaultKey
Class YAML::Syck::Emitter
Class YAML::Syck::Map
Class YAML::Syck::MergeKey
Class YAML::Syck::Node
Class YAML::Syck::Out
Class YAML::Syck::Parser
Class YAML::Syck::Resolver
Class YAML::Syck::Scalar
Class YAML::Syck::Seq

Public Instance methods

compile(p1)

Convert YAML to bytecode

[Source]

/*
 * Convert YAML to bytecode
 */
VALUE
rb_syck_compile(self, port)
    VALUE self, port;
{
    SYMID oid;
    int taint;
    char *ret;
    VALUE bc;
    bytestring_t *sav;

    SyckParser *parser = syck_new_parser();
    taint = syck_parser_assign_io(parser, port);
    syck_parser_handler( parser, syck_yaml2byte_handler );
    syck_parser_error_handler( parser, NULL );
    syck_parser_implicit_typing( parser, 0 );
    syck_parser_taguri_expansion( parser, 0 );
    oid = syck_parse( parser );
    syck_lookup_sym( parser, oid, (char **)&sav );

    ret = S_ALLOC_N( char, strlen( sav->buffer ) + 3 );
    ret[0] = '\0';
    strcat( ret, "D\n" );
    strcat( ret, sav->buffer );

    syck_free_parser( parser );

    bc = rb_str_new2( ret );
    if ( taint )      OBJ_TAINT( bc );
    return bc;
}


Class: YAML::Syck::BadAlias

Class | YAML::Syck::BadAlias
In: | syck/rubyext.c
Parent: | Object

Methods

<=> new

Public Class methods

new(p1)

YAML::Syck::BadAlias.initialize

[Source]

/*
 * YAML::Syck::BadAlias.initialize
 */
VALUE
syck_badalias_initialize( self, val )
    VALUE self, val;
{
    rb_iv_set( self, "@name", val );
    return self;
}

Public Instance methods

<=>(p1)

YAML::Syck::BadAlias.<=>

[Source]

/*
 * YAML::Syck::BadAlias.<=>
 */
VALUE
syck_badalias_cmp( alias1, alias2 )
    VALUE alias1, alias2;
{
    VALUE str1 = rb_ivar_get( alias1, s_name );
    VALUE str2 = rb_ivar_get( alias2, s_name );
    VALUE val = rb_funcall( str1, s_cmp, 1, str2 );
    return val;
}


Class: YAML::Syck::DefaultKey

Class | YAML::Syck::DefaultKey
In: | syck/rubyext.c
Parent: | Object


Class: YAML::Syck::Emitter

Class | YAML::Syck::Emitter
In: | syck/rubyext.c
Parent: | Object

Methods

emit new node_export reset set_resolver

Public Class methods

new(...)

YAML::Syck::Emitter.reset( options )

[Source]

/*
 * YAML::Syck::Emitter.reset( options )
 */
VALUE
syck_emitter_reset( argc, argv, self )
    int argc;
    VALUE *argv;
    VALUE self;
{
    VALUE options, tmp;
    SyckEmitter *emitter;
    struct emitter_xtra *bonus;
    volatile VALUE hash;    /* protect from GC */

    Data_Get_Struct(self, SyckEmitter, emitter);
    bonus = (struct emitter_xtra *)emitter->bonus;
    if ( bonus != NULL ) S_FREE( bonus );

    bonus = S_ALLOC_N( struct emitter_xtra, 1 );
    bonus->port = rb_str_new2( "" );
    bonus->data = hash = rb_hash_new();

    if (rb_scan_args(argc, argv, "01", &options) == 0)
    {
        options = rb_hash_new();
        rb_ivar_set(self, s_options, options);
    }
    else if ( !NIL_P(tmp = rb_check_string_type(options)) )
    {
        bonus->port = tmp;
    }
    else if ( rb_respond_to( options, s_write ) )
    {
        bonus->port = options;
    }
    else
    {
        Check_Type(options, T_HASH);
        rb_ivar_set(self, s_options, options);
    }

    emitter->headless = 1;
    emitter->bonus = (void *)bonus;
    rb_ivar_set(self, s_level, INT2FIX(0));
    rb_ivar_set(self, s_resolver, Qnil);
    return self;
}

Public Instance methods

emit(...)

YAML::Syck::Emitter.emit( object_id ) { |out| … }

[Source]

/*
 * YAML::Syck::Emitter.emit( object_id ) { |out| ... }
 */
VALUE
syck_emitter_emit( argc, argv, self )
    int argc;
    VALUE *argv;
    VALUE self;
{
    VALUE oid, proc;
    char *anchor_name;
    SyckEmitter *emitter;
    struct emitter_xtra *bonus;
    SYMID symple;
    int level = FIX2INT(rb_ivar_get(self, s_level)) + 1;
    rb_ivar_set(self, s_level, INT2FIX(level));

    rb_scan_args(argc, argv, "1&", &oid, &proc);
    Data_Get_Struct(self, SyckEmitter, emitter);
    bonus = (struct emitter_xtra *)emitter->bonus;

    /* Calculate anchors, normalize nodes, build a simpler symbol table */
    bonus->oid = oid;
    if ( !NIL_P( oid ) && RTEST( rb_funcall( bonus->data, s_haskey, 1, oid ) ) ) {
        symple = rb_hash_aref( bonus->data, oid );
    } else {
        symple = rb_funcall( proc, s_call, 1, rb_ivar_get( self, s_out ) );
    }
    syck_emitter_mark_node( emitter, (st_data_t)symple );

    /* Second pass, build emitted string */
    level -= 1;
    rb_ivar_set(self, s_level, INT2FIX(level));
    if ( level == 0 )
    {
        syck_emit(emitter, (st_data_t)symple);
        syck_emitter_flush(emitter, 0);

        return bonus->port;
    }

    return symple;
}
node_export(p1)

YAML::Syck::Emitter#node_export

[Source]

/*
 * YAML::Syck::Emitter#node_export
 */
VALUE
syck_emitter_node_export( self, node )
    VALUE self, node;
{
    return rb_funcall( node, s_to_yaml, 1, self );
}
reset(...)

YAML::Syck::Emitter.reset( options )

[Source]

/*
 * YAML::Syck::Emitter.reset( options )
 */
VALUE
syck_emitter_reset( argc, argv, self )
    int argc;
    VALUE *argv;
    VALUE self;
{
    VALUE options, tmp;
    SyckEmitter *emitter;
    struct emitter_xtra *bonus;
    volatile VALUE hash;    /* protect from GC */

    Data_Get_Struct(self, SyckEmitter, emitter);
    bonus = (struct emitter_xtra *)emitter->bonus;
    if ( bonus != NULL ) S_FREE( bonus );

    bonus = S_ALLOC_N( struct emitter_xtra, 1 );
    bonus->port = rb_str_new2( "" );
    bonus->data = hash = rb_hash_new();

    if (rb_scan_args(argc, argv, "01", &options) == 0)
    {
        options = rb_hash_new();
        rb_ivar_set(self, s_options, options);
    }
    else if ( !NIL_P(tmp = rb_check_string_type(options)) )
    {
        bonus->port = tmp;
    }
    else if ( rb_respond_to( options, s_write ) )
    {
        bonus->port = options;
    }
    else
    {
        Check_Type(options, T_HASH);
        rb_ivar_set(self, s_options, options);
    }

    emitter->headless = 1;
    emitter->bonus = (void *)bonus;
    rb_ivar_set(self, s_level, INT2FIX(0));
    rb_ivar_set(self, s_resolver, Qnil);
    return self;
}
set_resolver(p1)

YAML::Syck::Emitter#set_resolver

[Source]

/*
 * YAML::Syck::Emitter#set_resolver
 */
VALUE
syck_emitter_set_resolver( self, resolver )
    VALUE self, resolver;
{
    rb_ivar_set( self, s_resolver, resolver );
    return self;
}


Class: YAML::Syck::Map

Class | YAML::Syck::Map
In: | syck/rubyext.c
Parent: | YAML::Syck::Node

Methods

add new style= value=

Public Class methods

new(p1, p2, p3)

YAML::Syck::Map.initialize

[Source]

/*
 * YAML::Syck::Map.initialize
 */
VALUE
syck_map_initialize( self, type_id, val, style )
    VALUE self, type_id, val, style;
{
    SyckNode *node;
    Data_Get_Struct( self, SyckNode, node );

    if ( !NIL_P( val ) )
    {
        VALUE hsh = rb_check_convert_type(val, T_HASH, "Hash", "to_hash");
        VALUE keys;
        int i;
        if ( NIL_P(hsh) )
        {
            rb_raise( rb_eTypeError, "wrong argument type" );
        }

        keys = rb_funcall( hsh, s_keys, 0 );
        for ( i = 0; i < RARRAY(keys)->len; i++ )
        {
            VALUE key = rb_ary_entry(keys, i);
            syck_map_add( node, key, rb_hash_aref(hsh, key) );
        }
    }

    rb_iv_set( self, "@kind", sym_seq );
    rb_funcall( self, s_type_id_set, 1, type_id );
    rb_funcall( self, s_value_set, 1, val );
    rb_funcall( self, s_style_set, 1, style );
    return self;
}

Public Instance methods

add(p1, p2)

YAML::Syck::Map.add

[Source]

/*
 * YAML::Syck::Map.add
 */
VALUE
syck_map_add_m( self, key, val )
    VALUE self, key, val;
{
    SyckNode *node;
    VALUE emitter = rb_ivar_get( self, s_emitter );
    Data_Get_Struct( self, SyckNode, node );

    if ( rb_respond_to( emitter, s_node_export ) ) {
        key = rb_funcall( emitter, s_node_export, 1, key );
        val = rb_funcall( emitter, s_node_export, 1, val );
    }
    syck_map_add( node, key, val );
    rb_hash_aset( rb_ivar_get( self, s_value ), key, val );

    return self;
}
style=(p1)

YAML::Syck::Map.style=

[Source]

/*
 * YAML::Syck::Map.style=
 */
VALUE
syck_map_style_set( self, style )
    VALUE self, style;
{
    SyckNode *node;
    Data_Get_Struct( self, SyckNode, node );

    if ( style == sym_inline )
    {
        node->data.pairs->style = map_inline;
    }
    else
    {
        node->data.pairs->style = map_none;
    }

    rb_iv_set( self, "@style", style );
    return self;
}
value=(p1)

YAML::Syck::Map.value=

[Source]

/*
 * YAML::Syck::Map.value=
 */
VALUE
syck_map_value_set( self, val )
    VALUE self, val;
{
    SyckNode *node;
    Data_Get_Struct( self, SyckNode, node );

    if ( !NIL_P( val ) )
    {
        VALUE hsh = rb_check_convert_type(val, T_HASH, "Hash", "to_hash");
        VALUE keys;
        int i;
        if ( NIL_P(hsh) )
        {
            rb_raise( rb_eTypeError, "wrong argument type" );
        }

        syck_map_empty( node );
        keys = rb_funcall( hsh, s_keys, 0 );
        for ( i = 0; i < RARRAY(keys)->len; i++ )
        {
            VALUE key = rb_ary_entry(keys, i);
            syck_map_add( node, key, rb_hash_aref(hsh, key) );
        }
    }

    rb_iv_set( self, "@value", val );
    return val;
}


Class: YAML::Syck::MergeKey

Class | YAML::Syck::MergeKey
In: | syck/rubyext.c
Parent: | Object


Class: YAML::Syck::Node

Class | YAML::Syck::Node
In: | syck/rubyext.c
Parent: | Object

Methods

initialize_copy transform type_id=

Public Instance methods

initialize_copy(p1)

Cloning method for all node types

[Source]

/*
 * Cloning method for all node types
 */
VALUE
syck_node_init_copy( copy, orig )
    VALUE copy, orig;
{
    SyckNode *copy_n;
    SyckNode *orig_n;

    if ( copy == orig )
        return copy;

    if ( TYPE( orig ) != T_DATA ||
         RDATA( orig )->dfree != ( RUBY_DATA_FUNC )rb_syck_free_node )
    {
        rb_raise( rb_eTypeError, "wrong argument type" );
    }

    Data_Get_Struct( orig, SyckNode, orig_n );
    Data_Get_Struct( copy, SyckNode, copy_n );
    MEMCPY( copy_n, orig_n, SyckNode, 1 );
    return copy;
}
transform()

YAML::Syck::Node.transform

[Source]

/*
 * YAML::Syck::Node.transform
 */
VALUE
syck_node_transform( self )
    VALUE self;
{
    VALUE t;
    SyckNode *n;
    SyckNode *orig_n;
    Data_Get_Struct(self, SyckNode, orig_n);

    switch (orig_n->kind)
    {
        case syck_map_kind:
            {
                int i;
                n = syck_alloc_map();
                for ( i = 0; i < orig_n->data.pairs->idx; i++ )
                {
                    syck_map_add( n, rb_funcall( syck_map_read( orig_n, map_key, i ), s_transform, 0 ),
                                     rb_funcall( syck_map_read( orig_n, map_value, i ), s_transform, 0 ) );
                }
            }
        break;

        case syck_seq_kind:
            {
                int i;
                n = syck_alloc_seq();
                for ( i = 0; i < orig_n->data.list->idx; i++ )
                {
                    syck_seq_add( n, rb_funcall( syck_seq_read( orig_n, i ), s_transform, 0 ) );
                }
            }
        break;

        case syck_str_kind:
            n = syck_new_str2( orig_n->data.str->ptr, orig_n->data.str->len, orig_n->data.str->style );
        break;
    }

    if ( orig_n->type_id != NULL )
    {
        n->type_id = syck_strndup( orig_n->type_id, strlen( orig_n->type_id ) );
    }
    if ( orig_n->anchor != NULL )
    {
        n->anchor = syck_strndup( orig_n->anchor, strlen( orig_n->anchor ) );
    }
    t = Data_Wrap_Struct( cNode, NULL, NULL, n );
    n->id = t;
    t = rb_funcall( oDefaultResolver, s_node_import, 1, t );
    syck_free_node( n );
    return t;
}
type_id=(p1)

YAML::Syck::Node#type_id=

[Source]

/*
 * YAML::Syck::Node#type_id=
 */
VALUE
syck_node_type_id_set( self, type_id )
    VALUE self, type_id;
{
    SyckNode *node;
    Data_Get_Struct( self, SyckNode, node );

    if ( node->type_id != NULL ) S_FREE( node->type_id );

    if ( NIL_P( type_id ) ) {
        node->type_id = NULL;
    } else {
        node->type_id = StringValuePtr( type_id );
    }

    rb_iv_set( self, "@type_id", type_id );
    return type_id;
}


Class: YAML::Syck::Out

Class | YAML::Syck::Out
In: | syck/rubyext.c
Parent: | Object

Methods

map new scalar seq

Public Class methods

new(p1)

YAML::Syck::Out::initialize

[Source]

/*
 * YAML::Syck::Out::initialize
 */
VALUE
syck_out_initialize( self, emitter )
    VALUE self, emitter;
{
    rb_ivar_set( self, s_emitter, emitter );
    return self;
}

Public Instance methods

map(...)

YAML::Syck::Out::map

[Source]

/*
 * YAML::Syck::Out::map
 */
VALUE
syck_out_map( argc, argv, self )
    int argc;
    VALUE *argv;
    VALUE self;
{
    VALUE type_id, style, map;
    if (rb_scan_args(argc, argv, "11", &type_id, &style) == 1) {
        style = Qnil;
    }
    map = rb_funcall( cMap, s_new, 3, type_id, rb_hash_new(), style );
    syck_out_mark( rb_ivar_get( self, s_emitter ), map );
    rb_yield( map );
    return map;
}
scalar(...)
   YAML::Syck::Out::scalar

syck_out_scalar( self, type_id, str, style )

    VALUE self, type_id, str, style;

[Source]

/*
 * YAML::Syck::Out::scalar
syck_out_scalar( self, type_id, str, style )
    VALUE self, type_id, str, style;
 */
VALUE
syck_out_scalar( argc, argv, self )
    int argc;
    VALUE *argv;
    VALUE self;
{
    VALUE type_id, str, style, scalar;
    if (rb_scan_args(argc, argv, "21", &type_id, &str, &style) == 2) {
        style = Qnil;
    }
    scalar = rb_funcall( cScalar, s_new, 3, type_id, str, style );
    syck_out_mark( rb_ivar_get( self, s_emitter ), scalar );
    return scalar;
}
seq(...)

YAML::Syck::Out::seq

[Source]

/*
 * YAML::Syck::Out::seq
 */
VALUE
syck_out_seq( argc, argv, self )
    int argc;
    VALUE *argv;
    VALUE self;
{
    VALUE type_id, style, seq;
    if (rb_scan_args(argc, argv, "11", &type_id, &style) == 1) {
        style = Qnil;
    }
    seq = rb_funcall( cSeq, s_new, 3, type_id, rb_ary_new(), style );
    syck_out_mark( rb_ivar_get( self, s_emitter ), seq );
    rb_yield( seq );
    return seq;
}


Class: YAML::Syck::Parser

Class | YAML::Syck::Parser
In: | syck/rubyext.c
Parent: | Object

Methods

bufsize bufsize= load load_documents new set_resolver

Public Class methods

new(...)

YAML::Syck::Parser.initialize( resolver, options )

[Source]

/*
 * YAML::Syck::Parser.initialize( resolver, options )
 */
static VALUE
syck_parser_initialize(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    VALUE options;
    if (rb_scan_args(argc, argv, "01", &options) == 0)
    {
        options = rb_hash_new();
    }
    else
    {
        Check_Type(options, T_HASH);
    }
    rb_ivar_set(self, s_options, options);
    return self;
}

Public Instance methods

bufsize()

YAML::Syck::Parser.bufsize => Integer

[Source]

/*
 * YAML::Syck::Parser.bufsize => Integer
 */
static VALUE
syck_parser_bufsize_get( self )
    VALUE self;
{
    SyckParser *parser;

    Data_Get_Struct(self, SyckParser, parser);
    return INT2FIX( parser->bufsize );
}
bufsize=(p1)

YAML::Syck::Parser.bufsize = Integer

[Source]

/*
 * YAML::Syck::Parser.bufsize = Integer
 */
static VALUE
syck_parser_bufsize_set( self, size )
    VALUE self, size;
{
    SyckParser *parser;

    if ( rb_respond_to( size, s_to_i ) ) {
        int n = NUM2INT(rb_funcall(size, s_to_i, 0));
        Data_Get_Struct(self, SyckParser, parser);
        parser->bufsize = n;
    }
    return self;
}
load(...)

YAML::Syck::Parser.load( IO or String )

[Source]

/*
 * YAML::Syck::Parser.load( IO or String )
 */
VALUE
syck_parser_load(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    VALUE port, proc, model, input;
    SyckParser *parser;
    struct parser_xtra *bonus = S_ALLOC_N( struct parser_xtra, 1 );
    volatile VALUE hash;    /* protect from GC */

    rb_scan_args(argc, argv, "11", &port, &proc);

    input = rb_hash_aref( rb_attr_get( self, s_options ), sym_input );
    model = rb_hash_aref( rb_attr_get( self, s_options ), sym_model );
    Data_Get_Struct(self, SyckParser, parser);
    syck_set_model( self, input, model );

    bonus->taint = syck_parser_assign_io(parser, port);
    bonus->data = hash = rb_hash_new();
    bonus->resolver = rb_attr_get( self, s_resolver );
    if ( NIL_P( proc ) ) bonus->proc = 0;
    else                 bonus->proc = proc;

    parser->bonus = (void *)bonus;

    return syck_parse( parser );
}
load_documents(...)

YAML::Syck::Parser.load_documents( IO or String ) { |doc| }

[Source]

/*
 * YAML::Syck::Parser.load_documents( IO or String ) { |doc| }
 */
VALUE
syck_parser_load_documents(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    VALUE port, proc, v, input, model;
    SyckParser *parser;
    struct parser_xtra *bonus = S_ALLOC_N( struct parser_xtra, 1 );
    volatile VALUE hash;

    rb_scan_args(argc, argv, "1&", &port, &proc);

    input = rb_hash_aref( rb_attr_get( self, s_options ), sym_input );
    model = rb_hash_aref( rb_attr_get( self, s_options ), sym_model );
    Data_Get_Struct(self, SyckParser, parser);
    syck_set_model( self, input, model );

    bonus->taint = syck_parser_assign_io(parser, port);
    bonus->resolver = rb_attr_get( self, s_resolver );
    bonus->proc = 0;
    parser->bonus = (void *)bonus;

    while ( 1 )
    {
        /* Reset hash for tracking nodes */
        bonus->data = hash = rb_hash_new();

        /* Parse a document */
        v = syck_parse( parser );
        if ( parser->eof == 1 )
        {
            break;
        }

        /* Pass document to block */
        rb_funcall( proc, s_call, 1, v );
    }

    return Qnil;
}
set_resolver(p1)

YAML::Syck::Parser#set_resolver

[Source]

/*
 * YAML::Syck::Parser#set_resolver
 */
VALUE
syck_parser_set_resolver( self, resolver )
    VALUE self, resolver;
{
    rb_ivar_set( self, s_resolver, resolver );
    return self;
}


Class: YAML::Syck::Resolver

Class | YAML::Syck::Resolver
In: | syck/rubyext.c
Parent: | Object

Methods

add_type detect_implicit new node_import tagurize transfer use_types_at

Public Class methods

new()

YAML::Syck::Resolver.initialize

[Source]

/*
 * YAML::Syck::Resolver.initialize
 */
static VALUE
syck_resolver_initialize( self )
    VALUE self;
{
    VALUE tags = rb_hash_new();
    rb_ivar_set(self, s_tags, rb_hash_new());
    return self;
}

Public Instance methods

add_type(p1, p2)

YAML::Syck::Resolver#add_type

[Source]

/*
 * YAML::Syck::Resolver#add_type
 */
VALUE
syck_resolver_add_type( self, taguri, cls )
    VALUE self, taguri, cls;
{
    VALUE tags = rb_attr_get(self, s_tags);
    rb_hash_aset( tags, taguri, cls );
    return Qnil;
}
detect_implicit(p1)

YAML::Syck::Resolver#detect_implicit

[Source]

/*
 * YAML::Syck::Resolver#detect_implicit
 */
VALUE
syck_resolver_detect_implicit( self, val )
    VALUE self, val;
{
    char *type_id;
    return rb_str_new2( "" );
}
node_import(p1)

YAML::Syck::Resolver#node_import

[Source]

/*
 * YAML::Syck::Resolver#node_import
 */
VALUE
syck_resolver_node_import( self, node )
    VALUE self, node;
{
    SyckNode *n;
    VALUE obj;
    int i = 0;
    Data_Get_Struct(node, SyckNode, n);

    switch (n->kind)
    {
        case syck_str_kind:
            obj = rb_str_new( n->data.str->ptr, n->data.str->len );
        break;

        case syck_seq_kind:
            obj = rb_ary_new2( n->data.list->idx );
            for ( i = 0; i < n->data.list->idx; i++ )
            {
                rb_ary_store( obj, i, syck_seq_read( n, i ) );
            }
        break;

        case syck_map_kind:
            obj = rb_hash_new();
            for ( i = 0; i < n->data.pairs->idx; i++ )
            {
                VALUE k = syck_map_read( n, map_key, i );
                VALUE v = syck_map_read( n, map_value, i );
                int skip_aset = 0;

                /*
                 * Handle merge keys
                 */
                if ( rb_obj_is_kind_of( k, cMergeKey ) )
                {
                    if ( rb_obj_is_kind_of( v, rb_cHash ) )
                    {
                        VALUE dup = rb_funcall( v, s_dup, 0 );
                        rb_funcall( dup, s_update, 1, obj );
                        obj = dup;
                        skip_aset = 1;
                    }
                    else if ( rb_obj_is_kind_of( v, rb_cArray ) )
                    {
                        VALUE end = rb_ary_pop( v );
                        if ( rb_obj_is_kind_of( end, rb_cHash ) )
                        {
                            VALUE dup = rb_funcall( end, s_dup, 0 );
                            v = rb_ary_reverse( v );
                            rb_ary_push( v, obj );
                            rb_iterate( rb_each, v, syck_merge_i, dup );
                            obj = dup;
                            skip_aset = 1;
                        }
                    }
                }
                else if ( rb_obj_is_kind_of( k, cDefaultKey ) )
                {
                    rb_funcall( obj, s_default_set, 1, v );
                    skip_aset = 1;
                }

                if ( ! skip_aset )
                {
                    rb_hash_aset( obj, k, v );
                }
            }
        break;
    }

    if ( n->type_id != NULL )
    {
        obj = rb_funcall( self, s_transfer, 2, rb_str_new2( n->type_id ), obj );
    }
    return obj;
}
tagurize(p1)

YAML::Syck::Resolver#tagurize

[Source]

/*
 * YAML::Syck::Resolver#tagurize
 */
VALUE
syck_resolver_tagurize( self, val )
    VALUE self, val;
{
    VALUE tmp = rb_check_string_type(val);

    if ( !NIL_P(tmp) )
    {
        char *taguri;
        val = tmp;
        taguri = syck_type_id_to_uri( RSTRING(val)->ptr );
        return rb_str_new2( taguri );
    }

    return val;
}
transfer(p1, p2)

YAML::Syck::Resolver#transfer

[Source]

/*
 * YAML::Syck::Resolver#transfer
 */
VALUE
syck_resolver_transfer( self, type, val )
    VALUE self, type, val;
{
    if (NIL_P(type) || RSTRING(StringValue(type))->len == 0)
    {
        type = rb_funcall( self, s_detect_implicit, 1, val );
    }

    if ( ! (NIL_P(type) || RSTRING(StringValue(type))->len == 0) )
    {
        VALUE str_xprivate = rb_str_new2( "x-private" );
        VALUE colon = rb_str_new2( ":" );
        VALUE tags = rb_attr_get(self, s_tags);
        VALUE target_class = rb_hash_aref( tags, type );
        VALUE subclass = target_class;
        VALUE obj = Qnil;

        /*
         * Should no tag match exactly, check for subclass format
         */
        if ( NIL_P( target_class ) )
        {
            VALUE subclass_parts = rb_ary_new();
            VALUE parts = rb_str_split( type, ":" );

            while ( RARRAY(parts)->len > 1 )
            {
                VALUE partial;
                rb_ary_unshift( subclass_parts, rb_ary_pop( parts ) );
                partial = rb_ary_join( parts, colon );
                target_class = rb_hash_aref( tags, partial );
                if ( NIL_P( target_class ) )
                {
                    rb_str_append( partial, colon );
                    target_class = rb_hash_aref( tags, partial );
                }

                /*
                 * Possible subclass found, see if it supports subclassing
                 */
                if ( ! NIL_P( target_class ) )
                {
                    subclass = target_class;
                    if ( RARRAY(subclass_parts)->len > 0 && rb_respond_to( target_class, s_tag_subclasses ) &&
                         RTEST( rb_funcall( target_class, s_tag_subclasses, 0 ) ) )
                    {
                        VALUE subclass_v;
                        subclass = rb_ary_join( subclass_parts, colon );
                        subclass = rb_funcall( target_class, s_tag_read_class, 1, subclass );
                        subclass_v = syck_const_find( subclass );

                        if ( subclass_v != Qnil )
                        {
                            subclass = subclass_v;
                        }
                        else if ( rb_cObject == target_class && subclass_v == Qnil )
                        {
                            target_class = cYObject;
                            type = subclass;
                            subclass = cYObject;
                        }
                    }
                    break;
                }
            }
        }

        /* rb_raise(rb_eTypeError, "invalid typing scheme: %s given",
         *         scheme);
         */

        if ( rb_respond_to( target_class, s_call ) )
        {
            obj = rb_funcall( target_class, s_call, 2, type, val );
        }
        else
        {
            if ( rb_respond_to( target_class, s_yaml_new ) )
            {
                obj = rb_funcall( target_class, s_yaml_new, 3, subclass, type, val );
            }
            else if ( !NIL_P( target_class ) )
            {
                obj = rb_obj_alloc( subclass );
                if ( rb_respond_to( obj, s_yaml_initialize ) )
                {
                    rb_funcall( obj, s_yaml_initialize, 2, type, val );
                }
                else if ( !NIL_P( obj ) && rb_obj_is_instance_of( val, rb_cHash ) )
                {
                    rb_iterate( rb_each, val, syck_set_ivars, obj );
                }
            }
            else
            {
                VALUE parts = rb_str_split( type, ":" );
                VALUE scheme = rb_ary_shift( parts );
                if ( rb_str_cmp( scheme, str_xprivate ) == 0 )
                {
                    VALUE name = rb_ary_join( parts, colon );
                    obj = rb_funcall( cPrivateType, s_new, 2, name, val );
                }
                else
                {
                    VALUE domain = rb_ary_shift( parts );
                    VALUE name = rb_ary_join( parts, colon );
                    obj = rb_funcall( cDomainType, s_new, 3, domain, name, val );
                }
            }
        }
        val = obj;
    }

    return val;
}
use_types_at(p1)

YAML::Syck::Resolver#use_types_at

[Source]

/*
 * YAML::Syck::Resolver#use_types_at
 */
VALUE
syck_resolver_use_types_at( self, hsh )
    VALUE self, hsh;
{
    rb_ivar_set( self, s_tags, hsh );
    return Qnil;
}


Class: YAML::Syck::Scalar

Class | YAML::Syck::Scalar
In: | syck/rubyext.c
Parent: | YAML::Syck::Node

Methods

new style= value=

Public Class methods

new(p1, p2, p3)

YAML::Syck::Scalar.initialize

[Source]

/*
 * YAML::Syck::Scalar.initialize
 */
VALUE
syck_scalar_initialize( self, type_id, val, style )
    VALUE self, type_id, val, style;
{
    rb_iv_set( self, "@kind", sym_scalar );
    rb_funcall( self, s_type_id_set, 1, type_id );
    rb_funcall( self, s_value_set, 1, val );
    rb_funcall( self, s_style_set, 1, style );
    return self;
}

Public Instance methods

style=(p1)

YAML::Syck::Scalar.style=

[Source]

/*
 * YAML::Syck::Scalar.style=
 */
VALUE
syck_scalar_style_set( self, style )
    VALUE self, style;
{
    SyckNode *node;
    Data_Get_Struct( self, SyckNode, node );

    if ( NIL_P( style ) )
    {
        node->data.str->style = scalar_none;
    }
    else if ( style == sym_1quote )
    {
        node->data.str->style = scalar_1quote;
    }
    else if ( style == sym_2quote )
    {
        node->data.str->style = scalar_2quote;
    }
    else if ( style == sym_fold )
    {
        node->data.str->style = scalar_fold;
    }
    else if ( style == sym_literal )
    {
        node->data.str->style = scalar_literal;
    }
    else if ( style == sym_plain )
    {
        node->data.str->style = scalar_plain;
    }

    rb_iv_set( self, "@style", style );
    return self;
}
value=(p1)

YAML::Syck::Scalar.value=

[Source]

/*
 * YAML::Syck::Scalar.value=
 */
VALUE
syck_scalar_value_set( self, val )
    VALUE self, val;
{
    SyckNode *node;
    Data_Get_Struct( self, SyckNode, node );

    StringValue( val );
    node->data.str->ptr = RSTRING(val)->ptr;
    node->data.str->len = RSTRING(val)->len;
    node->data.str->style = scalar_none;

    rb_iv_set( self, "@value", val );
    return val;
}


Class: YAML::Syck::Seq

Class | YAML::Syck::Seq
In: | syck/rubyext.c
Parent: | YAML::Syck::Node

Methods

add new style= value=

Public Class methods

new(p1, p2, p3)

YAML::Syck::Seq.initialize

[Source]

/*
 * YAML::Syck::Seq.initialize
 */
VALUE
syck_seq_initialize( self, type_id, val, style )
    VALUE self, type_id, val, style;
{
    SyckNode *node;
    Data_Get_Struct( self, SyckNode, node );

    rb_iv_set( self, "@kind", sym_seq );
    rb_funcall( self, s_type_id_set, 1, type_id );
    rb_funcall( self, s_value_set, 1, val );
    rb_funcall( self, s_style_set, 1, style );
    return self;
}

Public Instance methods

add(p1)

YAML::Syck::Seq.add

[Source]

/*
 * YAML::Syck::Seq.add
 */
VALUE
syck_seq_add_m( self, val )
    VALUE self, val;
{
    SyckNode *node;
    VALUE emitter = rb_ivar_get( self, s_emitter );
    Data_Get_Struct( self, SyckNode, node );

    if ( rb_respond_to( emitter, s_node_export ) ) {
        val = rb_funcall( emitter, s_node_export, 1, val );
    }
    syck_seq_add( node, val );
    rb_ary_push( rb_ivar_get( self, s_value ), val );

    return self;
}
style=(p1)

YAML::Syck::Seq.style=

[Source]

/*
 * YAML::Syck::Seq.style=
 */
VALUE
syck_seq_style_set( self, style )
    VALUE self, style;
{
    SyckNode *node;
    Data_Get_Struct( self, SyckNode, node );

    if ( style == sym_inline )
    {
        node->data.list->style = seq_inline;
    }
    else
    {
        node->data.list->style = seq_none;
    }

    rb_iv_set( self, "@style", style );
    return self;
}
value=(p1)

YAML::Syck::Seq.value=

[Source]

/*
 * YAML::Syck::Seq.value=
 */
VALUE
syck_seq_value_set( self, val )
    VALUE self, val;
{
    SyckNode *node;
    Data_Get_Struct( self, SyckNode, node );

    val = rb_check_array_type( val );
    if ( !NIL_P( val ) ) {
        int i;
        syck_seq_empty( node );
        for ( i = 0; i < RARRAY( val )->len; i++ )
        {
            syck_seq_add( node, rb_ary_entry(val, i) );
        }
    }

    rb_iv_set( self, "@value", val );
    return val;
}


File: bytecode.c

bytecode.c

Path: | syck/bytecode.c
Last Update: | Sat Oct 15 23:43:58 AUS Eastern Standard Time 2005


File: emitter.c

emitter.c

Path: | syck/emitter.c
Last Update: | Sat Oct 15 23:43:58 AUS Eastern Standard Time 2005


File: gram.c

gram.c

Path: | syck/gram.c
Last Update: | Sat Oct 15 23:43:58 AUS Eastern Standard Time 2005


File: handler.c

handler.c

Path: | syck/handler.c
Last Update: | Sat Oct 15 23:43:58 AUS Eastern Standard Time 2005


File: implicit.c

implicit.c

Path: | syck/implicit.c
Last Update: | Fri Oct 28 08:39:51 AUS Eastern Standard Time 2005


File: node.c

node.c

Path: | syck/node.c
Last Update: | Sat Oct 15 23:43:58 AUS Eastern Standard Time 2005


File: rubyext.c

rubyext.c

Path: | syck/rubyext.c
Last Update: | Sat Oct 15 23:43:58 AUS Eastern Standard Time 2005


File: syck.c

syck.c

Path: | syck/syck.c
Last Update: | Sat Oct 15 23:43:58 AUS Eastern Standard Time 2005


File: token.c

token.c

Path: | syck/token.c
Last Update: | Sat Oct 15 23:43:58 AUS Eastern Standard Time 2005


File: yaml2byte.c

yaml2byte.c

Path: | syck/yaml2byte.c
Last Update: | Sat Oct 15 23:43:58 AUS Eastern Standard Time 2005


File: sync.rb

sync.rb

Path: | sync.rb
Last Update: | Thu Jun 07 00:19:33 AUS Eastern Standard Time 2001
  sync.rb - 2 phase lock with counter
      $Release Version: 1.0$
      $Revision: 1.4 $
      $Date: 2001/06/06 14:19:33 $
      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


Class: Sync

Class | Sync
In: | sync.rb
Parent: | Object

Methods

new

Included Modules

Sync_m

Public Class methods

new()

[Source]

# File sync.rb, line 306
  def initialize
    super
  end


Module: Sync_m

Module | Sync_m
In: | 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: /src/ruby/lib/sync.rb,v 1.4 2001/06/06 14:19:33 keiju Exp $-'
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)

[Source]

# File 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
define_aliases(cl)

[Source]

# File 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
extend_object(obj)

[Source]

# File sync.rb, line 99
  def Sync_m.extend_object(obj)
    super
    obj.sync_extended
  end
new(*args)

[Source]

# File sync.rb, line 254
  def initialize(*args)
    sync_initialize
    super
  end

Public Instance methods

sync_exclusive?()

[Source]

# File sync.rb, line 126
  def sync_exclusive?
    sync_mode == EX
  end
sync_extended()

[Source]

# File 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_lock(m = EX)

[Source]

# File 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_locked?()

accessing

[Source]

# File sync.rb, line 118
  def sync_locked?
    sync_mode != UN
  end
sync_shared?()

[Source]

# File sync.rb, line 122
  def sync_shared?
    sync_mode == SH
  end
sync_synchronize(mode = EX) {|| ...}

[Source]

# File sync.rb, line 226
  def sync_synchronize(mode = EX)
    begin
      sync_lock(mode)
      yield
    ensure
      sync_unlock
    end
  end
sync_try_lock(mode = EX)

locking methods.

[Source]

# File 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_unlock(m = EX)

[Source]

# File 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


Class: Sync_m::Err

Class | Sync_m::Err
In: | 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)

[Source]

# File sync.rb, line 56
    def Err.Fail(*opt)
      fail self, sprintf(self::Message, *opt)
    end


Class: Sync_m::Err::LockModeFailer

Class | Sync_m::Err::LockModeFailer
In: | sync.rb
Parent: | Err

Methods

Fail

Constants

Message = "Unknown lock mode(%s)"

Public Class methods

Fail(mode)

[Source]

# File sync.rb, line 69
      def LockModeFailer.Fail(mode)
        if mode.id2name
          mode = id2name
        end
        super(mode)
      end


Class: Sync_m::Err::UnknownLocker

Class | Sync_m::Err::UnknownLocker
In: | sync.rb
Parent: | Err

Methods

Fail

Constants

Message = "Thread(%s) not locked."

Public Class methods

Fail(th)

[Source]

# File sync.rb, line 62
      def UnknownLocker.Fail(th)
        super(th.inspect)
      end


Module: Syslog

Module | Syslog
In: | syslog/syslog.c

Init for package syslog

Methods

LOG_MASK LOG_UPTO close facility ident inspect instance log mask mask= open open! opened? options reopen

Included Modules

mSyslogConstants

Classes and Modules

Module Syslog::Constants

Public Instance methods

LOG_MASK(p1)
LOG_UPTO(p1)
close()

Syslog module methods

[Source]

/* Syslog module methods */
static VALUE mSyslog_close(VALUE self)
{
    if (!syslog_opened) {
        rb_raise(rb_eRuntimeError, "syslog not opened");
    }

    closelog();

    free((void *)syslog_ident);
    syslog_ident = NULL;
    syslog_options = syslog_facility = syslog_mask = -1;
    syslog_opened = 0;

    return Qnil;
}
facility()
ident()
inspect()
instance()
log(...)
mask()
mask=(p1)
open(...)
open!(...)
opened?()
options()
reopen(...)


Module: Syslog::Constants

Module | Syslog::Constants
In: | syslog/syslog.c

Methods

LOG_MASK LOG_UPTO

Public Instance methods

LOG_MASK(p1)
LOG_UPTO(p1)


Class: TestSyslog

Class | TestSyslog
In: | syslog/test.rb
Parent: | Test::Unit::TestCase

Methods

test_close test_inspect test_instance test_log test_mask test_new test_open test_opened?

Public Instance methods

test_close()

[Source]

# File syslog/test.rb, line 90
  def test_close
    assert_raises(RuntimeError) {
      Syslog.close
    }
  end
test_inspect()

[Source]

# File syslog/test.rb, line 151
  def test_inspect
    Syslog.open { |sl|
      assert_equal(format('<#%s: opened=true, ident="%s", options=%d, facility=%d, mask=%d>',
                          Syslog,
                          sl.ident,
                          sl.options,
                          sl.facility,
                          sl.mask),
                   sl.inspect)
    }

    assert_equal(format('<#%s: opened=false>', Syslog), Syslog.inspect)
  end
test_instance()

[Source]

# File syslog/test.rb, line 22
  def test_instance
    sl1 = Syslog.instance
    sl2 = Syslog.open
    sl3 = Syslog.instance

    assert_equal(Syslog, sl1)
    assert_equal(Syslog, sl2)
    assert_equal(Syslog, sl3)
  ensure
    Syslog.close if Syslog.opened?
  end
test_log()

[Source]

# File syslog/test.rb, line 114
  def test_log
    stderr = IO::pipe

    pid = fork {
      stderr[0].close
      STDERR.reopen(stderr[1])
      stderr[1].close

      options = Syslog::LOG_PERROR | Syslog::LOG_NDELAY

      Syslog.open("syslog_test", options) { |sl|
        sl.log(Syslog::LOG_NOTICE, "test1 - hello, %s!", "world")
        sl.notice("test1 - hello, %s!", "world")
      }

      Syslog.open("syslog_test", options | Syslog::LOG_PID) { |sl|
        sl.log(Syslog::LOG_CRIT, "test2 - pid")
        sl.crit("test2 - pid")
      }
      exit!
    }

    stderr[1].close
    Process.waitpid(pid)

    # LOG_PERROR is not yet implemented on Cygwin.
    return if RUBY_PLATFORM =~ /cygwin/

    2.times {
      assert_equal("syslog_test: test1 - hello, world!\n", stderr[0].gets)
    }

    2.times {
      assert_equal(format("syslog_test[%d]: test2 - pid\n", pid), stderr[0].gets)
    }
  end
test_mask()

[Source]

# File syslog/test.rb, line 96
  def test_mask
    assert_equal(nil, Syslog.mask)

    Syslog.open

    orig = Syslog.mask

    Syslog.mask = Syslog.LOG_UPTO(Syslog::LOG_ERR)
    assert_equal(Syslog.LOG_UPTO(Syslog::LOG_ERR), Syslog.mask)

    Syslog.mask = Syslog.LOG_MASK(Syslog::LOG_CRIT)
    assert_equal(Syslog.LOG_MASK(Syslog::LOG_CRIT), Syslog.mask)

    Syslog.mask = orig
  ensure
    Syslog.close if Syslog.opened?
  end
test_new()

[Source]

# File syslog/test.rb, line 16
  def test_new
    assert_raises(NoMethodError) {
      Syslog.new
    }
  end
test_open()

[Source]

# File syslog/test.rb, line 34
  def test_open
    # default parameters
    Syslog.open

    assert_equal($0, Syslog.ident)
    assert_equal(Syslog::LOG_PID | Syslog::LOG_CONS, Syslog.options)
    assert_equal(Syslog::LOG_USER, Syslog.facility)

    # open without close
    assert_raises(RuntimeError) {
      Syslog.open
    }

    Syslog.close

    # given parameters
    Syslog.open("foo", Syslog::LOG_NDELAY | Syslog::LOG_PERROR, Syslog::LOG_DAEMON)

    assert_equal('foo', Syslog.ident)
    assert_equal(Syslog::LOG_NDELAY | Syslog::LOG_PERROR, Syslog.options)
    assert_equal(Syslog::LOG_DAEMON, Syslog.facility)

    Syslog.close

    # default parameters again (after close)
    Syslog.open
    Syslog.close

    assert_equal(nil, Syslog.ident)
    assert_equal(nil, Syslog.options)
    assert_equal(nil, Syslog.facility)

    # block
    param = nil
    Syslog.open { |param| }
    assert_equal(Syslog, param)
  ensure
    Syslog.close if Syslog.opened?
  end
test_opened?()

[Source]

# File syslog/test.rb, line 74
  def test_opened?
    assert_equal(false, Syslog.opened?)

    Syslog.open
    assert_equal(true, Syslog.opened?)

    Syslog.close
    assert_equal(false, Syslog.opened?)

    Syslog.open {
      assert_equal(true, Syslog.opened?)
    }

    assert_equal(false, Syslog.opened?)
  end


File: syslog.c

syslog.c

Path: | syslog/syslog.c
Last Update: | Sat Oct 15 23:43:58 AUS Eastern Standard Time 2005


File: test.rb

test.rb

Path: | syslog/test.rb
Last Update: | Wed Nov 27 18:36:22 AUS Eastern Daylight Time 2002

$RoughId: test.rb,v 1.9 2002/02/25 08:20:14 knu Exp $ $Id: test.rb,v 1.4 2002/11/27 08:36:22 knu Exp $

Required files

test/unit syslog


Module: TclTkLib

Module | TclTkLib
In: | tcltklib/tcltklib.c

—- initialization —-

Methods

_conv_listelement _fromUTF8 _merge_tklist _split_tklist _subst_Tcl_backslash _subst_UTF_backslash _toUTF8 do_one_event do_thread_callback encoding encoding= encoding_system encoding_system= get_eventloop_tick get_eventloop_weight get_no_event_wait mainloop mainloop_abort_on_exception mainloop_abort_on_exception= mainloop_thread? mainloop_watchdog num_of_mainwindows set_eventloop_tick set_eventloop_weight set_max_block_time set_no_event_wait

Classes and Modules

Module TclTkLib::EventFlag
Module TclTkLib::VarAccessFlag

Public Instance methods

_conv_listelement(p1)
_fromUTF8(...)
_merge_tklist(...)
_split_tklist(p1)
_subst_Tcl_backslash(p1)
_subst_UTF_backslash(p1)
_toUTF8(...)
do_one_event(...)
do_thread_callback(...)
encoding()
encoding=(p1)
encoding_system()
encoding_system=(p1)
get_eventloop_tick()
get_eventloop_weight()
get_no_event_wait()
mainloop(...)

execute Tk_MainLoop

[Source]

/* execute Tk_MainLoop */
static VALUE
lib_mainloop(argc, argv, self)
    int   argc;
    VALUE *argv;
    VALUE self;
{
    VALUE check_rootwidget;

    if (rb_scan_args(argc, argv, "01", &check_rootwidget) == 0) {
        check_rootwidget = Qtrue;
    } else if (RTEST(check_rootwidget)) {
        check_rootwidget = Qtrue;
    } else {
        check_rootwidget = Qfalse;
    }

    return lib_eventloop_launcher(RTEST(check_rootwidget), 0, (int*)NULL);
}
mainloop_abort_on_exception()
mainloop_abort_on_exception=(p1)
mainloop_thread?()
mainloop_watchdog(...)
num_of_mainwindows()
set_eventloop_tick(p1)
set_eventloop_weight(p1, p2)
set_max_block_time(p1)
set_no_event_wait(p1)


Module: TclTk

Module | TclTk
In: | tcltklib/lib/tcltk.rb

module TclTk: collection of tcl/tk utilities (supplies namespace.)

Methods

_addcallback _callcallback _newname dcb deletecallbackkey mainloop

Public Class methods

_addcallback(ca)

TclTk._addcallback(ca): register callback

  ca: callback(TclTkCallback)

[Source]

# File tcltklib/lib/tcltk.rb, line 52
def TclTk._addcallback(ca)
  print("_addcallback: ", ca.to_s(), "\n") if $DEBUG
  @callback[ca.to_s()] = ca
end
_callcallback(key, arg)

TclTk._callcallback(key, arg): invoke registered callback

  key: key to select callback (to_s value of the TclTkCallback)
  arg: parameter from tcl/tk interpreter

[Source]

# File tcltklib/lib/tcltk.rb, line 60
def TclTk._callcallback(key, arg)
  print("_callcallback: ", @callback[key].inspect, "\n") if $DEBUG
  @callback[key]._call(arg)
  # throw out callback value
  # should return String to satisfy rb_eval_string()
  return ""
end
_newname(prefix)

TclTk._newname(prefix): generate unique name(String)

  prefix: prefix of the unique name

[Source]

# File tcltklib/lib/tcltk.rb, line 70
def TclTk._newname(prefix)
  # generated name counter is stored in @namecnt
  if !@namecnt.key?(prefix)
    # first appearing prefix, initialize
    @namecnt[prefix] = 1
  else
    # already appeared prefix, generate next name
    @namecnt[prefix] += 1
  end
  return "#{prefix}#{@namecnt[prefix]}"
end
dcb(ca, wid, w)

TclTk.dcb(ca, wid, W): call TclTk.deletecallbackkey() for each callbacks

    in an array.
    this is for callback for top-level <Destroy>
  ca: array of callbacks(TclTkCallback)
  wid: top-level widget(TclTkWidget)
  w: information about window given by %W(String)

[Source]

# File tcltklib/lib/tcltk.rb, line 42
def TclTk.dcb(ca, wid, w)
  if wid.to_s() == w
    ca.each{|i|
      TclTk.deletecallbackkey(i)
    }
  end
end
deletecallbackkey(ca)

TclTk.deletecallbackkey(ca): remove callback from TclTk module

    this does not remove callbacks from tcl/tk interpreter
    without calling this method, TclTkInterpreter will not be GCed
  ca: callback(TclTkCallback)

[Source]

# File tcltklib/lib/tcltk.rb, line 31
def TclTk.deletecallbackkey(ca)
  print("deletecallbackkey: ", ca.to_s(), "\n") if $DEBUG
  @callback.delete(ca.to_s)
end
mainloop()

TclTk.mainloop(): call TclTkLib.mainloop()

[Source]

# File tcltklib/lib/tcltk.rb, line 21
def TclTk.mainloop()
  print("mainloop: start\n") if $DEBUG
  TclTkLib.mainloop()
  print("mainloop: end\n") if $DEBUG
end


Class: TclTkCallback

Class | TclTkCallback
In: | tcltklib/lib/tcltk.rb
Parent: | TclTkObject

class TclTkCallback: tcl/tk callbacks

Methods

_call new to_eval

Public Class methods

new(interp, pr, arg = nil)

initialize(interp, pr, arg):

  interp: interpreter(TclTkInterpreter)
  pr: callback procedure(Proc)
  arg: string to pass as block parameters of pr
      bind command of tcl/tk uses % replacement for parameters
      pr can receive replaced data using block parameter
      its format is specified by arg string
      You should not specify arg for the command like
      scrollbar with -command option, which receives parameters
      without specifying any replacement

[Source]

# File tcltklib/lib/tcltk.rb, line 316
  def initialize(interp, pr, arg = nil)
    # auto-generate tcl/tk representation (variable name)
    exp = TclTk._newname("c_")
    # initialize TclTkObject
    super(interp._tcltkip(), exp)
    # save parameters
    @pr = pr
    @arg = arg
    # register in the module
    TclTk._addcallback(self)
  end

Public Instance methods

_call(arg)

_call(arg): invoke callback

  arg: callback parameter

[Source]

# File tcltklib/lib/tcltk.rb, line 342
  def _call(arg)
    @pr.call(arg)
  end
to_eval()

to_eval(): retuens string representation for @ip._eval_args

[Source]

# File tcltklib/lib/tcltk.rb, line 329
  def to_eval()
    if @arg
      # bind replaces %s before calling ruby_fmt, so %%s is used
      s = %Q/{ruby_fmt {TclTk._callcallback("#{to_s()}", "%%s")} #{@arg}}/
    else
      s = %Q/{ruby_fmt {TclTk._callcallback("#{to_s()}", "%s")}}/
    end

    return s
  end


Class: TclTkCommand

Class | TclTkCommand
In: | tcltklib/lib/tcltk.rb
Parent: | TclTkObject

class TclTkCommand: tcl/tk commands you should not call TclTkCommand.new() commands are created by TclTkInterpreter:initialize()

Methods

e

Public Instance methods

e(*args)

e(*args): execute command. returns String (e is for exec or eval)

  *args: command arguments

[Source]

# File tcltklib/lib/tcltk.rb, line 206
  def e(*args)
    return @ip._eval_args(to_s(), *args)
  end


Class: TclTkImage

Class | TclTkImage
In: | tcltklib/lib/tcltk.rb
Parent: | TclTkCommand

class TclTkImage: tcl/tk images

Methods

new

Public Class methods

new(interp, t, *args)

initialize(interp, t, *args):

    generating image is done by TclTkImage.new()
    destrying is done by image delete (inconsistent, sigh)
  interp: interpreter(TclTkInterpreter)
  t: image type (photo, bitmap, etc.)
  *args: command argument

[Source]

# File tcltklib/lib/tcltk.rb, line 356
  def initialize(interp, t, *args)
    # auto-generate tcl/tk representation
    exp = TclTk._newname("i_")
    # initialize TclTkObject
    super(interp._tcltkip(), exp)
    # generate image
    res = @ip._eval_args("image create", t, exp, *args)
    fail("can't create Image") if res != exp
  end


Class: TclTkInterpreter

Class | TclTkInterpreter
In: | tcltklib/lib/tcltk.rb
Parent: | Object

class TclTkInterpreter: tcl/tk interpreter

Methods

_tcltkip commands method_missing new rootwidget

Public Class methods

new()

initialize():

[Source]

# File tcltklib/lib/tcltk.rb, line 88
  def initialize()
    # generate interpreter object
    @ip = TclTkIp.new()

    # add ruby_fmt command to tcl interpreter
    # ruby_fmt command format arguments by `format' and call `ruby' command
    # (notice ruby command receives only one argument)
    if $DEBUG
      @ip._eval("proc ruby_fmt {fmt args} { puts \"ruby_fmt: $fmt $args\" ; set cmd [list ruby [format $fmt $args]] ; uplevel $cmd }")
    else
      @ip._eval("proc ruby_fmt {fmt args} { set cmd [list ruby [format $fmt $args]] ; uplevel $cmd }")
    end

    # @ip._get_eval_string(*args): generate string to evaluate in tcl interpreter
    #   *args: script which is going to be evaluated under tcl/tk
    def @ip._get_eval_string(*args)
      argstr = ""
      args.each{|arg|
        argstr += " " if argstr != ""
        # call to_eval if it is defined
        if (arg.respond_to?(:to_eval))
          argstr += arg.to_eval()
        else
          # call to_s unless defined
          argstr += arg.to_s()
        end
      }
      return argstr
    end

    # @ip._eval_args(*args): evaluate string under tcl/tk interpreter
    #     returns result string.
    #   *args: script which is going to be evaluated under tcl/tk
    def @ip._eval_args(*args)
      # calculate the string to eval in the interpreter
      argstr = _get_eval_string(*args)

      # evaluate under the interpreter
      print("_eval: \"", argstr, "\"") if $DEBUG
      res = _eval(argstr)
      if $DEBUG
        print(" -> \"", res, "\"\n")
      elsif  _return_value() != 0
        print(res, "\n")
      end
      fail(%Q/can't eval "#{argstr}"/) if _return_value() != 0 #'
      return res
    end

    # generate tcl/tk command object and register in the hash
    @commands = {}
    # for all commands registered in tcl/tk interpreter:
    @ip._eval("info command").split(/ /).each{|comname|
      if comname =~ /^[.]/
        # if command is a widget (path), generate TclTkWidget,
        # and register it in the hash
        @commands[comname] = TclTkWidget.new(@ip, comname)
      else
        # otherwise, generate TclTkCommand
        @commands[comname] = TclTkCommand.new(@ip, comname)
      end
    }
  end

Public Instance methods

_tcltkip()

_tcltkip(): returns @ip(TclTkIp)

[Source]

# File tcltklib/lib/tcltk.rb, line 163
  def _tcltkip()
    return @ip
  end
commands()

commands(): returns hash of the tcl/tk commands

[Source]

# File tcltklib/lib/tcltk.rb, line 153
  def   commandscommandscommands()
    return @commands
  end
method_missing(id, *args)

method_missing(id, *args): execute undefined method as tcl/tk command

  id: method symbol
  *args: method arguments

[Source]

# File tcltklib/lib/tcltk.rb, line 170
  def method_missing(id, *args)
    # if command named by id registered, then execute it
    if @commands.key?(id.id2name)
      return @commands[id.id2name].e(*args)
    else
      # otherwise, exception
      super
    end
  end
rootwidget()

rootwidget(): returns root widget(TclTkWidget)

[Source]

# File tcltklib/lib/tcltk.rb, line 158
  def rootwidget()
    return @commands["."]
  end


Class: TclTkIp

Class | TclTkIp
In: | tcltklib/tcltklib.c
Parent: | Object

Methods

_conv_listelement _create_console _eval _fromUTF8 _get_global_var _get_global_var2 _get_variable _get_variable2 _invoke _merge_tklist _return_value _set_global_var _set_global_var2 _set_variable _set_variable2 _split_tklist _thread_tkwait _thread_vwait _toUTF8 _unset_global_var _unset_global_var2 _unset_variable _unset_variable2 allow_ruby_exit= allow_ruby_exit? create_slave delete deleted? do_one_event get_eventloop_tick get_eventloop_weight get_no_event_wait has_mainwindow? invalid_namespace? mainloop mainloop_abort_on_exception mainloop_abort_on_exception= mainloop_watchdog make_safe new restart safe? set_eventloop_tick set_eventloop_weight set_max_block_time set_no_event_wait

Public Class methods

new(...)

initialize interpreter

[Source]

/* initialize interpreter */
static VALUE
ip_init(argc, argv, self)
    int   argc;
    VALUE *argv;
    VALUE self;
{
    struct tcltkip *ptr;        /* tcltkip data struct */
    VALUE argv0, opts;
    int cnt;
    int st;
    int with_tk = 1;
    Tk_Window mainWin = (Tk_Window)NULL;

    /* security check */
    if (ruby_safe_level >= 4) {
        rb_raise(rb_eSecurityError,
                 "Cannot create a TclTkIp object at level %d",
                 ruby_safe_level);
    }

    /* create object */
    Data_Get_Struct(self, struct tcltkip, ptr);
    ptr = ALLOC(struct tcltkip);
    DATA_PTR(self) = ptr;
    ptr->ref_count = 0;
    ptr->allow_ruby_exit = 1;
    ptr->return_value = 0;

    /* from Tk_Main() */
    DUMP1("Tcl_CreateInterp");
    ptr->ip = ruby_tcl_create_ip_and_stubs_init(&st);
    if (ptr->ip == NULL) {
        switch(st) {
        case TCLTK_STUBS_OK:
            break;
        case NO_TCL_DLL:
            rb_raise(rb_eLoadError, "tcltklib: fail to open tcl_dll");
        case NO_FindExecutable:
            rb_raise(rb_eLoadError, "tcltklib: can't find Tcl_FindExecutable");
        case NO_CreateInterp:
            rb_raise(rb_eLoadError, "tcltklib: can't find Tcl_CreateInterp()");
        case NO_DeleteInterp:
            rb_raise(rb_eLoadError, "tcltklib: can't find Tcl_DeleteInterp()");
        case FAIL_CreateInterp:
            rb_raise(rb_eRuntimeError, "tcltklib: fail to create a new IP");
        case FAIL_Tcl_InitStubs:
            rb_raise(rb_eRuntimeError, "tcltklib: fail to Tcl_InitStubs()");
        default:
            rb_raise(rb_eRuntimeError, "tcltklib: unknown error(%d) on ruby_tcl_create_ip_and_stubs_init", st);
        }
    }

#if TCL_MAJOR_VERSION >= 8
#if TCL_NAMESPACE_DEBUG
    DUMP1("get current namespace");
    if ((ptr->default_ns = Tcl_GetCurrentNamespace(ptr->ip))
        == (Tcl_Namespace*)NULL) {
      rb_raise(rb_eRuntimeError, "a new Tk interpreter has a NULL namespace");
    }
#endif
#endif

    rbtk_preserve_ip(ptr);
    DUMP2("IP ref_count = %d", ptr->ref_count);
    current_interp = ptr->ip;

    ptr->has_orig_exit
        = Tcl_GetCommandInfo(ptr->ip, "exit", &(ptr->orig_exit_info));

    /* from Tcl_AppInit() */
    DUMP1("Tcl_Init");
    if (Tcl_Init(ptr->ip) == TCL_ERROR) {
        rb_raise(rb_eRuntimeError, "%s", Tcl_GetStringResult(ptr->ip));
    }

    /* set variables */
    cnt = rb_scan_args(argc, argv, "02", &argv0, &opts);
    switch(cnt) {
    case 2:
        /* options */
        if (NIL_P(opts) || opts == Qfalse) {
            /* without Tk */
            with_tk = 0;
        } else {
            /* Tcl_SetVar(ptr->ip, "argv", StringValuePtr(opts), 0); */
            Tcl_SetVar(ptr->ip, "argv", StringValuePtr(opts), TCL_GLOBAL_ONLY);
        }
    case 1:
        /* argv0 */
        if (!NIL_P(argv0)) {
            if (strncmp(StringValuePtr(argv0), "-e", 3) == 0
                || strncmp(StringValuePtr(argv0), "-", 2) == 0) {
                Tcl_SetVar(ptr->ip, "argv0", "ruby", TCL_GLOBAL_ONLY);
            } else {
                /* Tcl_SetVar(ptr->ip, "argv0", StringValuePtr(argv0), 0); */
                Tcl_SetVar(ptr->ip, "argv0", StringValuePtr(argv0),
                           TCL_GLOBAL_ONLY);
            }
        }
    case 0:
        /* no args */
        ;
    }

    /* from Tcl_AppInit() */
    if (with_tk) {
        DUMP1("Tk_Init");
        st = ruby_tk_stubs_init(ptr->ip);
        switch(st) {
        case TCLTK_STUBS_OK:
            break;
        case NO_Tk_Init:
            rb_raise(rb_eLoadError, "tcltklib: can't find Tk_Init()");
        case FAIL_Tk_Init:
            rb_raise(rb_eRuntimeError, "tcltklib: fail to Tk_Init(). %s",
                     Tcl_GetStringResult(ptr->ip));
        case FAIL_Tk_InitStubs:
            rb_raise(rb_eRuntimeError, "tcltklib: fail to Tk_InitStubs(). %s",
                     Tcl_GetStringResult(ptr->ip));
        default:
            rb_raise(rb_eRuntimeError, "tcltklib: unknown error(%d) on ruby_tk_stubs_init", st);
        }

        DUMP1("Tcl_StaticPackage(\"Tk\")");
#if TCL_MAJOR_VERSION >= 8
        Tcl_StaticPackage(ptr->ip, "Tk", Tk_Init, Tk_SafeInit);
#else /* TCL_MAJOR_VERSION < 8 */
        Tcl_StaticPackage(ptr->ip, "Tk", Tk_Init,
                          (Tcl_PackageInitProc *) NULL);
#endif

        /* get main window */
        mainWin = Tk_MainWindow(ptr->ip);
        Tk_Preserve((ClientData)mainWin);
    }

    /* add ruby command to the interpreter */
#if TCL_MAJOR_VERSION >= 8
    DUMP1("Tcl_CreateObjCommand(\"ruby\")");
    Tcl_CreateObjCommand(ptr->ip, "ruby", ip_ruby_eval, (ClientData)NULL,
                         (Tcl_CmdDeleteProc *)NULL);
    DUMP1("Tcl_CreateObjCommand(\"ruby_eval\")");
    Tcl_CreateObjCommand(ptr->ip, "ruby_eval", ip_ruby_eval, (ClientData)NULL,
                         (Tcl_CmdDeleteProc *)NULL);
    DUMP1("Tcl_CreateObjCommand(\"ruby_cmd\")");
    Tcl_CreateObjCommand(ptr->ip, "ruby_cmd", ip_ruby_cmd, (ClientData)NULL,
                         (Tcl_CmdDeleteProc *)NULL);
#else /* TCL_MAJOR_VERSION < 8 */
    DUMP1("Tcl_CreateCommand(\"ruby\")");
    Tcl_CreateCommand(ptr->ip, "ruby", ip_ruby_eval, (ClientData)NULL,
                      (Tcl_CmdDeleteProc *)NULL);
    DUMP1("Tcl_CreateCommand(\"ruby_eval\")");
    Tcl_CreateCommand(ptr->ip, "ruby_eval", ip_ruby_eval, (ClientData)NULL,
                      (Tcl_CmdDeleteProc *)NULL);
    DUMP1("Tcl_CreateCommand(\"ruby_cmd\")");
    Tcl_CreateCommand(ptr->ip, "ruby_cmd", ip_ruby_cmd, (ClientData)NULL,
                      (Tcl_CmdDeleteProc *)NULL);
#endif

    /* add 'interp_exit', 'ruby_exit' and replace 'exit' command */
#if TCL_MAJOR_VERSION >= 8
    DUMP1("Tcl_CreateObjCommand(\"interp_exit\")");
    Tcl_CreateObjCommand(ptr->ip, "interp_exit", ip_InterpExitObjCmd,
                         (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
    DUMP1("Tcl_CreateObjCommand(\"ruby_exit\")");
    Tcl_CreateObjCommand(ptr->ip, "ruby_exit", ip_RubyExitObjCmd,
                         (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
    DUMP1("Tcl_CreateObjCommand(\"exit\") --> \"ruby_exit\"");
    Tcl_CreateObjCommand(ptr->ip, "exit", ip_RubyExitObjCmd,
                         (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
#else /* TCL_MAJOR_VERSION < 8 */
    DUMP1("Tcl_CreateCommand(\"interp_exit\")");
    Tcl_CreateCommand(ptr->ip, "interp_exit", ip_InterpExitCommand,
                      (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
    DUMP1("Tcl_CreateCommand(\"ruby_exit\")");
    Tcl_CreateCommand(ptr->ip, "ruby_exit", ip_RubyExitCommand,
                      (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
    DUMP1("Tcl_CreateCommand(\"exit\") --> \"ruby_exit\"");
    Tcl_CreateCommand(ptr->ip, "exit", ip_RubyExitCommand,
                      (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
#endif

    /* replace vwait and tkwait */
    ip_replace_wait_commands(ptr->ip, mainWin);

    /* wrap namespace command */
    ip_wrap_namespace_command(ptr->ip);

    /* set finalizer */
    Tcl_CallWhenDeleted(ptr->ip, ip_CallWhenDeleted, (ClientData)mainWin);

    if (mainWin != (Tk_Window)NULL) {
        Tk_Release((ClientData)mainWin);
    }

    return self;
}

Public Instance methods

_conv_listelement(p1)
_create_console()
_eval(p1)
_fromUTF8(...)
_get_global_var(p1)
_get_global_var2(p1, p2)
_get_variable(p1, p2)
_get_variable2(p1, p2, p3)
_invoke(...)
_merge_tklist(...)
_return_value()

get return code from Tcl_Eval()

[Source]

/* get return code from Tcl_Eval() */
static VALUE
ip_retval(self)
    VALUE self;
{
    struct tcltkip *ptr;        /* tcltkip data struct */

    /* get the data strcut */
    ptr = get_ip(self);

    /* ip is deleted? */
    if (deleted_ip(ptr)) {
        return rb_tainted_str_new2("");
    }

    return (INT2FIX(ptr->return_value));
}
_set_global_var(p1, p2)
_set_global_var2(p1, p2, p3)
_set_variable(p1, p2, p3)
_set_variable2(p1, p2, p3, p4)
_split_tklist(p1)
_thread_tkwait(p1, p2)
_thread_vwait(p1)
_toUTF8(...)
_unset_global_var(p1)
_unset_global_var2(p1, p2)
_unset_variable(p1, p2)
_unset_variable2(p1, p2, p3)
allow_ruby_exit=(p1)

allow_ruby_exit = mode

[Source]

/* allow_ruby_exit = mode */
static VALUE
ip_allow_ruby_exit_set(self, val)
    VALUE self, val;
{
    struct tcltkip *ptr = get_ip(self);
    Tk_Window mainWin;

    rb_secure(4);

    /* ip is deleted? */
    if (deleted_ip(ptr)) {
        rb_raise(rb_eRuntimeError, "interpreter is deleted");
    }

    if (Tcl_IsSafe(ptr->ip)) {
        rb_raise(rb_eSecurityError,
                 "insecure operation on a safe interpreter");
    }

    mainWin = (tk_stubs_init_p())? Tk_MainWindow(ptr->ip): (Tk_Window)NULL;

    if (RTEST(val)) {
        ptr->allow_ruby_exit = 1;
#if TCL_MAJOR_VERSION >= 8
        DUMP1("Tcl_CreateObjCommand(\"exit\") --> \"ruby_exit\"");
        Tcl_CreateObjCommand(ptr->ip, "exit", ip_RubyExitObjCmd,
                             (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
#else /* TCL_MAJOR_VERSION < 8 */
        DUMP1("Tcl_CreateCommand(\"exit\") --> \"ruby_exit\"");
        Tcl_CreateCommand(ptr->ip, "exit", ip_RubyExitCommand,
                          (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
#endif
        return Qtrue;

    } else {
        ptr->allow_ruby_exit = 0;
#if TCL_MAJOR_VERSION >= 8
        DUMP1("Tcl_CreateObjCommand(\"exit\") --> \"interp_exit\"");
        Tcl_CreateObjCommand(ptr->ip, "exit", ip_InterpExitObjCmd,
                             (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
#else /* TCL_MAJOR_VERSION < 8 */
        DUMP1("Tcl_CreateCommand(\"exit\") --> \"interp_exit\"");
        Tcl_CreateCommand(ptr->ip, "exit", ip_InterpExitCommand,
                          (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
#endif
        return Qfalse;
    }
}
allow_ruby_exit?()

allow_ruby_exit?

[Source]

/* allow_ruby_exit? */
static VALUE
ip_allow_ruby_exit_p(self)
    VALUE self;
{
    struct tcltkip *ptr = get_ip(self);

    /* ip is deleted? */
    if (deleted_ip(ptr)) {
        rb_raise(rb_eRuntimeError, "interpreter is deleted");
    }

    if (ptr->allow_ruby_exit) {
        return Qtrue;
    } else {
        return Qfalse;
    }
}
create_slave(...)
delete()

delete interpreter

[Source]

/* delete interpreter */
static VALUE
ip_delete(self)
    VALUE self;
{
    int  thr_crit_bup;
    struct tcltkip *ptr = get_ip(self);
    Tcl_CmdInfo info;

    if (ptr == (struct tcltkip *)NULL || ptr->ip == (Tcl_Interp*)NULL) {
        DUMP1("delete deleted IP");
        return Qnil;
    }

    thr_crit_bup = rb_thread_critical;
    rb_thread_critical = Qtrue;

    DUMP1("call ip_finalize");
    ip_finalize(ptr->ip);

    DUMP1("delete interp");
    Tcl_DeleteInterp(ptr->ip);
    Tcl_Release(ptr->ip);

    ptr->ip = (Tcl_Interp*)NULL;

    rb_thread_critical = thr_crit_bup;

    return Qnil;
}
deleted?()
do_one_event(...)
get_eventloop_tick()
get_eventloop_weight()
get_no_event_wait()
has_mainwindow?()
invalid_namespace?()

is deleted?

[Source]

/* is deleted? */
static VALUE
ip_has_invalid_namespace_p(self)
    VALUE self;
{
    struct tcltkip *ptr = get_ip(self);

    if (ptr == (struct tcltkip *)NULL || ptr->ip == (Tcl_Interp *)NULL) {
        /* deleted IP */
        return Qtrue;
    }

#if TCL_NAMESPACE_DEBUG
    if (rbtk_invalid_namespace(ptr)) {
        return Qtrue;
    } else {
        return Qfalse;
    }
#else
    return Qfalse;
#endif
}
mainloop(...)
mainloop_abort_on_exception()
mainloop_abort_on_exception=(p1)
mainloop_watchdog(...)
make_safe()
restart()
safe?()

is safe?

[Source]

/* is safe? */
static VALUE
ip_is_safe_p(self)
    VALUE self;
{
    struct tcltkip *ptr = get_ip(self);

    /* ip is deleted? */
    if (deleted_ip(ptr)) {
        rb_raise(rb_eRuntimeError, "interpreter is deleted");
    }

    if (Tcl_IsSafe(ptr->ip)) {
        return Qtrue;
    } else {
        return Qfalse;
    }
}
set_eventloop_tick(p1)
set_eventloop_weight(p1, p2)
set_max_block_time(p1)
set_no_event_wait(p1)


Module: TclTkLib::EventFlag

Module | TclTkLib::EventFlag
In: | tcltklib/tcltklib.c


Module: TclTkLib::VarAccessFlag

Module | TclTkLib::VarAccessFlag
In: | tcltklib/tcltklib.c


Class: TclTkLibCommand

Class | TclTkLibCommand
In: | tcltklib/lib/tcltk.rb
Parent: | TclTkCommand

class TclTkLibCommand: tcl/tk commands in the library

Methods

new

Public Class methods

new(ip, name)

initialize(ip, name):

  ip: interpreter(TclTkInterpreter)
  name: command name (String)

[Source]

# File tcltklib/lib/tcltk.rb, line 217
  def initialize(ip, name)
    super(ip._tcltkip, name)
  end


Class: TclTkObject

Class | TclTkObject
In: | tcltklib/lib/tcltk.rb
Parent: | Object

class TclTkObject: base class of the tcl/tk objects

Methods

new to_s

Public Class methods

new(ip, exp)

initialize(ip, exp):

  ip: interpreter(TclTkIp)
  exp: tcl/tk representation

[Source]

# File tcltklib/lib/tcltk.rb, line 187
  def initialize(ip, exp)
    fail("type is not TclTkIp") if !ip.kind_of?(TclTkIp)
    @ip = ip
    @exp = exp
  end

Public Instance methods

to_s()

to_s(): returns tcl/tk representation

[Source]

# File tcltklib/lib/tcltk.rb, line 194
  def to_s()
    return @exp
  end


Class: TclTkVariable

Class | TclTkVariable
In: | tcltklib/lib/tcltk.rb
Parent: | TclTkObject

class TclTkVariable: tcl/tk variable

Methods

get new set

Public Class methods

new(interp, dat)

initialize(interp, dat):

  interp: interpreter(TclTkInterpreter)
  dat: the value to set(String)
      if nil, not initialize variable

[Source]

# File tcltklib/lib/tcltk.rb, line 229
  def initialize(interp, dat)
    # auto-generate tcl/tk representation (variable name)
    exp = TclTk._newname("v_")
    # initialize TclTkObject
    super(interp._tcltkip(), exp)
    # safe this for `set' command
    @set = interp.commands()["set"]
    # set value
    set(dat) if dat
  end

Public Instance methods

get()

get(): read tcl/tk variable(String) using `set’

[Source]

# File tcltklib/lib/tcltk.rb, line 250
  def get()
    return @set.e(to_s())
  end
set(data)

set(data): set tcl/tk variable using `set’

  data: new value

[Source]

# File tcltklib/lib/tcltk.rb, line 245
  def set(data)
    @set.e(to_s(), data.to_s())
  end


Class: TclTkWidget

Class | TclTkWidget
In: | tcltklib/lib/tcltk.rb
Parent: | TclTkCommand

class TclTkWidget: tcl/tk widget

Methods

new

Public Class methods

new(*args)

initialize(*args):

  *args: parameters

[Source]

# File tcltklib/lib/tcltk.rb, line 260
  def initialize(*args)
    if args[0].kind_of?(TclTkIp)
      # in case the 1st argument is TclTkIp:

      # Wrap tcl/tk widget by TclTkWidget
      # (used in TclTkInterpreter#initialize())

      # need two arguments
      fail("illegal # of parameter") if args.size != 2

      # ip: interpreter(TclTkIp)
      # exp: tcl/tk representation
      ip, exp = args

      # initialize TclTkObject
      super(ip, exp)
    elsif args[0].kind_of?(TclTkInterpreter)
      # in case 1st parameter is TclTkInterpreter:

      # generate new widget from parent widget

      # interp: interpreter(TclTkInterpreter)
      # parent: parent widget
      # command: widget generating tk command(label Åù)
      # *args: argument to the command
      interp, parent, command, *args = args

      # generate widget name
      exp = parent.to_s()
      exp += "." if exp !~ /[.]$/
      exp += TclTk._newname("w_")
      # initialize TclTkObject
      super(interp._tcltkip(), exp)
      # generate widget
      res = @ip._eval_args(command, exp, *args)
#      fail("can't create Widget") if res != exp
      # for tk_optionMenu, it is legal res != exp
    else
      fail("first parameter is not TclTkInterpreter")
    end
  end


Class: TkCallbackBreak

Class | TkCallbackBreak
In: | tcltklib/tcltklib.c
Parent: | StandardError


Class: TkCallbackContinue

Class | TkCallbackContinue
In: | tcltklib/tcltklib.c
Parent: | StandardError


Class: TkCallbackRedo

Class | TkCallbackRedo
In: | tcltklib/tcltklib.c
Parent: | TkLocalJumpError


Class: TkCallbackRetry

Class | TkCallbackRetry
In: | tcltklib/tcltklib.c
Parent: | TkLocalJumpError


Class: TkCallbackReturn

Class | TkCallbackReturn
In: | tcltklib/tcltklib.c
Parent: | StandardError


Class: TkCallbackThrow

Class | TkCallbackThrow
In: | tcltklib/tcltklib.c
Parent: | TkLocalJumpError


Class: TkLocalJumpError

Class | TkLocalJumpError
In: | tcltklib/tcltklib.c
Parent: | eLocalJumpError


File: tcltk.rb

tcltk.rb

Path: | tcltklib/lib/tcltk.rb
Last Update: | Mon Oct 11 14:51:05 AUS Eastern Standard Time 2004

tof

Required files

tcltklib


File: stubs.c

stubs.c

Path: | tcltklib/stubs.c
Last Update: | Thu Aug 04 19:41:31 AUS Eastern Standard Time 2005


File: tcltklib.c

tcltklib.c

Path: | tcltklib/tcltklib.c
Last Update: | Wed Sep 28 11:48:34 AUS Eastern Standard Time 2005


Class: Tempfile

Class | Tempfile
In: | 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)

[Source]

# File 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(*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.

[Source]

# File 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

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.

[Source]

# File tempfile.rb, line 93
  def close(unlink_now=false)
    if unlink_now
      close!
    else
      _close
    end
  end
close!()

Closes and unlinks the file.

[Source]

# File tempfile.rb, line 102
  def close!
    _close
    @clean_proc.call
    ObjectSpace.undefine_finalizer(self)
  end
delete()

Alias for unlink

length()

Alias for size

open()

Opens or reopens the file with mode "r+".

[Source]

# File tempfile.rb, line 75
  def open
    @tmpfile.close if @tmpfile
    @tmpfile = File.open(@tmpname, 'r+')
    @data[1] = @tmpfile
    __setobj__(@tmpfile)
  end
path()

Returns the full path name of the temporary file.

[Source]

# File tempfile.rb, line 126
  def path
    @tmpname
  end
size()

Returns the size of the temporary file. As a side effect, the IO buffer is flushed before determining the size.

[Source]

# File tempfile.rb, line 132
  def size
    if @tmpfile
      @tmpfile.flush
      @tmpfile.stat.size
    else
      0
    end
  end
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.

[Source]

# File 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


File: tempfile.rb

tempfile.rb

Path: | tempfile.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

tempfile - manipulates temporary files

$Id: tempfile.rb,v 1.19.2.4 2005/05/11 01:46:31 ocean Exp $

Required files

delegate tmpdir


Module: Test::Unit

Module | Test::Unit
In: | test/unit.rb test/unit/util/procwrapper.rb test/unit/util/observable.rb test/unit/util/backtracefilter.rb test/unit/ui/tk/testrunner.rb test/unit/ui/testrunnerutilities.rb test/unit/ui/testrunnermediator.rb test/unit/ui/gtk2/testrunner.rb test/unit/ui/gtk/testrunner.rb test/unit/ui/fox/testrunner.rb test/unit/ui/console/testrunner.rb test/unit/testsuite.rb test/unit/testresult.rb test/unit/testcase.rb test/unit/failure.rb test/unit/error.rb test/unit/collector.rb test/unit/collector/objectspace.rb test/unit/collector/dir.rb test/unit/autorunner.rb test/unit/assertions.rb test/unit/assertionfailederror.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 © 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 © 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)

[Source]

# File test/unit.rb, line 273
    def self.run=(flag)
      @run = flag
    end
run?()

[Source]

# File test/unit.rb, line 277
    def self.run?
      @run ||= false
    end


Module: Test

Module | Test
In: | test/unit.rb test/unit/util/procwrapper.rb test/unit/util/observable.rb test/unit/util/backtracefilter.rb test/unit/ui/tk/testrunner.rb test/unit/ui/testrunnerutilities.rb test/unit/ui/testrunnermediator.rb test/unit/ui/gtk2/testrunner.rb test/unit/ui/gtk/testrunner.rb test/unit/ui/fox/testrunner.rb test/unit/ui/console/testrunner.rb test/unit/testsuite.rb test/unit/testresult.rb test/unit/testcase.rb test/unit/failure.rb test/unit/error.rb test/unit/collector.rb test/unit/collector/objectspace.rb test/unit/collector/dir.rb test/unit/autorunner.rb test/unit/assertions.rb test/unit/assertionfailederror.rb
Author: | Nathaniel Talbott.
Copyright: | Copyright © 2000-2002 Nathaniel Talbott. All rights reserved.
License: | Ruby license.

Methods

keyword_display new options process_args run

Classes and Modules

Module Test::Unit

Attributes

collector | [W]
exclude | [RW]
filters | [RW]
output_level | [RW]
pattern | [RW]
runner | [W]
suite | [R]
to_run | [RW]

Public Class methods

new(standalone) {|self| ...}

[Source]

# File test/unit/autorunner.rb, line 75
      def initialize(standalone)
        Unit.run = true
        @standalone = standalone
        @runner = RUNNERS[:console]
        @collector = COLLECTORS[(standalone ? :dir : :objectspace)]
        @filters = []
        @to_run = []
        @output_level = UI::NORMAL
        yield(self) if(block_given?)
      end

Public Instance methods

keyword_display(array)

[Source]

# File test/unit/autorunner.rb, line 191
      def keyword_display(array)
        list = array.collect {|e, *| e.to_s}
        Array === array or list.sort!
        list.collect {|e| e.sub(/^(.)([A-Za-z]+)(?=\w*$)/, '\\1[\\2]')}.join(", ")
      end
options()

[Source]

# File test/unit/autorunner.rb, line 100
      def options
        @options ||= OptionParser.new do |o|
          o.banner = "Test::Unit automatic runner."
          o.banner << "\nUsage: #{$0} [options] [-- untouched arguments]"

          o.on
          o.on('-r', '--runner=RUNNER', RUNNERS,
               "Use the given RUNNER.",
               "(" + keyword_display(RUNNERS) + ")") do |r|
            @runner = r
          end

          if(@standalone)
            o.on('-a', '--add=TORUN', Array,
                 "Add TORUN to the list of things to run;",
                 "can be a file or a directory.") do |a|
              @to_run.concat(a)
            end

            @pattern = []
            o.on('-p', '--pattern=PATTERN', Regexp,
                 "Match files to collect against PATTERN.") do |e|
              @pattern << e
            end

            @exclude = []
            o.on('-x', '--exclude=PATTERN', Regexp,
                 "Ignore files to collect against PATTERN.") do |e|
              @exclude << e
            end
          end

          o.on('-n', '--name=NAME', String,
               "Runs tests matching NAME.",
               "(patterns may be used).") do |n|
            n = (%r{\A/(.*)/\Z} =~ n ? Regexp.new($1) : n)
            case n
            when Regexp
              @filters << proc{|t| n =~ t.method_name ? true : nil}
            else
              @filters << proc{|t| n == t.method_name ? true : nil}
            end
          end

          o.on('-t', '--testcase=TESTCASE', String,
               "Runs tests in TestCases matching TESTCASE.",
               "(patterns may be used).") do |n|
            n = (%r{\A/(.*)/\Z} =~ n ? Regexp.new($1) : n)
            case n
            when Regexp
              @filters << proc{|t| n =~ t.class.name ? true : nil}
            else
              @filters << proc{|t| n == t.class.name ? true : nil}
            end
          end

          o.on('-v', '--verbose=[LEVEL]', OUTPUT_LEVELS,
               "Set the output level (default is verbose).",
               "(" + keyword_display(OUTPUT_LEVELS) + ")") do |l|
            @output_level = l || UI::VERBOSE
          end

          o.on('--',
               "Stop processing options so that the",
               "remaining options will be passed to the",
               "test."){o.terminate}

          o.on('-h', '--help', 'Display this help.'){puts o; exit}

          o.on_tail
          o.on_tail('Deprecated options:')

          o.on_tail('--console', 'Console runner (use --runner).') do
            warn("Deprecated option (--console).")
            @runner = RUNNERS[:console]
          end

          o.on_tail('--gtk', 'GTK runner (use --runner).') do
            warn("Deprecated option (--gtk).")
            @runner = RUNNERS[:gtk]
          end

          o.on_tail('--fox', 'Fox runner (use --runner).') do
            warn("Deprecated option (--fox).")
            @runner = RUNNERS[:fox]
          end

          o.on_tail
        end
      end
process_args(args = ARGV)

[Source]

# File test/unit/autorunner.rb, line 86
      def process_args(args = ARGV)
        begin
          @to_run.concat options.parse!(args)
        rescue OptionParser::ParseError => e
          puts e
          puts options
          $! = nil
          abort
        else
          @filters << proc{false} unless(@filters.empty?)
        end
        not @to_run.empty?
      end
run()

[Source]

# File test/unit/autorunner.rb, line 197
      def run
        @suite = @collector[self]
        result = @runner[self] or return false
        result.run(@suite, @output_level).passed?
      end


Class: Test::Unit::AssertionFailedError

Class | Test::Unit::AssertionFailedError
In: | test/unit/assertionfailederror.rb
Parent: | StandardError

Thrown by Test::Unit::Assertions when an assertion fails.


Module: Test::Unit::Assertions

Module | Test::Unit::Assertions
In: | test/unit/assertions.rb

Contains all of the standard Test::Unit assertions. Mixed in to Test::Unit::TestCase. To mix it in and use its functionality, you simply need to rescue Test::Unit::AssertionFailedError, and you can additionally override add_assertion to be notified whenever an assertion is made.

Notes:

  • The message to each assertion, if given, will be propagated with the failure.
  • It’s easy to add your own assertions based on assert_block().

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=

Classes and Modules

Class Test::Unit::Assertions::AssertionMessage

Constants

UncaughtThrow = {NameError => /^uncaught throw \`(.+)\'$/, ThreadError => /^uncaught throw \`(.+)\' in thread /}

Public Class methods

use_pp=(value)

Select whether or not to use the prettyprinter. If this option is set to false before any assertions are made, the prettyprinter will not be required at all.

[Source]

# File test/unit/assertions.rb, line 380
      def self.use_pp=(value)
        AssertionMessage.use_pp = value
      end

Public Instance methods

assert(boolean, message=nil)

Passes if boolean is true.

[Source]

# File test/unit/assertions.rb, line 37
      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_block(message="assert_block failed.") {|| ...}

The assertion upon which all other assertions are based. Passes if the block yields true.

[Source]

# File test/unit/assertions.rb, line 27
      def assert_block(message="assert_block failed.") # :yields:
        _wrap_assertion do
          if (! yield)
            raise AssertionFailedError.new(message.to_s)
          end
        end
      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.

[Source]

# File test/unit/assertions.rb, line 49
      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_in_delta(expected_float, actual_float, delta, message="")

Passes if expected_float and actual_float are equal within delta tolerance.

[Source]

# File test/unit/assertions.rb, line 318
      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_instance_of(klass, object, message="")

Passes if object.class == klass.

[Source]

# File test/unit/assertions.rb, line 108
      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_kind_of(klass, object, message="")

Passes if object.kind_of?(klass).

[Source]

# File test/unit/assertions.rb, line 129
      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_match(pattern, string, message="")

Passes if string =~ pattern.

[Source]

# File test/unit/assertions.rb, line 158
      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_nil(object, message="")

Passes if object.nil?.

[Source]

# File test/unit/assertions.rb, line 123
      def assert_nil(object, message="")
        assert_equal(nil, object, message)
      end
assert_no_match(regexp, string, message="")

Passes if string !~ regularExpression.

[Source]

# File test/unit/assertions.rb, line 262
      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_not_equal(expected, actual, message="")

Passes if expected != actual.

[Source]

# File test/unit/assertions.rb, line 248
      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(object, message="")

Passes if !object.nil?.

[Source]

# File test/unit/assertions.rb, line 255
      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_not_same(expected, actual, message="")

Passes if !actual.equal?(expected).

[Source]

# File test/unit/assertions.rb, line 235
      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_nothing_raised(*args) {|| ...}

Passes if block does not raise an exception.

[Source]

# File test/unit/assertions.rb, line 205
      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
assert_nothing_thrown(message="", &proc)

Passes if block does not throw anything.

[Source]

# File test/unit/assertions.rb, line 299
      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_operator(object1, operator, object2, message="")

Compares the two objects based on the passed operator. Passes if object1.send(operator, object2) is true.

[Source]

# File test/unit/assertions.rb, line 189
      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_raise(*args) {|| ...}

Passes if block raises one of the given exceptions.

[Source]

# File test/unit/assertions.rb, line 75
      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(*args, &block)

Alias of assert_raise. Will be deprecated in 1.9, and removed in 2.0.

[Source]

# File test/unit/assertions.rb, line 102
      def assert_raises(*args, &block)
        assert_raise(*args, &block)
      end
assert_respond_to(object, method, message="")

Passes if object.respond_to?(method) is true.

[Source]

# File test/unit/assertions.rb, line 139
      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_same(expected, actual, message="")

Passes if actual.equal?(expected) (i.e. they are the same instance).

[Source]

# File test/unit/assertions.rb, line 174
      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_send(send_array, message="")

Passes if the method sent returns a true value.

[Source]

# File test/unit/assertions.rb, line 336
      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
assert_throws(expected_symbol, message="", &proc)

Passes if block throws symbol.

[Source]

# File test/unit/assertions.rb, line 275
      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
build_message(head, template=nil, *arguments)

[Source]

# File test/unit/assertions.rb, line 350
      def build_message(head, template=nil, *arguments)
        template &&= template.chomp
        return AssertionMessage.new(head, template, arguments)
      end
flunk(message="Flunked")

Always fails.

[Source]

# File test/unit/assertions.rb, line 229
      def flunk(message="Flunked")
        assert_block(build_message(message)){false}
      end


Class: Test::Unit::Assertions::AssertionMessage

Class | Test::Unit::Assertions::AssertionMessage
In: | test/unit/assertions.rb
Parent: | Object

Methods

add_period convert literal new template to_s

Included Modules

Util::BacktraceFilter

Classes and Modules

Class Test::Unit::Assertions::AssertionMessage::Literal
Class Test::Unit::Assertions::AssertionMessage::Template

Attributes

use_pp [RW]

Public Class methods

literal(value)

[Source]

# File test/unit/assertions.rb, line 420
        def self.literal(value)
          Literal.new(value)
        end
new(head, template_string, parameters)

[Source]

# File test/unit/assertions.rb, line 426
        def initialize(head, template_string, parameters)
          @head = head
          @template_string = template_string
          @parameters = parameters
        end

Public Instance methods

add_period(string)

[Source]

# File test/unit/assertions.rb, line 462
        def add_period(string)
          (string =~ /\.\Z/ ? string : string + '.')
        end
convert(object)

[Source]

# File test/unit/assertions.rb, line 432
        def convert(object)
          case object
            when Exception
              "Class: <\#{convert(object.class)}>\nMessage: <\#{convert(object.message)}>\n---Backtrace---\n\#{filter_backtrace(object.backtrace).join(\"\\n\")}\n---------------\n".chop
            else
              if(self.class.use_pp)
                begin
                  require 'pp'
                rescue LoadError
                  self.class.use_pp = false
                  return object.inspect
                end unless(defined?(PP))
                PP.pp(object, '').chomp
              else
                object.inspect
              end
          end
        end
template()

[Source]

# File test/unit/assertions.rb, line 458
        def template
          @template ||= Template.create(@template_string)
        end
to_s()

[Source]

# File test/unit/assertions.rb, line 466
        def to_s
          message_parts = []
          if (@head)
            head = @head.to_s
            unless(head.empty?)
              message_parts << add_period(head)
            end
          end
          tail = template.result(@parameters.collect{|e| convert(e)})
          message_parts << tail unless(tail.empty?)
          message_parts.join("\n")
        end


Class: Test::Unit::Assertions::AssertionMessage::Literal

Class | Test::Unit::Assertions::AssertionMessage::Literal
In: | test/unit/assertions.rb
Parent: | Object

Methods

inspect new

Public Class methods

new(value)

[Source]

# File test/unit/assertions.rb, line 391
          def initialize(value)
            @value = value
          end

Public Instance methods

inspect()

[Source]

# File test/unit/assertions.rb, line 395
          def inspect
            @value.to_s
          end


Class: Test::Unit::Assertions::AssertionMessage::Template

Class | Test::Unit::Assertions::AssertionMessage::Template
In: | test/unit/assertions.rb
Parent: | Object

Methods

create new result

Attributes

count [R]

Public Class methods

create(string)

[Source]

# File test/unit/assertions.rb, line 401
          def self.create(string)
            parts = (string ? string.scan(/(?=[^\\])\?|(?:\\\?|[^\?])+/m) : [])
            self.new(parts)
          end
new(parts)

[Source]

# File test/unit/assertions.rb, line 408
          def initialize(parts)
            @parts = parts
            @count = parts.find_all{|e| e == '?'}.size
          end

Public Instance methods

result(parameters)

[Source]

# File test/unit/assertions.rb, line 413
          def result(parameters)
            raise "The number of parameters does not match the number of substitutions." if(parameters.size != count)
            params = parameters.dup
            @parts.collect{|e| e == '?' ? params.shift : e.gsub(/\\\?/m, '?')}.join('')
          end


Class: Test::Unit::AutoRunner

Class | Test::Unit::AutoRunner
In: | 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)

[Source]

# File test/unit/autorunner.rb, line 8
      def self.run(force_standalone=false, default_dir=nil, argv=ARGV, &block)
        r = new(force_standalone || standalone?, &block)
        if((!r.process_args(argv)) && default_dir)
          r.to_run << default_dir
        end
        r.run
      end
standalone?()

[Source]

# File test/unit/autorunner.rb, line 16
      def self.standalone?
        return false unless("-e" == $0)
        ObjectSpace.each_object(Class) do |klass|
          return false if(klass < TestCase)
        end
        true
      end


Module: Test::Unit::Collector

Module | Test::Unit::Collector
In: | test/unit/collector.rb test/unit/collector/objectspace.rb test/unit/collector/dir.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()

[Source]

# File test/unit/collector.rb, line 4
      def initialize
        @filters = []
      end

Public Instance methods

add_suite(destination, suite)

[Source]

# File 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
filter=(filters)

[Source]

# File test/unit/collector.rb, line 8
      def filter=(filters)
        @filters = case(filters)
          when Proc
            [filters]
          when Array
            filters
        end
      end
include?(test)

[Source]

# File 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(suites)

[Source]

# File test/unit/collector.rb, line 38
      def sort(suites)
        suites.sort_by{|s| s.name}
      end


Class: Test::Unit::Collector::Dir

Class | Test::Unit::Collector::Dir
In: | test/unit/collector/dir.rb
Parent: | Object

Methods

collect collect_file find_test_cases new recursive_collect

Included Modules

Collector

Attributes

exclude | [R]
pattern | [R]

Public Class methods

new(dir=::Dir, file=::File, object_space=::ObjectSpace, req=nil)

[Source]

# File test/unit/collector/dir.rb, line 12
        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

Public Instance methods

collect(*from)

[Source]

# File test/unit/collector/dir.rb, line 22
        def collect(*from)
          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
        end
collect_file(name, suites, already_gathered)

[Source]

# File test/unit/collector/dir.rb, line 77
        def collect_file(name, suites, already_gathered)
          dir = File.dirname(File.expand_path(name))
          $:.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
find_test_cases(ignore=[])

[Source]

# File test/unit/collector/dir.rb, line 39
        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(name, already_gathered)

[Source]

# File test/unit/collector/dir.rb, line 48
        def recursive_collect(name, already_gathered)
          sub_suites = []
          if(@file.directory?(name))
            @dir.entries(name).each do |e|
              next if(e == '.' || e == '..')
              e_name = @file.join(name, e)
              if(@file.directory?(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


Class: Test::Unit::Collector::ObjectSpace

Class | Test::Unit::Collector::ObjectSpace
In: | 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)

[Source]

# File test/unit/collector/objectspace.rb, line 15
        def initialize(source=::ObjectSpace)
          super()
          @source = source
        end

Public Instance methods

collect(name=NAME)

[Source]

# File 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


Class: Test::Unit::Error

Class | Test::Unit::Error
In: | 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.

[Source]

# File test/unit/error.rb, line 22
      def initialize(test_name, exception)
        @test_name = test_name
        @exception = exception
      end

Public Instance methods

long_display()

Returns a verbose version of the error description.

[Source]

# File test/unit/error.rb, line 43
      def long_display
        backtrace = filter_backtrace(@exception.backtrace).join("\n    ")
        "Error:\n#@test_name:\n#{message}\n    #{backtrace}"
      end
message()

Returns the message associated with the error.

[Source]

# File test/unit/error.rb, line 33
      def message
        "#{@exception.class.name}: #{@exception.message}"
      end
short_display()

Returns a brief version of the error description.

[Source]

# File test/unit/error.rb, line 38
      def short_display
        "#@test_name: #{message.split("\n")[0]}"
      end
single_character_display()

Returns a single character representation of an error.

[Source]

# File test/unit/error.rb, line 28
      def single_character_display
        SINGLE_CHARACTER
      end
to_s()

Overridden to return long_display.

[Source]

# File test/unit/error.rb, line 49
      def to_s
        long_display
      end


Class: Test::Unit::Failure

Class | Test::Unit::Failure
In: | 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.

[Source]

# File test/unit/failure.rb, line 17
      def initialize(test_name, location, message)
        @test_name = test_name
        @location = location
        @message = message
      end

Public Instance methods

long_display()

Returns a verbose version of the error description.

[Source]

# File test/unit/failure.rb, line 34
      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
short_display()

Returns a brief version of the error description.

[Source]

# File test/unit/failure.rb, line 29
      def short_display
        "#@test_name: #{@message.split("\n")[0]}"
      end
single_character_display()

Returns a single character representation of a failure.

[Source]

# File test/unit/failure.rb, line 24
      def single_character_display
        SINGLE_CHARACTER
      end
to_s()

Overridden to return long_display.

[Source]

# File test/unit/failure.rb, line 44
      def to_s
        long_display
      end


Class: Test::Unit::TestCase

Class | Test::Unit::TestCase
In: | 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"

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.

[Source]

# File test/unit/testcase.rb, line 31
      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()

Rolls up all of the test* methods in the fixture into one suite, creating a new instance of the fixture for each method.

[Source]

# File test/unit/testcase.rb, line 44
      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

Public Instance methods

==(other)

It’s handy to be able to compare TestCase instances.

[Source]

# File test/unit/testcase.rb, line 143
      def ==(other)
        return false unless(other.kind_of?(self.class))
        return false unless(@method_name == other.method_name)
        self.class == other.class
      end
default_test()

[Source]

# File test/unit/testcase.rb, line 98
      def default_test
        flunk("No tests were specified")
      end
name()

Returns a human-readable name for the specific test that this instance of TestCase represents.

[Source]

# File test/unit/testcase.rb, line 133
      def name
        "#{@method_name}(#{self.class.name})"
      end
run(result) {|STARTED, name| ...}

Runs the individual test method represented by this instance of the fixture, collecting statistics, failures and errors in result.

[Source]

# File test/unit/testcase.rb, line 65
      def run(result)
        yield(STARTED, name)
        @_result = result
        begin
          setup
          __send__(@method_name)
        rescue AssertionFailedError => e
          add_failure(e.message, e.backtrace)
        rescue StandardError, ScriptError
          add_error($!)
        ensure
          begin
            teardown
          rescue AssertionFailedError => e
            add_failure(e.message, e.backtrace)
          rescue StandardError, ScriptError
            add_error($!)
          end
        end
        result.add_run
        yield(FINISHED, name)
      end
setup()

Called before every test method runs. Can be used to set up fixture information.

[Source]

# File test/unit/testcase.rb, line 90
      def setup
      end
size()

[Source]

# File test/unit/testcase.rb, line 110
      def size
        1
      end
teardown()

Called after every test method runs. Can be used to tear down fixture information.

[Source]

# File test/unit/testcase.rb, line 95
      def teardown
      end
to_s()

Overridden to return name.

[Source]

# File test/unit/testcase.rb, line 138
      def to_s
        name
      end


Class: Test::Unit::TestResult

Class | Test::Unit::TestResult
In: | 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.

[Source]

# File test/unit/testresult.rb, line 23
      def initialize
        @run_count, @assertion_count = 0, 0
        @failures, @errors = Array.new, Array.new
      end

Public Instance methods

add_assertion()

Records an individual assertion.

[Source]

# File test/unit/testresult.rb, line 49
      def add_assertion
        @assertion_count += 1
        notify_listeners(CHANGED, self)
      end
add_error(error)

Records a Test::Unit::Error.

[Source]

# File test/unit/testresult.rb, line 42
      def add_error(error)
        @errors << error
        notify_listeners(FAULT, error)
        notify_listeners(CHANGED, self)
      end
add_failure(failure)

Records a Test::Unit::Failure.

[Source]

# File test/unit/testresult.rb, line 35
      def add_failure(failure)
        @failures << failure
        notify_listeners(FAULT, failure)
        notify_listeners(CHANGED, self)
      end
add_run()

Records a test run.

[Source]

# File test/unit/testresult.rb, line 29
      def add_run
        @run_count += 1
        notify_listeners(CHANGED, self)
      end
error_count()

Returns the number of errors this TestResult has recorded.

[Source]

# File test/unit/testresult.rb, line 74
      def error_count
        return @errors.size
      end
failure_count()

Returns the number of failures this TestResult has recorded.

[Source]

# File test/unit/testresult.rb, line 68
      def failure_count
        return @failures.size
      end
passed?()

Returns whether or not this TestResult represents successful completion.

[Source]

# File test/unit/testresult.rb, line 62
      def passed?
        return @failures.empty? && @errors.empty?
      end
to_s()

Returns a string contain the recorded runs, assertions, failures and errors in this TestResult.

[Source]

# File test/unit/testresult.rb, line 56
      def to_s
        "#{run_count} tests, #{assertion_count} assertions, #{failure_count} failures, #{error_count} errors"
      end


Class: Test::Unit::TestSuite

Class | Test::Unit::TestSuite
In: | 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.

[Source]

# File test/unit/testsuite.rb, line 22
      def initialize(name="Unnamed TestSuite")
        @name = name
        @tests = []
      end

Public Instance methods

<<(test)

Adds the test to the suite.

[Source]

# File test/unit/testsuite.rb, line 38
      def <<(test)
        @tests << test
        self
      end
==(other)

It’s handy to be able to compare TestSuite instances.

[Source]

# File test/unit/testsuite.rb, line 67
      def ==(other)
        return false unless(other.kind_of?(self.class))
        return false unless(@name == other.name)
        @tests == other.tests
      end
delete(test)

[Source]

# File test/unit/testsuite.rb, line 43
      def delete(test)
        @tests.delete(test)
      end
empty?()

[Source]

# File test/unit/testsuite.rb, line 56
      def empty?
        tests.empty?
      end
run(result) {|STARTED, name| ...}

Runs the tests and/or suites contained in this TestSuite.

[Source]

# File test/unit/testsuite.rb, line 29
      def run(result, &progress_block)
        yield(STARTED, name)
        @tests.each do |test|
          test.run(result, &progress_block)
        end
        yield(FINISHED, name)
      end
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.

[Source]

# File test/unit/testsuite.rb, line 50
      def size
        total_size = 0
        @tests.each { |test| total_size += test.size }
        total_size
      end
to_s()

Overridden to return the name given the suite at creation.

[Source]

# File test/unit/testsuite.rb, line 62
      def to_s
        @name
      end


Module: Test::Unit::UI

Module | Test::Unit::UI
In: | test/unit/ui/tk/testrunner.rb test/unit/ui/testrunnerutilities.rb test/unit/ui/testrunnermediator.rb test/unit/ui/gtk2/testrunner.rb test/unit/ui/gtk/testrunner.rb test/unit/ui/fox/testrunner.rb test/unit/ui/console/testrunner.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: | 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: | 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.

[Source]

# File test/unit/ui/console/testrunner.rb, line 23
          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

Public Instance methods

start()

Begins the test run.

[Source]

# File test/unit/ui/console/testrunner.rb, line 36
          def start
            setup_mediator
            attach_to_mediator
            return start_mediator
          end


Module: Test::Unit::UI::Fox

Module | Test::Unit::UI::Fox
In: | 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: | test/unit/ui/fox/testrunner.rb
Parent: | FXListItem

Methods

new

Attributes

fault [R]

Public Class methods

new(fault)

[Source]

# File test/unit/ui/fox/testrunner.rb, line 254
          def initialize(fault)
            super(fault.short_display)
            @fault = fault
          end


Class: Test::Unit::UI::Fox::TestRunner

Class | Test::Unit::UI::Fox::TestRunner
In: | 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.

[Source]

# File test/unit/ui/fox/testrunner.rb, line 30
          def initialize(suite, output_level = NORMAL)
            if (suite.respond_to?(:suite))
              @suite = suite.suite
            else
              @suite = suite
            end

            @result = nil
            @red = false
          end

Public Instance methods

add_fault(fault)

[Source]

# File test/unit/ui/fox/testrunner.rb, line 95
          def add_fault(fault)
            if ( ! @red )
              @test_progress_bar.barColor = RED_STYLE
              @red = true
            end
            item = FaultListItem.new(fault)
            @fault_list.appendItem(item)
          end
attach_to_mediator()

[Source]

# File test/unit/ui/fox/testrunner.rb, line 59
          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
clear_fault()

[Source]

# File test/unit/ui/fox/testrunner.rb, line 112
          def clear_fault
            raw_show_fault("")
          end
create_application()

[Source]

# File test/unit/ui/fox/testrunner.rb, line 181
          def create_application
            app = FXApp.new("TestRunner", "Test::Unit")
            app.init([])
            app
          end
create_button(parent, text, action)

[Source]

# File test/unit/ui/fox/testrunner.rb, line 205
          def create_button(parent, text, action)
            FXButton.new(parent, text).connect(SEL_COMMAND, &action)
          end
create_detail_panel(parent)

[Source]

# File test/unit/ui/fox/testrunner.rb, line 237
          def create_detail_panel(parent)
            FXHorizontalFrame.new(parent, LAYOUT_FILL_X | LAYOUT_FILL_Y | FRAME_SUNKEN | FRAME_THICK)
          end
create_entry(parent)

[Source]

# File test/unit/ui/fox/testrunner.rb, line 245
          def create_entry(parent)
            entry = FXTextField.new(parent, 30, nil, 0, TEXTFIELD_NORMAL | LAYOUT_SIDE_BOTTOM | LAYOUT_FILL_X)
            entry.disable
            entry
          end
create_fault_list(parent)

[Source]

# File test/unit/ui/fox/testrunner.rb, line 225
          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_info_panel(parent)

[Source]

# File test/unit/ui/fox/testrunner.rb, line 213
          def create_info_panel(parent)
            FXMatrix.new(parent, 1, MATRIX_BY_ROWS | LAYOUT_FILL_X)
          end
create_label(parent, text)

[Source]

# File test/unit/ui/fox/testrunner.rb, line 217
          def create_label(parent, text)
            FXLabel.new(parent, text, nil, JUSTIFY_CENTER_X | LAYOUT_FILL_COLUMN)
          end
create_list_panel(parent)

[Source]

# File test/unit/ui/fox/testrunner.rb, line 221
          def create_list_panel(parent)
            FXHorizontalFrame.new(parent, LAYOUT_FILL_X | FRAME_SUNKEN | FRAME_THICK)
          end
create_main_panel(parent)

[Source]

# File test/unit/ui/fox/testrunner.rb, line 195
          def create_main_panel(parent)
            panel = FXVerticalFrame.new(parent, LAYOUT_FILL_X | LAYOUT_FILL_Y)
            panel.vSpacing = 10
            panel
          end
create_progress_bar(parent)

[Source]

# File test/unit/ui/fox/testrunner.rb, line 209
          def create_progress_bar(parent)
            FXProgressBar.new(parent, nil, 0, PROGRESSBAR_NORMAL | LAYOUT_FILL_X)
          end
create_suite_panel(parent)

[Source]

# File test/unit/ui/fox/testrunner.rb, line 201
          def create_suite_panel(parent)
            FXHorizontalFrame.new(parent, LAYOUT_SIDE_LEFT | LAYOUT_FILL_X)
          end
create_text(parent)

[Source]

# File test/unit/ui/fox/testrunner.rb, line 241
          def create_text(parent)
            FXText.new(parent, nil, 0, TEXT_READONLY | LAYOUT_FILL_X | LAYOUT_FILL_Y)
          end
create_tooltip(app)

[Source]

# File test/unit/ui/fox/testrunner.rb, line 191
          def create_tooltip(app)
            FXTooltip.new(app)
          end
create_window(app)

[Source]

# File test/unit/ui/fox/testrunner.rb, line 187
          def create_window(app)
            FXMainWindow.new(app, "Test::Unit TestRunner", nil, nil, DECOR_ALL, 0, 0, 450)
          end
finished(elapsed_time)

[Source]

# File test/unit/ui/fox/testrunner.rb, line 138
          def finished(elapsed_time)
            output_status("Finished in #{elapsed_time} seconds")
          end
output_status(string)

[Source]

# File test/unit/ui/fox/testrunner.rb, line 142
          def output_status(string)
            @status_entry.text = string
            @status_entry.repaint
          end
raw_show_fault(string)

[Source]

# File test/unit/ui/fox/testrunner.rb, line 108
          def raw_show_fault(string)
            @detail_text.setText(string)
          end
reset_ui(count)

[Source]

# File test/unit/ui/fox/testrunner.rb, line 81
          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
result_changed(result)

[Source]

# File test/unit/ui/fox/testrunner.rb, line 116
          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
setup_mediator()

[Source]

# File test/unit/ui/fox/testrunner.rb, line 50
          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
setup_ui()

[Source]

# File test/unit/ui/fox/testrunner.rb, line 147
          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
show_fault(fault)

[Source]

# File test/unit/ui/fox/testrunner.rb, line 104
          def show_fault(fault)
            raw_show_fault(fault.long_display)
          end
start()

Begins the test run.

[Source]

# File test/unit/ui/fox/testrunner.rb, line 42
          def start
            setup_ui
            setup_mediator
            attach_to_mediator
            start_ui
            @result
          end
start_ui()

[Source]

# File test/unit/ui/fox/testrunner.rb, line 68
          def start_ui
            @application.create
            @window.show(PLACEMENT_SCREEN)
            @application.addTimeout(1) do
              @mediator.run_suite
            end
            @application.run
          end
started(result)

[Source]

# File test/unit/ui/fox/testrunner.rb, line 129
          def started(result)
            @result = result
            output_status("Started...")
          end
stop()

[Source]

# File test/unit/ui/fox/testrunner.rb, line 77
          def stop
            @application.exit(0)
          end
test_started(test_name)

[Source]

# File test/unit/ui/fox/testrunner.rb, line 134
          def test_started(test_name)
            output_status("Running #{test_name}...")
          end


Module: Test::Unit::UI::GTK

Module | Test::Unit::UI::GTK
In: | 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: | test/unit/ui/gtk/testrunner.rb
Parent: | Gtk::Label

Methods

set_text

Public Instance methods

set_text(text)

[Source]

# File test/unit/ui/gtk/testrunner.rb, line 395
          def set_text(text)
            super(text.gsub(/\n\t/, "\n" + (" " * 4)))
          end


Class: Test::Unit::UI::GTK::EnhancedProgressBar

Class | Test::Unit::UI::GTK::EnhancedProgressBar
In: | test/unit/ui/gtk/testrunner.rb
Parent: | Gtk::ProgressBar

Methods

set_style

Public Instance methods

set_style(style)

[Source]

# File test/unit/ui/gtk/testrunner.rb, line 387
          def set_style(style)
            super
            hide
            show
          end


Class: Test::Unit::UI::GTK::FaultListItem

Class | Test::Unit::UI::GTK::FaultListItem
In: | test/unit/ui/gtk/testrunner.rb
Parent: | Gtk::ListItem

Methods

new

Attributes

fault [R]

Public Class methods

new(fault)

[Source]

# File test/unit/ui/gtk/testrunner.rb, line 402
          def initialize(fault)
            super(fault.short_display)
            @fault = fault
          end


Class: Test::Unit::UI::GTK::TestRunner

Class | Test::Unit::UI::GTK::TestRunner
In: | 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.

[Source]

# File test/unit/ui/gtk/testrunner.rb, line 23
          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

Public Instance methods

start()

Begins the test run.

[Source]

# File test/unit/ui/gtk/testrunner.rb, line 41
          def start
            setup_mediator
            setup_ui
            attach_to_mediator
            start_ui
            @result
          end


Module: Test::Unit::UI::GTK2

Module | Test::Unit::UI::GTK2
In: | 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: | test/unit/ui/gtk2/testrunner.rb
Parent: | Gtk::Label

Methods

set_text

Public Instance methods

set_text(text)

[Source]

# File test/unit/ui/gtk2/testrunner.rb, line 17
          def set_text(text)
            super(text.gsub(/\n\t/, "\n    "))
          end


Class: Test::Unit::UI::GTK2::FaultList

Class | Test::Unit::UI::GTK2::FaultList
In: | test/unit/ui/gtk2/testrunner.rb
Parent: | Gtk::TreeView

Methods

add_fault clear get_fault new

Public Class methods

new()

[Source]

# File test/unit/ui/gtk2/testrunner.rb, line 23
          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

Public Instance methods

add_fault(fault)

[Source]

# File test/unit/ui/gtk2/testrunner.rb, line 38
          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
clear()

[Source]

# File test/unit/ui/gtk2/testrunner.rb, line 49
          def clear
            model.clear
          end
get_fault(iter)

[Source]

# File test/unit/ui/gtk2/testrunner.rb, line 45
          def get_fault(iter)
            @faults[iter.get_value(0).to_i]
          end


Class: Test::Unit::UI::GTK2::TestRunner

Class | Test::Unit::UI::GTK2::TestRunner
In: | 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)

[Source]

# File test/unit/ui/gtk2/testrunner.rb, line 441
          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

Public Instance methods

progress_panel()

[Source]

# File test/unit/ui/gtk2/testrunner.rb, line 235
          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()

[Source]

# File test/unit/ui/gtk2/testrunner.rb, line 243
          def run_button
            lazy_initialize(:run_button) do
              @run_button = Gtk::Button.new("Run")
            end
          end
start()

[Source]

# File test/unit/ui/gtk2/testrunner.rb, line 433
          def start
            setup_mediator
            setup_ui
            attach_to_mediator
            start_ui
            @result
          end
test_finished(result)

[Source]

# File test/unit/ui/gtk2/testrunner.rb, line 328
          def test_finished(result)
            test_progress_bar.fraction += 1.0 / @count
          end


Class: Test::Unit::UI::TestRunnerMediator

Class | Test::Unit::UI::TestRunnerMediator
In: | 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.

[Source]

# File test/unit/ui/testrunnermediator.rb, line 24
        def initialize(suite)
          @suite = suite
        end

Public Instance methods

run_suite()

Runs the suite the TestRunnerMediator was created with.

[Source]

# File test/unit/ui/testrunnermediator.rb, line 30
        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


Module: Test::Unit::UI::TestRunnerUtilities

Module | Test::Unit::UI::TestRunnerUtilities
In: | 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.

[Source]

# File test/unit/ui/testrunnerutilities.rb, line 26
        def run(suite, output_level=NORMAL)
          return new(suite, output_level).start
        end
start_command_line_test()

Takes care of the ARGV parsing and suite determination necessary for running one of the TestRunners from the command line.

[Source]

# File test/unit/ui/testrunnerutilities.rb, line 33
        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


Module: Test::Unit::UI::Tk

Module | Test::Unit::UI::Tk
In: | 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: | 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.

[Source]

# File test/unit/ui/tk/testrunner.rb, line 24
          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

Public Instance methods

start()

Begins the test run.

[Source]

# File test/unit/ui/tk/testrunner.rb, line 44
          def start
            setup_ui
            setup_mediator
            attach_to_mediator
            start_ui
            @result
          end


Module: Test::Unit::Util

Module | Test::Unit::Util
In: | test/unit/util/procwrapper.rb test/unit/util/observable.rb test/unit/util/backtracefilter.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: | 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)

[Source]

# File 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


Module: Test::Unit::Util::Observable

Module | Test::Unit::Util::Observable
In: | 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)

[Source]

# File test/unit/util/observable.rb, line 29
        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
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.

[Source]

# File test/unit/util/observable.rb, line 72
        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
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.

[Source]

# File test/unit/util/observable.rb, line 49
        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


Class: Test::Unit::Util::ProcWrapper

Class | Test::Unit::Util::ProcWrapper
In: | 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.

[Source]

# File test/unit/util/procwrapper.rb, line 21
        def initialize(a_proc)
          @a_proc = a_proc
          @hash = a_proc.inspect.sub(/^(#<#{a_proc.class}:)/){''}.sub(/(>)$/){''}.hex
        end

Public Instance methods

==(other)

[Source]

# File test/unit/util/procwrapper.rb, line 30
        def ==(other)
          case(other)
            when ProcWrapper
              return @a_proc == other.to_proc
            else
              return super
          end
        end
eql?(other)

Alias for #==

hash()

[Source]

# File test/unit/util/procwrapper.rb, line 26
        def hash
          return @hash
        end
to_proc()

[Source]

# File test/unit/util/procwrapper.rb, line 40
        def to_proc
          return @a_proc
        end


File: unit.rb

unit.rb

Path: | test/unit.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

test/unit.rb

Ruby’s standard unit testing library/software.

Copyright © 2000-2003, Nathaniel Talbott.

See Test::Unit for documentation.

Required files

test/unit/testcase test/unit/autorunner


File: assertionfailederror.rb

assertionfailederror.rb

Path: | test/unit/assertionfailederror.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005
Author: | Nathaniel Talbott.
Copyright: | Copyright © 2000-2002 Nathaniel Talbott. All rights reserved.
License: | Ruby license.


File: assertions.rb

assertions.rb

Path: | test/unit/assertions.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005
Author: | Nathaniel Talbott.
Copyright: | Copyright © 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: | test/unit/autorunner.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

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: | test/unit/collector.rb
Last Update: | Wed Oct 08 23:21:28 AUS Eastern Standard Time 2003


File: dir.rb

dir.rb

Path: | test/unit/collector/dir.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

Required files

test/unit/testsuite test/unit/collector


File: objectspace.rb

objectspace.rb

Path: | test/unit/collector/objectspace.rb
Last Update: | Wed Oct 08 23:21:28 AUS Eastern Standard Time 2003
Author: | Nathaniel Talbott.
Copyright: | Copyright © 2000-2003 Nathaniel Talbott. All rights reserved.
License: | Ruby license.

Required files

test/unit/collector


File: error.rb

error.rb

Path: | test/unit/error.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005
Author: | Nathaniel Talbott.
Copyright: | Copyright © 2000-2002 Nathaniel Talbott. All rights reserved.
License: | Ruby license.

Required files

test/unit/util/backtracefilter


File: failure.rb

failure.rb

Path: | test/unit/failure.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005
Author: | Nathaniel Talbott.
Copyright: | Copyright © 2000-2002 Nathaniel Talbott. All rights reserved.
License: | Ruby license.


File: testcase.rb

testcase.rb

Path: | test/unit/testcase.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005
Author: | Nathaniel Talbott.
Copyright: | Copyright © 2000-2003 Nathaniel Talbott. All rights reserved.
License: | Ruby license.

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: | test/unit/testresult.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005
Author: | Nathaniel Talbott.
Copyright: | Copyright © 2000-2002 Nathaniel Talbott. All rights reserved.
License: | Ruby license.

Required files

test/unit/util/observable


File: testsuite.rb

testsuite.rb

Path: | test/unit/testsuite.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005
Author: | Nathaniel Talbott.
Copyright: | Copyright © 2000-2003 Nathaniel Talbott. All rights reserved.
License: | Ruby license.


File: testrunner.rb

testrunner.rb

Path: | test/unit/ui/console/testrunner.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005
Author: | Nathaniel Talbott.
Copyright: | Copyright © 2000-2003 Nathaniel Talbott. All rights reserved.
License: | Ruby license.

Required files

test/unit/ui/testrunnermediator test/unit/ui/testrunnerutilities


File: testrunner.rb

testrunner.rb

Path: | test/unit/ui/fox/testrunner.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005
Author: | Nathaniel Talbott.
Copyright: | Copyright © 2000-2002 Nathaniel Talbott. All rights reserved.
License: | Ruby license.

Required files

fox test/unit/ui/testrunnermediator test/unit/ui/testrunnerutilities

Included Modules

Fox


File: testrunner.rb

testrunner.rb

Path: | test/unit/ui/gtk/testrunner.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005
Author: | Nathaniel Talbott.
Copyright: | Copyright © 2000-2002 Nathaniel Talbott. All rights reserved.
License: | Ruby license.

Required files

gtk test/unit/ui/testrunnermediator test/unit/ui/testrunnerutilities


File: testrunner.rb

testrunner.rb

Path: | test/unit/ui/gtk2/testrunner.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005
Author: | Kenta MURATA.
Copyright: | Copyright © 2000-2002 Kenta MURATA. All rights reserved.
License: | Ruby license.

Required files

gtk2 test/unit/ui/testrunnermediator test/unit/ui/testrunnerutilities


File: testrunnermediator.rb

testrunnermediator.rb

Path: | test/unit/ui/testrunnermediator.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005
Author: | Nathaniel Talbott.
Copyright: | Copyright © 2000-2002 Nathaniel Talbott. All rights reserved.
License: | Ruby license.

Required files

test/unit test/unit/util/observable test/unit/testresult


File: testrunnerutilities.rb

testrunnerutilities.rb

Path: | test/unit/ui/testrunnerutilities.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005
Author: | Nathaniel Talbott.
Copyright: | Copyright © 2000-2002 Nathaniel Talbott. All rights reserved.
License: | Ruby license.


File: testrunner.rb

testrunner.rb

Path: | test/unit/ui/tk/testrunner.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005
Original Author: | Nathaniel Talbott.
Author: | Kazuhiro NISHIYAMA.
Copyright: | Copyright © 2000-2002 Nathaniel Talbott. All rights reserved.
Copyright: | Copyright © 2003 Kazuhiro NISHIYAMA. All rights reserved.
License: | Ruby license.

Required files

tk test/unit/ui/testrunnermediator test/unit/ui/testrunnerutilities


File: backtracefilter.rb

backtracefilter.rb

Path: | test/unit/util/backtracefilter.rb
Last Update: | Sat Nov 22 08:36:13 AUS Eastern Daylight Time 2003


File: observable.rb

observable.rb

Path: | test/unit/util/observable.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005
Author: | Nathaniel Talbott.
Copyright: | Copyright © 2000-2002 Nathaniel Talbott. All rights reserved.
License: | Ruby license.

Required files

test/unit/util/procwrapper


File: procwrapper.rb

procwrapper.rb

Path: | test/unit/util/procwrapper.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005
Author: | Nathaniel Talbott.
Copyright: | Copyright © 2000-2002 Nathaniel Talbott. All rights reserved.
License: | Ruby license.


Class: Thread

Class | Thread
In: | thread.rb
Parent: | Object

Methods

exclusive

Public Class methods

exclusive() {|| ...}

Wraps a block in Thread.critical, restoring the original value upon exit from the critical section.

[Source]

# File thread.rb, line 29
  def Thread.exclusive
    _old = Thread.critical
    begin
      Thread.critical = true
      return yield
    ensure
      Thread.critical = _old
    end
  end


Class: ConditionVariable

Class | ConditionVariable
In: | 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

[Source]

# File thread.rb, line 192
  def initialize
    @waiters = []
  end

Public Instance methods

broadcast()

Wakes up all threads waiting for this lock.

[Source]

# File thread.rb, line 225
  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
signal()

Wakes up the first thread in line waiting for this lock.

[Source]

# File thread.rb, line 213
  def signal
    begin
      t = @waiters.shift
      t.run if t
    rescue ThreadError
      retry
    end
  end
wait(mutex)

Releases the lock held in mutex and waits; reacquires the lock on wakeup.

[Source]

# File thread.rb, line 199
  def wait(mutex)
    begin
      mutex.exclusive_unlock do
        @waiters.push(Thread.current)
        Thread.stop
      end
    ensure
      mutex.lock
    end
  end


Class: Mutex

Class | Mutex
In: | 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

[Source]

# File thread.rb, line 65
  def initialize
    @waiting = []
    @locked = false;
    @waiting.taint              # enable tainted comunication
    self.taint
  end

Public Instance methods

exclusive_unlock() {|| ...}

If the mutex is locked, unlocks the mutex, wakes one waiting thread, and yields in a critical section.

[Source]

# File thread.rb, line 145
  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
lock()

Attempts to grab the lock and waits if it isn’t available.

[Source]

# File thread.rb, line 97
  def lock
    while (Thread.critical = true; @locked)
      @waiting.push Thread.current
      Thread.stop
    end
    @locked = true
    Thread.critical = false
    self
  end
locked?()

Returns true if this lock is currently held by some thread.

[Source]

# File thread.rb, line 75
  def locked?
    @locked
  end
synchronize() {|| ...}

Obtains a lock, runs the block, and releases the lock when the block completes. See the example under Mutex.

[Source]

# File thread.rb, line 132
  def synchronize
    lock
    begin
      yield
    ensure
      unlock
    end
  end
try_lock()

Attempts to obtain the lock and returns immediately. Returns true if the lock was granted.

[Source]

# File thread.rb, line 83
  def try_lock
    result = false
    Thread.critical = true
    unless @locked
      @locked = true
      result = true
    end
    Thread.critical = false
    result
  end
unlock()

Releases the lock. Returns nil if ref wasn’t locked.

[Source]

# File thread.rb, line 110
  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


Class: Queue

Class | Queue
In: | 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.

[Source]

# File thread.rb, line 271
  def initialize
    @que = []
    @waiting = []
    @que.taint          # enable tainted comunication
    @waiting.taint
    self.taint
  end

Public Instance methods

<<(obj)

Alias for push

clear()

Removes all objects from the queue.

[Source]

# File thread.rb, line 345
  def clear
    @que.clear
  end
deq(non_block=false)

Alias for pop

empty?()

Returns true is the queue is empty.

[Source]

# File thread.rb, line 338
  def empty?
    @que.empty?
  end
enq(obj)

Alias for push

length()

Returns the length of the queue.

[Source]

# File thread.rb, line 352
  def length
    @que.length
  end
num_waiting()

Returns the number of threads waiting on the queue.

[Source]

# File thread.rb, line 364
  def num_waiting
    @waiting.size
  end
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.

[Source]

# File thread.rb, line 314
  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
push(obj)

Pushes obj to the queue.

[Source]

# File thread.rb, line 282
  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
shift(non_block=false)

Alias for pop

size()

Alias for length


Class: SizedQueue

Class | SizedQueue
In: | 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.

[Source]

# File thread.rb, line 379
  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

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.

[Source]

# File thread.rb, line 390
  def max
    @max
  end
max=(max)

Sets the maximum size of the queue.

[Source]

# File thread.rb, line 397
  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
num_waiting()

Returns the number of threads waiting on the queue.

[Source]

# File thread.rb, line 478
  def num_waiting
    @waiting.size + @queue_wait.size
  end
pop(*args)

Retrieves data from the queue and runs a waiting thread, if any.

[Source]

# File thread.rb, line 445
  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
push(obj)

Pushes obj to the queue. If there is no space left in the queue, waits until space becomes available.

[Source]

# File thread.rb, line 422
  def push(obj)
    Thread.critical = true
    while @que.length >= @max
      @queue_wait.push Thread.current
      Thread.stop
      Thread.critical = true
    end
    super
  end
shift(*args)

Alias for pop


Class: ThreadError

Class | ThreadError
In: | thread.rb
Parent: | StandardError


File: thread.rb

thread.rb

Path: | thread.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005
              thread.rb - thread support classes
                      $Date: 2005/06/07 09:41:17 $
                      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: | thwait.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005
  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


Class: ThreadsWait

Class | ThreadsWait
In: | 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.

[Source]

# File 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(*threads)

Creates a ThreadsWait object, specifying the threads to wait on. Non-blocking.

[Source]

# File thwait.rb, line 80
  def initialize(*threads)
    @threads = []
    @wait_queue = Queue.new
    join_nowait(*threads) unless threads.empty?
  end

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.

[Source]

# File thwait.rb, line 152
  def all_waits
    until @threads.empty?
      th = next_wait
      yield th if block_given?
    end
  end
empty?()

Returns true if there are no threads to be synchronized.

[Source]

# File thwait.rb, line 92
  def empty?
    @threads.empty?
  end
finished?()

Returns true if any thread has terminated.

[Source]

# File thwait.rb, line 99
  def finished?
    !@wait_queue.empty?
  end
join(*threads)

Waits for specified threads to terminate.

[Source]

# File thwait.rb, line 106
  def join(*threads)
    join_nowait(*threads)
    next_wait
  end
join_nowait(*threads)

Specifies the threads that this object will wait for, but does not actually wait.

[Source]

# File 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(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.

[Source]

# File 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


Class: Time

Class | Time
In: | time.rb
Parent: | Object

Implements the extensions to the Time class that are described in the documentation for the time.rb library.

Methods

httpdate httpdate iso8601 parse rfc2822 rfc2822 rfc822 xmlschema xmlschema zone_offset

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

rfc2822 | -> | rfc822
xmlschema | -> | iso8601

Public Class methods

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.

[Source]

# File 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
        Time.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
        Time.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
        Time.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
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.

[Source]

# File 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(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.

[Source]

# File 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 = Time.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
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.

[Source]

# File 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
zone_offset(zone, year=Time.now.year)

[Source]

# File 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

Public Instance methods

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).

[Source]

# File 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
iso8601(fraction_digits=0)

Alias for xmlschema

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.

[Source]

# File 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
rfc822()

Alias for rfc2822

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.

[Source]

# File 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


File: time.rb

time.rb

Path: | time.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

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


Module: Timeout

Module | Timeout
In: | timeout.rb

timeout.rb

execution timeout

Synopsis

  require 'timeout'
  status = Timeout::timeout(5) {
    # Something that should be interrupted if it takes too much time...
  }

Description

A way of performing a potentially long-running operation in a thread, and terminating it’s execution if it hasn’t finished by a fixed amount of time.

Previous versions of timeout didn’t provide use a module for namespace. This version provides both Timeout.timeout, and a backwards-compatible timeout.

Copyright

Copyright: | (C) 2000 Network Applied Communication Laboratory, Inc.
Copyright: | (C) 2000 Information-technology Promotion Agency, Japan

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().

[Source]

# File timeout.rb, line 37
  def timeout(sec, exception=Error)
    return yield if sec == nil or sec.zero?
    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


Class: Timeout::Error

Class | Timeout::Error
In: | timeout.rb
Parent: | Interrupt

Raised by Timeout#timeout when the block times out.


File: timeout.rb

timeout.rb

Path: | timeout.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

timeout.rb

execution timeout

Synopsis

  require 'timeout'
  status = Timeout::timeout(5) {
    # Something that should be interrupted if it takes too much time...
  }

Description

A way of performing a potentially long-running operation in a thread, and terminating it’s execution if it hasn’t finished by a fixed amount of time.

Previous versions of timeout didn’t provide use a module for namespace. This version provides both Timeout.timeout, and a backwards-compatible timeout.

Copyright

Copyright: | (C) 2000 Network Applied Communication Laboratory, Inc.
Copyright: | (C) 2000 Information-technology Promotion Agency, Japan

Methods

timeout

Constants

TimeoutError = Timeout::Error Another name for Timeout::Error, defined for backwards compatibility with earlier versions of timeout.rb.

Public Instance methods

timeout(n, e=Timeout::Error, &block)

Identical to:

  Timeout::timeout(n, e, &block).

Defined for backwards compatibility with earlier versions of timeout.rb, see Timeout#timeout.

[Source]

# File timeout.rb, line 61
def timeout(n, e=Timeout::Error, &block)
  Timeout::timeout(n, e, &block)
end


Module: Tk
In: tk/lib/tkextlib/winico/winico.rb
tk/lib/tkextlib/vu.rb
tk/lib/tkextlib/vu/spinbox.rb
tk/lib/tkextlib/vu/pie.rb
tk/lib/tkextlib/vu/dial.rb
tk/lib/tkextlib/vu/charts.rb
tk/lib/tkextlib/vu/bargraph.rb
tk/lib/tkextlib/treectrl/tktreectrl.rb
tk/lib/tkextlib/tktrans/tktrans.rb
tk/lib/tkextlib/tktable/tktable.rb
tk/lib/tkextlib/tkimg.rb
tk/lib/tkextlib/tkimg/xpm.rb
tk/lib/tkextlib/tkimg/xbm.rb
tk/lib/tkextlib/tkimg/window.rb
tk/lib/tkextlib/tkimg/tiff.rb
tk/lib/tkextlib/tkimg/tga.rb
tk/lib/tkextlib/tkimg/sun.rb
tk/lib/tkextlib/tkimg/sgi.rb
tk/lib/tkextlib/tkimg/ps.rb
tk/lib/tkextlib/tkimg/ppm.rb
tk/lib/tkextlib/tkimg/png.rb
tk/lib/tkextlib/tkimg/pixmap.rb
tk/lib/tkextlib/tkimg/pcx.rb
tk/lib/tkextlib/tkimg/jpeg.rb
tk/lib/tkextlib/tkimg/ico.rb
tk/lib/tkextlib/tkimg/gif.rb
tk/lib/tkextlib/tkimg/bmp.rb
tk/lib/tkextlib/tkHTML/htmlwidget.rb
tk/lib/tkextlib/tkDND.rb
tk/lib/tkextlib/tkDND/tkdnd.rb
tk/lib/tkextlib/tkDND/shape.rb
tk/lib/tkextlib/tile.rb
tk/lib/tkextlib/tile/tsquare.rb
tk/lib/tkextlib/tile/tseparator.rb
tk/lib/tkextlib/tile/tscrollbar.rb
tk/lib/tkextlib/tile/tscale.rb
tk/lib/tkextlib/tile/treeview.rb
tk/lib/tkextlib/tile/tradiobutton.rb
tk/lib/tkextlib/tile/tprogressbar.rb
tk/lib/tkextlib/tile/tpaned.rb
tk/lib/tkextlib/tile/tnotebook.rb
tk/lib/tkextlib/tile/tmenubutton.rb
tk/lib/tkextlib/tile/tlabelframe.rb
tk/lib/tkextlib/tile/tlabel.rb
tk/lib/tkextlib/tile/tframe.rb
tk/lib/tkextlib/tile/tentry.rb
tk/lib/tkextlib/tile/tcombobox.rb
tk/lib/tkextlib/tile/tcheckbutton.rb
tk/lib/tkextlib/tile/tbutton.rb
tk/lib/tkextlib/tile/style.rb
tk/lib/tkextlib/tile/dialog.rb
tk/lib/tkextlib/tclx/tclx.rb
tk/lib/tkextlib/tcllib.rb
tk/lib/tkextlib/tcllib/tkpiechart.rb
tk/lib/tkextlib/tcllib/tablelist_tile.rb
tk/lib/tkextlib/tcllib/tablelist_core.rb
tk/lib/tkextlib/tcllib/plotchart.rb
tk/lib/tkextlib/tcllib/ip_entry.rb
tk/lib/tkextlib/tcllib/ico.rb
tk/lib/tkextlib/tcllib/datefield.rb
tk/lib/tkextlib/tcllib/cursor.rb
tk/lib/tkextlib/tcllib/ctext.rb
tk/lib/tkextlib/tcllib/autoscroll.rb
tk/lib/tkextlib/iwidgets.rb
tk/lib/tkextlib/iwidgets/watch.rb
tk/lib/tkextlib/iwidgets/toolbar.rb
tk/lib/tkextlib/iwidgets/timefield.rb
tk/lib/tkextlib/iwidgets/timeentry.rb
tk/lib/tkextlib/iwidgets/tabset.rb
tk/lib/tkextlib/iwidgets/tabnotebook.rb
tk/lib/tkextlib/iwidgets/spintime.rb
tk/lib/tkextlib/iwidgets/spinner.rb
tk/lib/tkextlib/iwidgets/spinint.rb
tk/lib/tkextlib/iwidgets/spindate.rb
tk/lib/tkextlib/iwidgets/shell.rb
tk/lib/tkextlib/iwidgets/selectiondialog.rb
tk/lib/tkextlib/iwidgets/selectionbox.rb
tk/lib/tkextlib/iwidgets/scrolledwidget.rb
tk/lib/tkextlib/iwidgets/scrolledtext.rb
tk/lib/tkextlib/iwidgets/scrolledlistbox.rb
tk/lib/tkextlib/iwidgets/scrolledhtml.rb
tk/lib/tkextlib/iwidgets/scrolledframe.rb
tk/lib/tkextlib/iwidgets/scrolledcanvas.rb
tk/lib/tkextlib/iwidgets/scopedobject.rb
tk/lib/tkextlib/iwidgets/radiobox.rb
tk/lib/tkextlib/iwidgets/pushbutton.rb
tk/lib/tkextlib/iwidgets/promptdialog.rb
tk/lib/tkextlib/iwidgets/panedwindow.rb
tk/lib/tkextlib/iwidgets/optionmenu.rb
tk/lib/tkextlib/iwidgets/notebook.rb
tk/lib/tkextlib/iwidgets/messagedialog.rb
tk/lib/tkextlib/iwidgets/messagebox.rb
tk/lib/tkextlib/iwidgets/menubar.rb
tk/lib/tkextlib/iwidgets/mainwindow.rb
tk/lib/tkextlib/iwidgets/labeledwidget.rb
tk/lib/tkextlib/iwidgets/labeledframe.rb
tk/lib/tkextlib/iwidgets/hyperhelp.rb
tk/lib/tkextlib/iwidgets/hierarchy.rb
tk/lib/tkextlib/iwidgets/finddialog.rb
tk/lib/tkextlib/iwidgets/fileselectiondialog.rb
tk/lib/tkextlib/iwidgets/fileselectionbox.rb
tk/lib/tkextlib/iwidgets/feedback.rb
tk/lib/tkextlib/iwidgets/extfileselectiondialog.rb
tk/lib/tkextlib/iwidgets/extfileselectionbox.rb
tk/lib/tkextlib/iwidgets/extbutton.rb
tk/lib/tkextlib/iwidgets/entryfield.rb
tk/lib/tkextlib/iwidgets/disjointlistbox.rb
tk/lib/tkextlib/iwidgets/dialogshell.rb
tk/lib/tkextlib/iwidgets/dialog.rb
tk/lib/tkextlib/iwidgets/datefield.rb
tk/lib/tkextlib/iwidgets/dateentry.rb
tk/lib/tkextlib/iwidgets/combobox.rb
tk/lib/tkextlib/iwidgets/checkbox.rb
tk/lib/tkextlib/iwidgets/canvasprintdialog.rb
tk/lib/tkextlib/iwidgets/canvasprintbox.rb
tk/lib/tkextlib/iwidgets/calendar.rb
tk/lib/tkextlib/iwidgets/buttonbox.rb
tk/lib/tkextlib/itk/incr_tk.rb
tk/lib/tkextlib/itcl/incr_tcl.rb
tk/lib/tkextlib/ICONS/icons.rb
tk/lib/tkextlib/bwidget.rb
tk/lib/tkextlib/bwidget/widget.rb
tk/lib/tkextlib/bwidget/tree.rb
tk/lib/tkextlib/bwidget/titleframe.rb
tk/lib/tkextlib/bwidget/statusbar.rb
tk/lib/tkextlib/bwidget/spinbox.rb
tk/lib/tkextlib/bwidget/separator.rb
tk/lib/tkextlib/bwidget/selectfont.rb
tk/lib/tkextlib/bwidget/selectcolor.rb
tk/lib/tkextlib/bwidget/scrollview.rb
tk/lib/tkextlib/bwidget/scrolledwindow.rb
tk/lib/tkextlib/bwidget/scrollableframe.rb
tk/lib/tkextlib/bwidget/progressdlg.rb
tk/lib/tkextlib/bwidget/progressbar.rb
tk/lib/tkextlib/bwidget/passwddlg.rb
tk/lib/tkextlib/bwidget/panelframe.rb
tk/lib/tkextlib/bwidget/panedwindow.rb
tk/lib/tkextlib/bwidget/pagesmanager.rb
tk/lib/tkextlib/bwidget/notebook.rb
tk/lib/tkextlib/bwidget/messagedlg.rb
tk/lib/tkextlib/bwidget/mainframe.rb
tk/lib/tkextlib/bwidget/listbox.rb
tk/lib/tkextlib/bwidget/labelframe.rb
tk/lib/tkextlib/bwidget/labelentry.rb
tk/lib/tkextlib/bwidget/label.rb
tk/lib/tkextlib/bwidget/entry.rb
tk/lib/tkextlib/bwidget/dynamichelp.rb
tk/lib/tkextlib/bwidget/dropsite.rb
tk/lib/tkextlib/bwidget/dragsite.rb
tk/lib/tkextlib/bwidget/dialog.rb
tk/lib/tkextlib/bwidget/combobox.rb
tk/lib/tkextlib/bwidget/buttonbox.rb
tk/lib/tkextlib/bwidget/button.rb
tk/lib/tkextlib/bwidget/bitmap.rb
tk/lib/tkextlib/bwidget/arrowbutton.rb
tk/lib/tkextlib/blt.rb
tk/lib/tk.rb
tk/lib/tk/wm.rb
tk/lib/tk/variable.rb
tk/lib/tk/validation.rb
tk/lib/tk/scrollable.rb
tk/lib/tk/optionobj.rb
tk/lib/tk/macpkg.rb
tk/lib/tk/encodedstr.rb
tk/lib/tk/clock.rb
tk/lib/tk/autoload.rb

sub-module of Tk

Methods

BinaryString EncodedString UTF8_String add_kinsoku bell bell_on_display const_missing current_grabs cursor_display delete_kinsoku destroy errorCode errorInfo exit focus focus_lastfor focus_next focus_prev focus_to fromUTF8 grid grid_forget has_mainwindow? load_tcllibrary load_tclscript load_tclscript_rsrc load_tclscript_rsrcid lower_window pack pack_forget place place_forget raise_window root show_kinsoku strictMotif subst_tk_backslash subst_utf_backslash thread_update thread_update_idletasks toUTF8 to_backslash_sequence ungrid unload_tcllibrary unpack unplace update update update_idletasks utf_to_backslash utf_to_backslash_sequence

Included Modules

TkCore

Classes and Modules

Module Tk::BLT
Module Tk::BWidget
Module Tk::Clock
Module Tk::Encoding
Module Tk::Img
Module Tk::Itcl
Module Tk::ItemValidateConfigure
Module Tk::Itk
Module Tk::Iwidgets
Module Tk::Scrollable
Module Tk::TclX
Module Tk::Tcllib
Module Tk::Tile
Module Tk::TkDND
Module Tk::TkTrans
Module Tk::ValidateConfigure
Module Tk::Vu
Module Tk::Wm
Module Tk::X_Scrollable
Module Tk::Y_Scrollable
Class Tk::BinaryString
Class Tk::EncodedString
Class Tk::HTML_Widget
Class Tk::ICONS
Class Tk::OptionObj
Class Tk::TkTable
Class Tk::TreeCtrl
Class Tk::UTF8_String
Class Tk::Winico

Constants

TreeCtrl_Widget | = | TreeCtrl
TCL_VERSION | = | INTERP._invoke_without_enc("info", "tclversion").freeze
TCL_PATCHLEVEL | = | INTERP._invoke_without_enc("info", "patchlevel").freeze
TCL_MAJOR_VERSION | = | major.to_i
TCL_MINOR_VERSION | = | minor.to_i
TK_VERSION | = | INTERP._invoke_without_enc("set", "tk_version").freeze
TK_PATCHLEVEL | = | INTERP._invoke_without_enc("set", "tk_patchLevel").freeze
TK_MAJOR_VERSION | = | major.to_i
TK_MINOR_VERSION | = | minor.to_i
JAPANIZED_TK | = | (INTERP._invoke_without_enc("info", "commands", "kanji") != "").freeze
RELEASE_DATE | = | '2005-10-24'.freeze
AUTO_PATH | = | TkVarAccess.new('auto_path', auto_path)
TCL_PACKAGE_PATH | = | TkVarAccess.new('tcl_pkgPath')
PACKAGE_PATH | = | TCL_PACKAGE_PATH
TCL_LIBRARY_PATH | = | TkVarAccess.new('tcl_libPath')
LIBRARY_PATH | = | TCL_LIBRARY_PATH
TCL_PRECISION | = | TkVarAccess.new('tcl_precision')

Public Class methods

BinaryString(str)

[Source]

# File tk/lib/tk/autoload.rb, line 191
  def Tk.BinaryString(str); Tk::BinaryString.new(str); end
EncodedString(str, enc = nil)

[Source]

# File tk/lib/tk/autoload.rb, line 188
  def Tk.EncodedString(str, enc = nil); Tk::EncodedString.new(str, enc); end
UTF8_String(str)

[Source]

# File tk/lib/tk/autoload.rb, line 194
  def Tk.UTF8_String(str); Tk::UTF8_String.new(str); end
add_kinsoku(chars, mode='both')

[Source]

# File tk/lib/tk.rb, line 2020
  def Tk.add_kinsoku(chars, mode='both')
    begin
      if /^8\.*/ === TK_VERSION  && JAPANIZED_TK
        tk_split_simplelist(tk_call('kinsoku', 'add', mode,
                                    *(chars.split(''))))
      else
        []
      end
    rescue
      []
    end
  end
bell(nice = false)

[Source]

# File tk/lib/tk.rb, line 1869
  def Tk.bell(nice = false)
    if nice
      tk_call_without_enc('bell', '-nice')
    else
      tk_call_without_enc('bell')
    end
    nil
  end
bell_on_display(win, nice = false)

[Source]

# File tk/lib/tk.rb, line 1878
  def Tk.bell_on_display(win, nice = false)
    if nice
      tk_call_without_enc('bell', '-displayof', win, '-nice')
    else
      tk_call_without_enc('bell', '-displayof', win)
    end
    nil
  end
const_missing(sym)

[Source]

# File tk/lib/tk.rb, line 1748
  def Tk.const_missing(sym)
    case(sym)
    when :TCL_LIBRARY
      INTERP._invoke_without_enc('global', 'tcl_library')
      INTERP._invoke("set", "tcl_library").freeze

    when :TK_LIBRARY
      INTERP._invoke_without_enc('global', 'tk_library')
      INTERP._invoke("set", "tk_library").freeze

    when :LIBRARY
      INTERP._invoke("info", "library").freeze

    #when :PKG_PATH, :PACKAGE_PATH, :TCL_PACKAGE_PATH
    #  INTERP._invoke_without_enc('global', 'tcl_pkgPath')
    #  tk_split_simplelist(INTERP._invoke('set', 'tcl_pkgPath'))

    #when :LIB_PATH, :LIBRARY_PATH, :TCL_LIBRARY_PATH
    #  INTERP._invoke_without_enc('global', 'tcl_libPath')
    #  tk_split_simplelist(INTERP._invoke('set', 'tcl_libPath'))

    when :PLATFORM, :TCL_PLATFORM
      if $SAFE >= 4
        fail SecurityError, "can't get #{sym} when $SAFE >= 4"
      end
      INTERP._invoke_without_enc('global', 'tcl_platform')
      Hash[*tk_split_simplelist(INTERP._invoke_without_enc('array', 'get',
                                                           'tcl_platform'))]

    when :ENV
      INTERP._invoke_without_enc('global', 'env')
      Hash[*tk_split_simplelist(INTERP._invoke('array', 'get', 'env'))]

    #when :AUTO_PATH   #<===
    #  tk_split_simplelist(INTERP._invoke('set', 'auto_path'))

    #when :AUTO_OLDPATH
    #  tk_split_simplelist(INTERP._invoke('set', 'auto_oldpath'))

    when :AUTO_INDEX
      INTERP._invoke_without_enc('global', 'auto_index')
      Hash[*tk_split_simplelist(INTERP._invoke('array', 'get', 'auto_index'))]

    when :PRIV, :PRIVATE, :TK_PRIV
      priv = {}
      if INTERP._invoke_without_enc('info', 'vars', 'tk::Priv') != ""
        var_nam = 'tk::Priv'
      else
        var_nam = 'tkPriv'
      end
      INTERP._invoke_without_enc('global', var_nam)
      Hash[*tk_split_simplelist(INTERP._invoke('array', 'get',
                                               var_nam))].each{|k,v|
        k.freeze
        case v
        when /^-?\d+$/
          priv[k] = v.to_i
        when /^-?\d+\.?\d*(e[-+]?\d+)?$/
          priv[k] = v.to_f
        else
          priv[k] = v.freeze
        end
      }
      priv

    else
      raise NameError, 'uninitialized constant Tk::' + sym.id2name
    end
  end
current_grabs(win = nil)

[Source]

# File tk/lib/tk.rb, line 1972
  def Tk.current_grabs(win = nil)
    if win
      window(tk_call_without_enc('grab', 'current', win))
    else
      tk_split_list(tk_call_without_enc('grab', 'current'))
    end
  end
cursor_display(parent=None)

[Source]

# File tk/lib/tkextlib/tcllib/cursor.rb, line 46
  def self.cursor_display(parent=None)
    # Pops up a dialog with a listbox containing all the cursor names.
    # Selecting a cursor name will display it in that dialog.
    # This is simply for viewing any available cursors on the platform .
    #tk_call_without_enc('::cursor::display', parent)
    Tk::Tcllib::Cursor.cursor_display(parent)
  end
delete_kinsoku(chars, mode='both')

[Source]

# File tk/lib/tk.rb, line 2032
  def Tk.delete_kinsoku(chars, mode='both')
    begin
      if /^8\.*/ === TK_VERSION  && JAPANIZED_TK
        tk_split_simplelist(tk_call('kinsoku', 'delete', mode,
                            *(chars.split(''))))
      end
    rescue
    end
  end
destroy(*wins)

[Source]

# File tk/lib/tk.rb, line 1887
  def Tk.destroy(*wins)
    #tk_call_without_enc('destroy', *wins)
    tk_call_without_enc('destroy', *(wins.collect{|win|
                                       if win.kind_of?(TkWindow)
                                         win.epath
                                       else
                                         win
                                       end
                                     }))
  end
errorCode()

[Source]

# File tk/lib/tk.rb, line 1823
  def Tk.errorCode
    INTERP._invoke_without_enc('global', 'errorCode')
    code = tk_split_simplelist(INTERP._invoke_without_enc('set', 'errorCode'))
    case code[0]
    when 'CHILDKILLED', 'CHILDSTATUS', 'CHILDSUSP'
      begin
        pid = Integer(code[1])
        code[1] = pid
      rescue
      end
    end
    code
  end
errorInfo()

[Source]

# File tk/lib/tk.rb, line 1818
  def Tk.errorInfo
    INTERP._invoke_without_enc('global', 'errorInfo')
    INTERP._invoke_without_enc('set', 'errorInfo')
  end
exit()

[Source]

# File tk/lib/tk.rb, line 1898
  def Tk.exit
    tk_call_without_enc('destroy', '.')
  end
focus(display=nil)

[Source]

# File tk/lib/tk.rb, line 1980
  def Tk.focus(display=nil)
    if display == nil
      window(tk_call_without_enc('focus'))
    else
      window(tk_call_without_enc('focus', '-displayof', display))
    end
  end
focus_lastfor(win)

[Source]

# File tk/lib/tk.rb, line 1996
  def Tk.focus_lastfor(win)
    window(tk_call_without_enc('focus', '-lastfor', win))
  end
focus_next(win)

[Source]

# File tk/lib/tk.rb, line 2000
  def Tk.focus_next(win)
    TkManageFocus.next(win)
  end
focus_prev(win)

[Source]

# File tk/lib/tk.rb, line 2004
  def Tk.focus_prev(win)
    TkManageFocus.prev(win)
  end
focus_to(win, force=false)

[Source]

# File tk/lib/tk.rb, line 1988
  def Tk.focus_to(win, force=false)
    if force
      tk_call_without_enc('focus', '-force', win)
    else
      tk_call_without_enc('focus', win)
    end
  end
fromUTF8(str, encoding = nil)

[Source]

# File tk/lib/tk.rb, line 2046
  def Tk.fromUTF8(str, encoding = nil)
    _fromUTF8(str, encoding)
  end
grid(*args)

[Source]

# File tk/lib/tk.rb, line 1912
  def Tk.grid(*args)
    TkGrid.configure(*args)
  end
grid_forget(*args)

[Source]

# File tk/lib/tk.rb, line 1915
  def Tk.grid_forget(*args)
    TkGrid.forget(*args)
  end
has_mainwindow?()

[Source]

# File tk/lib/tk.rb, line 1837
  def Tk.has_mainwindow?
    INTERP.has_mainwindow?
  end
load_tcllibrary(file, pkg_name=None, interp=None)

[Source]

# File tk/lib/tk.rb, line 1854
  def Tk.load_tcllibrary(file, pkg_name=None, interp=None)
    tk_call('load', file, pkg_name, interp)
  end
load_tclscript(file, enc=nil)

[Source]

# File tk/lib/tk.rb, line 1845
  def Tk.load_tclscript(file, enc=nil)
    if enc
      # TCL_VERSION >= 8.5
      tk_call('source', '-encoding', enc, file)
    else
      tk_call('source', file)
    end
  end
load_tclscript_rsrc(resource_name, file=None)

[Source]

# File tk/lib/tk/macpkg.rb, line 12
  def Tk.load_tclscript_rsrc(resource_name, file=None)
    # Mac only
    tk_call('source', '-rsrc', resource_name, file)
  end
load_tclscript_rsrcid(resource_id, file=None)

[Source]

# File tk/lib/tk/macpkg.rb, line 17
  def Tk.load_tclscript_rsrcid(resource_id, file=None)
    # Mac only
    tk_call('source', '-rsrcid', resource_id, file)
  end
lower_window(win, below=None)

[Source]

# File tk/lib/tk.rb, line 1963
  def Tk.lower_window(win, below=None)
    tk_call('lower', _epath(win), _epath(below))
    nil
  end
pack(*args)

[Source]

# File tk/lib/tk.rb, line 1902
  def Tk.pack(*args)
    TkPack.configure(*args)
  end
pack_forget(*args)

[Source]

# File tk/lib/tk.rb, line 1905
  def Tk.pack_forget(*args)
    TkPack.forget(*args)
  end
place(*args)

[Source]

# File tk/lib/tk.rb, line 1922
  def Tk.place(*args)
    TkPlace.configure(*args)
  end
place_forget(*args)

[Source]

# File tk/lib/tk.rb, line 1925
  def Tk.place_forget(*args)
    TkPlace.forget(*args)
  end
raise_window(win, above=None)

[Source]

# File tk/lib/tk.rb, line 1967
  def Tk.raise_window(win, above=None)
    tk_call('raise', _epath(win), _epath(above))
    nil
  end
show_kinsoku(mode='both')

[Source]

# File tk/lib/tk.rb, line 2012
  def Tk.show_kinsoku(mode='both')
    begin
      if /^8\.*/ === TK_VERSION  && JAPANIZED_TK
        tk_split_simplelist(tk_call('kinsoku', 'show', mode))
      end
    rescue
    end
  end
strictMotif(mode=None)

[Source]

# File tk/lib/tk.rb, line 2008
  def Tk.strictMotif(mode=None)
    bool(tk_call_without_enc('set', 'tk_strictMotif', mode))
  end
subst_tk_backslash(str)

[Source]

# File tk/lib/tk.rb, line 2058
  def Tk.subst_tk_backslash(str)
    Tk::EncodedString.subst_tk_backslash(str)
  end
subst_utf_backslash(str)

[Source]

# File tk/lib/tk.rb, line 2055
  def Tk.subst_utf_backslash(str)
    Tk::EncodedString.subst_utf_backslash(str)
  end
thread_update(idle=nil)
NOTE: If no eventloop-thread is running, "thread_update" method is same to "update" method. Else, "thread_update" method waits to complete idletask operation on the eventloop-thread.

[Source]

# File tk/lib/tk.rb, line 1952
  def Tk.thread_update(idle=nil)
    if idle
      tk_call_without_enc('thread_update', 'idletasks')
    else
      tk_call_without_enc('thread_update')
    end
  end
thread_update_idletasks()

[Source]

# File tk/lib/tk.rb, line 1959
  def Tk.thread_update_idletasks
    thread_update(true)
  end
toUTF8(str, encoding = nil)

[Source]

# File tk/lib/tk.rb, line 2042
  def Tk.toUTF8(str, encoding = nil)
    _toUTF8(str, encoding)
  end
to_backslash_sequence(str)

[Source]

# File tk/lib/tk.rb, line 2067
  def Tk.to_backslash_sequence(str)
    Tk::EncodedString.to_backslash_sequence(str)
  end
ungrid(*args)

[Source]

# File tk/lib/tk.rb, line 1918
  def Tk.ungrid(*args)
    TkGrid.forget(*args)
  end
unload_tcllibrary(*args)

[Source]

# File tk/lib/tk.rb, line 1858
  def Tk.unload_tcllibrary(*args)
    if args[-1].kind_of?(Hash)
      keys = _symbolkey2str(args.pop)
      nocomp = (keys['nocomplain'])? '-nocomplain': None
      keeplib = (keys['keeplibrary'])? '-keeplibrary': None
      tk_call('unload', nocomp, keeplib, '--', *args)
    else
      tk_call('unload', *args)
    end
  end
unpack(*args)

[Source]

# File tk/lib/tk.rb, line 1908
  def Tk.unpack(*args)
    TkPack.forget(*args)
  end
unplace(*args)

[Source]

# File tk/lib/tk.rb, line 1928
  def Tk.unplace(*args)
    TkPlace.forget(*args)
  end
update(idle=nil)

[Source]

# File tk/lib/tk.rb, line 1932
  def Tk.update(idle=nil)
    if idle
      tk_call_without_enc('update', 'idletasks')
    else
      tk_call_without_enc('update')
    end
  end
update_idletasks()

[Source]

# File tk/lib/tk.rb, line 1939
  def Tk.update_idletasks
    update(true)
  end
utf_to_backslash(str)

[Source]

# File tk/lib/tk.rb, line 2064
  def Tk.utf_to_backslash(str)
    Tk::EncodedString.utf_to_backslash_sequence(str)
  end
utf_to_backslash_sequence(str)

[Source]

# File tk/lib/tk.rb, line 2061
  def Tk.utf_to_backslash_sequence(str)
    Tk::EncodedString.utf_to_backslash_sequence(str)
  end

Public Instance methods

root()

[Source]

# File tk/lib/tk.rb, line 1841
  def root
    TkRoot.new
  end
update(idle=nil)

[Source]

# File tk/lib/tk.rb, line 1942
  def update(idle=nil)
    # only for backward compatibility (This never be recommended to use)
    Tk.update(idle)
    self
  end


Class: MultiTkIp

Class | MultiTkIp
In: | tk/lib/remote-tk.rb tk/lib/multi-tk.rb
Parent: | Object

remove methods for security

Methods

_DEFAULT_MASTER _IP_TABLE _TK_TABLE_LIST __create_safe_slave_obj __create_trusted_slave_obj __eval __getip __invoke _add_new_tables _add_tk_procs _conv_listelement _conv_listelement _create_console _create_slave_object _default_delete_hook _destroy_slaves_of_slaveIP _eval _eval _eval_with_enc _eval_with_enc _eval_without_enc _eval_without_enc _fromUTF8 _fromUTF8 _get_global_var _get_global_var _get_global_var2 _get_global_var2 _get_variable _get_variable _get_variable2 _get_variable2 _init_ip_env _init_ip_internal _invoke _invoke _invoke_with_enc _invoke_with_enc _invoke_without_enc _invoke_without_enc _ip_id_ _ip_id_ _merge_tklist _merge_tklist _receiver_mainloop _return_value _return_value _set_global_var _set_global_var _set_global_var2 _set_global_var2 _set_variable _set_variable _set_variable2 _set_variable2 _split_tklist _split_tklist _thread_tkwait _thread_tkwait _thread_vwait _thread_vwait _tk_cmd_tbl _tk_table_list _tk_windows _toUTF8 _toUTF8 _unset_global_var _unset_global_var _unset_global_var2 _unset_global_var2 _unset_variable _unset_variable _unset_variable2 _unset_variable2 abort abort add_tk_procs alias_delete alias_delete alias_info alias_info alias_target alias_target aliases aliases alive? alive? allow_ruby_exit= allow_ruby_exit= allow_ruby_exit? allow_ruby_exit? assign_receiver_and_watchdog background_call background_eval_proc background_eval_str background_eval_string bg_call bg_eval_proc bg_eval_str bg_eval_string bgerror bgerror call call call cb_entry_class cb_error cb_eval create_table def_alias def_alias delete delete delete_cmd delete_cmd delete_slaves delete_slaves deleted? deleted? do_one_event encoding encoding= encoding_convert_from encoding_convert_to encoding_convertfrom encoding_convertto eval_callback eval_proc eval_proc eval_str eval_string eval_string exist? exist? exit exit exit! exit! expose_cmd expose_cmd get_bgerror_handler get_cb_entry get_eventloop_tick get_eventloop_weight get_limit get_limit get_no_event_wait has_mainwindow? has_mainwindow? hidden_cmds hidden_cmds hide_cmd hide_cmd inherited init_ip_env init_ip_internal inspect inspect invalid_namespace? invalid_namespace? invoke_hidden invoke_hidden invoke_hidden_on_global invoke_hidden_on_global invoke_hidden_on_namespace invoke_hidden_on_namespace ip_name ip_name mainloop mainloop mainloop_abort_on_exception mainloop_abort_on_exception= mainloop_watchdog make_safe make_safe mark_trusted mark_trusted master? master? method_missing new new new new_master new_safe_slave new_slave path path recursion_limit recursion_limit restart restart running_mainloop? safe? safe? safe_base? safe_base? safe_level safe_level safe_level= safe_level= safeip_add_to_access_path safeip_configinfo safeip_configure safeip_delete safeip_find_in_access_path safeip_set_log_cmd set_bgerror_handler set_cb_error set_eventloop_tick set_eventloop_weight set_limit set_limit set_no_event_wait set_safe_level set_safe_level share_stderr share_stderr share_stdin share_stdin share_stdio share_stdio share_stdout share_stdout slave? slave? slaves slaves thread_eval_proc tk_cmd_tbl tk_object_table tk_windows to_eval to_eval transfer_stderr transfer_stderr transfer_stdin transfer_stdin transfer_stdio transfer_stdio transfer_stdout transfer_stdout wait_on_mainloop= wait_on_mainloop?

External Aliases

new | -> | __new
new_master | -> | new
new_slave | -> | new_trusted_slave
new_safe_slave | -> | new_safeTk

Attributes

cmd | [R]
ip | [R]
ret | [RW]
target | [RW]

Public Class methods

_DEFAULT_MASTER()

[Source]

# File tk/lib/remote-tk.rb, line 19
  def self._DEFAULT_MASTER
    # work only once
    if @flag
      @flag = nil
      @@DEFAULT_MASTER
    else
      nil
    end
  end
_IP_TABLE()

[Source]

# File tk/lib/remote-tk.rb, line 15
  def self._IP_TABLE; @@IP_TABLE; end
_TK_TABLE_LIST()

[Source]

# File tk/lib/remote-tk.rb, line 16
  def self._TK_TABLE_LIST; @@TK_TABLE_LIST; end
__getip()

[Source]

# File tk/lib/multi-tk.rb, line 1096
  def self.__getip
    current = Thread.current
    if TclTkLib.mainloop_thread? != false && current['callback_ip']
      return current['callback_ip']
    end
    if current.group == ThreadGroup::Default
      @@DEFAULT_MASTER
    else
      ip = @@IP_TABLE[current.group]
      unless ip
        fail SecurityError,
          "cannot call Tk methods on #{Thread.current.inspect}"
      end
      ip
    end
  end
_conv_listelement(arg)

[Source]

# File tk/lib/multi-tk.rb, line 1813
  def _conv_listelement(arg)
    __getip._conv_listelement(arg)
  end
_create_console()

[Source]

# File tk/lib/multi-tk.rb, line 1817
  def _create_console
    __getip._create_console
  end
_eval(str)

[Source]

# File tk/lib/multi-tk.rb, line 1725
  def _eval(str)
    __getip._eval(str)
  end
_eval_with_enc(str)

[Source]

# File tk/lib/multi-tk.rb, line 1741
  def _eval_with_enc(str)
    __getip._eval_with_enc(str)
  end
_eval_without_enc(str)

[Source]

# File tk/lib/multi-tk.rb, line 1733
  def _eval_without_enc(str)
    __getip._eval_without_enc(str)
  end
_fromUTF8(str, encoding=nil)

[Source]

# File tk/lib/multi-tk.rb, line 1753
  def _fromUTF8(str, encoding=nil)
    __getip._fromUTF8(str, encoding)
  end
_get_global_var(var)

[Source]

# File tk/lib/multi-tk.rb, line 1788
  def _get_global_var(var)
    __getip._get_global_var(var)
  end
_get_global_var2(var, idx)

[Source]

# File tk/lib/multi-tk.rb, line 1791
  def _get_global_var2(var, idx)
    __getip._get_global_var2(var, idx)
  end
_get_variable(var, flag)

[Source]

# File tk/lib/multi-tk.rb, line 1769
  def _get_variable(var, flag)
    __getip._get_variable(var, flag)
  end
_get_variable2(var, idx, flag)

[Source]

# File tk/lib/multi-tk.rb, line 1772
  def _get_variable2(var, idx, flag)
    __getip._get_variable2(var, idx, flag)
  end
_invoke(*args)

[Source]

# File tk/lib/multi-tk.rb, line 1729
  def _invoke(*args)
    __getip._invoke(*args)
  end
_invoke_with_enc(*args)

[Source]

# File tk/lib/multi-tk.rb, line 1745
  def _invoke_with_enc(*args)
    __getip._invoke_with_enc(*args)
  end
_invoke_without_enc(*args)

[Source]

# File tk/lib/multi-tk.rb, line 1737
  def _invoke_without_enc(*args)
    __getip._invoke_without_enc(*args)
  end
_ip_id_()

[Source]

# File tk/lib/multi-tk.rb, line 1089
  def self._ip_id_
    __getip._ip_id_
  end
_merge_tklist(*args)

[Source]

# File tk/lib/multi-tk.rb, line 1810
  def _merge_tklist(*args)
    __getip._merge_tklist(*args)
  end
_return_value()

[Source]

# File tk/lib/multi-tk.rb, line 1765
  def _return_value
    __getip._return_value
  end
_set_global_var(var, value)

[Source]

# File tk/lib/multi-tk.rb, line 1794
  def _set_global_var(var, value)
    __getip._set_global_var(var, value)
  end
_set_global_var2(var, idx, value)

[Source]

# File tk/lib/multi-tk.rb, line 1797
  def _set_global_var2(var, idx, value)
    __getip._set_global_var2(var, idx, value)
  end
_set_variable(var, value, flag)

[Source]

# File tk/lib/multi-tk.rb, line 1775
  def _set_variable(var, value, flag)
    __getip._set_variable(var, value, flag)
  end
_set_variable2(var, idx, value, flag)

[Source]

# File tk/lib/multi-tk.rb, line 1778
  def _set_variable2(var, idx, value, flag)
    __getip._set_variable2(var, idx, value, flag)
  end
_split_tklist(str)

[Source]

# File tk/lib/multi-tk.rb, line 1807
  def _split_tklist(str)
    __getip._split_tklist(str)
  end
_thread_tkwait(mode, target)

[Source]

# File tk/lib/multi-tk.rb, line 1761
  def _thread_tkwait(mode, target)
    __getip._thread_tkwait(mode, target)
  end
_thread_vwait(var)

[Source]

# File tk/lib/multi-tk.rb, line 1757
  def _thread_vwait(var)
    __getip._thread_vwait(var)
  end
_toUTF8(str, encoding=nil)

[Source]

# File tk/lib/multi-tk.rb, line 1749
  def _toUTF8(str, encoding=nil)
    __getip._toUTF8(str, encoding)
  end
_unset_global_var(var)

[Source]

# File tk/lib/multi-tk.rb, line 1800
  def _unset_global_var(var)
    __getip._unset_global_var(var)
  end
_unset_global_var2(var, idx)

[Source]

# File tk/lib/multi-tk.rb, line 1803
  def _unset_global_var2(var, idx)
    __getip._unset_global_var2(var, idx)
  end
_unset_variable(var, flag)

[Source]

# File tk/lib/multi-tk.rb, line 1781
  def _unset_variable(var, flag)
    __getip._unset_variable(var, flag)
  end
_unset_variable2(var, idx, flag)

[Source]

# File tk/lib/multi-tk.rb, line 1784
  def _unset_variable2(var, idx, flag)
    __getip._unset_variable2(var, idx, flag)
  end
abort(msg = nil)

[Source]

# File tk/lib/multi-tk.rb, line 1702
  def abort(msg = nil)
    __getip.abort(msg)
  end
add_tk_procs(name, args=nil, body=nil)

[Source]

# File tk/lib/multi-tk.rb, line 1365
  def self.add_tk_procs(name, args=nil, body=nil)
    @@ADD_TK_PROCS << [name, args, body]
    @@IP_TABLE.each{|tg, ip|
      ip._add_tk_procs(name, args, body)
    }
  end
alias_delete(slave, cmd_name)

[Source]

# File tk/lib/multi-tk.rb, line 2275
  def self.alias_delete(slave, cmd_name)
    __getip.alias_delete(slave, cmd_name)
    self
  end
alias_info(slave, cmd_name)

[Source]

# File tk/lib/multi-tk.rb, line 2267
  def self.alias_info(slave, cmd_name)
    __getip.alias_info(slave, cmd_name)
  end
alias_target(aliascmd, slave = '')

[Source]

# File tk/lib/multi-tk.rb, line 2486
  def self.alias_target(aliascmd, slave = '')
    __getip.alias_target(aliascmd, slave)
  end
aliases(slave = '')

[Source]

# File tk/lib/multi-tk.rb, line 2293
  def self.aliases(slave = '')
    __getip.aliases(slave)
  end
alive?()

[Source]

# File tk/lib/multi-tk.rb, line 1241
  def self.alive?
    __getip.alive?
  end
allow_ruby_exit=(mode)

[Source]

# File tk/lib/multi-tk.rb, line 1682
  def allow_ruby_exit= (mode)
    __getip.allow_ruby_exit = mode
  end
allow_ruby_exit?()

[Source]

# File tk/lib/multi-tk.rb, line 1678
  def allow_ruby_exit?
    __getip.allow_ruby_exit?
  end
assign_receiver_and_watchdog(target)

[Source]

# File tk/lib/multi-tk.rb, line 650
    def self.assign_receiver_and_watchdog(target)
      ret = [nil]
      @assign_thread.raise(@assign_request.new(target, ret))
      while ret[0] == nil
        unless @assign_thread.alive?
          raise RuntimeError, 'lost the thread to assign a receiver and a watchdog thread'
        end
      end
      if ret[0].kind_of?(Exception)
        raise ret[0]
      else
        ret[0]
      end
    end
bgerror(cmd = Proc.new, slave = nil, &b)

[Source]

# File tk/lib/multi-tk.rb, line 2434
  def self.bgerror(cmd = Proc.new, slave = nil, &b)
    __getip.bgerror(cmd, slave, &b)
  end
bgerror(slave = '')

[Source]

# File tk/lib/multi-tk.rb, line 2441
  def self.bgerror(slave = '')
    __getip.bgerror(slave)
  end
cb_entry_class()

[Source]

# File tk/lib/multi-tk.rb, line 1380
  def self.cb_entry_class
    @@CB_ENTRY_CLASS
  end
create_table()

[Source]

# File tk/lib/multi-tk.rb, line 1340
  def self.create_table
    #if __getip.slave?
    #  raise SecurityError, "slave-IP has no permission creating a new table"
    #end
    id = @@TK_TABLE_LIST.size
    obj = Object.new
    @@TK_TABLE_LIST << obj
    obj.instance_eval "def self.method_missing(m, *args)\nMultiTkIp.tk_object_table(\#{id}).__send__(m, *args)\nend\n"
    obj.freeze
    @@IP_TABLE.each{|tg, ip| ip._add_new_tables }
    return obj
  end
def_alias(slave, new_cmd, org_cmd, *args)

[Source]

# File tk/lib/multi-tk.rb, line 2285
  def self.def_alias(slave, new_cmd, org_cmd, *args)
    ret = __getip.def_alias(slave, new_cmd, org_cmd, *args)
    (ret == new_cmd)? self: nil
  end
delete()

[Source]

# File tk/lib/multi-tk.rb, line 1686
  def delete
    __getip.delete
  end
delete_cmd(slave, cmd)

[Source]

# File tk/lib/multi-tk.rb, line 2320
  def self.delete_cmd(slave, cmd)
    __getip.delete_cmd(slave, cmd)
    self
  end
delete_slaves(*args)

[Source]

# File tk/lib/multi-tk.rb, line 2302
  def self.delete_slaves(*args)
    __getip.delete_slaves(*args)
    self
  end
deleted?()

[Source]

# File tk/lib/multi-tk.rb, line 1690
  def deleted?
    __getip.deleted?
  end
do_one_event(flag = TclTkLib::EventFlag::ALL)

[Source]

# File tk/lib/multi-tk.rb, line 1625
  def do_one_event(flag = TclTkLib::EventFlag::ALL)
    __getip.do_one_event(flag)
  end
eval_proc(*args, &blk)

class method

[Source]

# File tk/lib/multi-tk.rb, line 1607
  def eval_proc(*args, &blk)
    # class ==> interp object
    __getip.eval_proc(*args, &blk)
  end
exist?(slave = '')

[Source]

# File tk/lib/multi-tk.rb, line 2311
  def self.exist?(slave = '')
    __getip.exist?(slave)
  end
exit(st = true)

[Source]

# File tk/lib/multi-tk.rb, line 1706
  def exit(st = true)
    __getip.exit(st)
  end
exit!(st = false)

[Source]

# File tk/lib/multi-tk.rb, line 1710
  def exit!(st = false)
    __getip.exit!(st)
  end
expose_cmd(slave, cmd, aliasname = nil)

[Source]

# File tk/lib/multi-tk.rb, line 2333
  def self.expose_cmd(slave, cmd, aliasname = nil)
    __getip.expose_cmd(slave, cmd, aliasname)
    self
  end
get_cb_entry(cmd)

[Source]

# File tk/lib/multi-tk.rb, line 1383
  def self.get_cb_entry(cmd)
    @@CB_ENTRY_CLASS.new(__getip, cmd).freeze
  end
get_eventloop_tick()

[Source]

# File tk/lib/multi-tk.rb, line 1639
  def get_eventloop_tick
    __getip.get_eventloop_tick
  end
get_eventloop_weight()

[Source]

# File tk/lib/multi-tk.rb, line 1651
  def get_eventloop_weight
    __getip.get_eventloop_weight
  end
get_limit(limit_type, slave = '', slot = nil)

[Source]

# File tk/lib/multi-tk.rb, line 2471
  def self.get_limit(limit_type, slave = '', slot = nil)
    __getip.get_limit(limit_type, slave, slot)
  end
get_no_event_wait()

[Source]

# File tk/lib/multi-tk.rb, line 1645
  def get_no_event_wait
    __getip.get_no_event_wait
  end
has_mainwindow?()

[Source]

# File tk/lib/multi-tk.rb, line 1694
  def has_mainwindow?
    __getip.has_mainwindow?
  end
hidden_cmds(slave = '')

[Source]

# File tk/lib/multi-tk.rb, line 2354
  def self.hidden_cmds(slave = '')
    __getip.hidden_cmds(slave)
  end
hide_cmd(slave, cmd, aliasname = nil)

[Source]

# File tk/lib/multi-tk.rb, line 2346
  def self.hide_cmd(slave, cmd, aliasname = nil)
    __getip.hide_cmd(slave, cmd, aliasname)
    self
  end
inherited(subclass)

[Source]

# File tk/lib/multi-tk.rb, line 675
  def self.inherited(subclass)
    # trust if on ThreadGroup::Default or @@DEFAULT_MASTER's ThreadGroup
    if @@IP_TABLE[Thread.current.group] == @@DEFAULT_MASTER
      begin
        class << subclass
          self.methods.each{|m|
            begin
              unless m == '__id__' || m == '__send__' || m == 'freeze'
                undef_method(m)
              end
            rescue Exception
              # ignore all exceptions
            end
          }
        end
      ensure
        subclass.freeze
        fail SecurityError,
          "cannot create subclass of MultiTkIp on a untrusted ThreadGroup"
      end
    end
  end
init_ip_env(script = Proc.new)

[Source]

# File tk/lib/multi-tk.rb, line 1358
  def self.init_ip_env(script = Proc.new)
    @@INIT_IP_ENV << script
    @@IP_TABLE.each{|tg, ip|
      ip._init_ip_env(script)
    }
  end
init_ip_internal()

[Source]

# File tk/lib/multi-tk.rb, line 1372
  def self.init_ip_internal
    __getip._init_ip_internal(@@INIT_IP_ENV, @@ADD_TK_PROCS)
  end
invalid_namespace?()

[Source]

# File tk/lib/multi-tk.rb, line 1698
  def invalid_namespace?
    __getip.invalid_namespace?
  end
invoke_hidden(slave, cmd, *args)

[Source]

# File tk/lib/multi-tk.rb, line 2373
  def self.invoke_hidden(slave, cmd, *args)
    __getip.invoke_hidden(slave, cmd, *args)
  end
invoke_hidden_on_global(slave, cmd, *args)

[Source]

# File tk/lib/multi-tk.rb, line 2393
  def self.invoke_hidden_on_global(slave, cmd, *args)
    __getip.invoke_hidden_on_global(slave, cmd, *args)
  end
invoke_hidden_on_namespace(slave, ns, cmd, *args)

[Source]

# File tk/lib/multi-tk.rb, line 2410
  def self.invoke_hidden_on_namespace(slave, ns, cmd, *args)
    __getip.invoke_hidden_on_namespace(slave, ns, cmd, *args)
  end
ip_name()

[Source]

# File tk/lib/multi-tk.rb, line 1254
  def self.ip_name
    __getip.ip_name
  end
mainloop(check_root = true)

[Source]

# File tk/lib/multi-tk.rb, line 1619
  def mainloop(check_root = true)
    __getip.mainloop(check_root)
  end
mainloop_abort_on_exception()

[Source]

# File tk/lib/multi-tk.rb, line 1628
  def mainloop_abort_on_exception
    # __getip.mainloop_abort_on_exception
    TclTkLib.mainloop_abort_on_exception
  end
mainloop_abort_on_exception=(mode)

[Source]

# File tk/lib/multi-tk.rb, line 1632
  def mainloop_abort_on_exception=(mode)
    # __getip.mainloop_abort_on_exception=(mode)
    TclTkLib.mainloop_abort_on_exception=(mode)
  end
mainloop_watchdog(check_root = true)

[Source]

# File tk/lib/multi-tk.rb, line 1622
  def mainloop_watchdog(check_root = true)
    __getip.mainloop_watchdog(check_root)
  end
make_safe()

[Source]

# File tk/lib/multi-tk.rb, line 1662
  def make_safe
    __getip.make_safe
  end
mark_trusted(slave = '')

[Source]

# File tk/lib/multi-tk.rb, line 2418
  def self.mark_trusted(slave = '')
    __getip.mark_trusted(slave)
    self
  end
master?()

[Source]

# File tk/lib/multi-tk.rb, line 1220
  def self.master?
    __getip.master?
  end
method_missing(id, *args)

[Source]

# File tk/lib/multi-tk.rb, line 1658
  def method_missing(id, *args)
    __getip.__send__(id, *args)
  end
new(target, ret)

[Source]

# File tk/lib/multi-tk.rb, line 614
      def self.new(target, ret)
        obj = super()
        obj.target = target
        obj.ret = ret
        obj
      end
new(master, safeip=true, keys={})

[Source]

# File tk/lib/multi-tk.rb, line 938
  def initialize(master, safeip=true, keys={})
    if $SAFE >= 4
      fail SecurityError, "cannot create a new interpreter at level #{$SAFE}"
    end

    if safeip == nil && $SAFE >= 2
      fail SecurityError, "cannot create a master-ip at level #{$SAFE}"
    end

    if master.deleted? && safeip == nil
      fail RuntimeError, "cannot create a slave of a deleted interpreter"
    end

    if !master.deleted? && !master.master? && master.safe?
      fail SecurityError, "safe-slave-ip cannot create a new interpreter"
    end

    if safeip == nil && !master.master?
      fail SecurityError, "slave-ip cannot create a master-ip"
    end

    unless keys.kind_of? Hash
      fail ArgumentError, "expecting a Hash object for the 2nd argument"
    end

    @tk_windows = {}
    @tk_table_list = []
    @slave_ip_tbl = {}
    @slave_ip_top = {}
    @cb_error_proc = []
    @evloop_thread = []

    @tk_windows.taint unless @tk_windows.tainted?
    @tk_table_list.taint unless @tk_table_list.tainted?
    @slave_ip_tbl.taint unless @slave_ip_tbl.tainted?
    @slave_ip_top.taint unless @slave_ip_top.tainted?
    @cb_error_proc.taint unless @cb_error_proc.tainted?
    @evloop_thread.taint unless @evloop_thread.tainted?

    name, safe, safe_opts, tk_opts = _parse_slaveopts(keys)

    safe = 4 if safe && !safe.kind_of?(Fixnum)

    @safe_base = false

    if safeip == nil
      # create master-ip
      @interp = TclTkIp.new(name, _keys2opts(tk_opts))

      @ip_name = nil
      if safe
        safe = $SAFE if safe < $SAFE
        @safe_level = [safe]
      else
        @safe_level = [$SAFE]
      end
    else
      # create slave-ip
      if safeip || master.safe?
        @safe_base = true
        @interp, @ip_name = master.__create_safe_slave_obj(safe_opts,
                                                           name, tk_opts)
        if safe
          safe = master.safe_level if safe < master.safe_level
          @safe_level = [safe]
        else
          @safe_level = [4]
        end
      else
        @interp, @ip_name = master.__create_trusted_slave_obj(name, tk_opts)
        if safe
          safe = master.safe_level if safe < master.safe_level
          @safe_level = [safe]
        else
          @safe_level = [master.safe_level]
        end
      end
      @set_alias_proc = proc{|name|
        master._invoke('interp', 'alias', @ip_name, name, '', name)
      }.freeze
    end

    @system = Object.new

    @wait_on_mainloop = [true, 0].taint
    # @wait_on_mainloop = [false, 0].taint

    @threadgroup  = ThreadGroup.new

    @cmd_queue = Queue.new

??
    @@DEFAULT_MASTER.assign_receiver_and_watchdog(self)

    @@IP_TABLE[@threadgroup] = self
    _init_ip_internal(@@INIT_IP_ENV, @@ADD_TK_PROCS)
    @@TK_TABLE_LIST.size.times{
      (tbl = {}).tainted? || tbl.taint
      @tk_table_list << tbl
    }

    class << self
      undef :instance_eval
    end

    # dummy call for initialization
    self.eval_proc{ Tk.tk_call('set', 'tcl_patchLevel') }

    self.freeze  # defend against modification
  end
new(ip, cmd)

[Source]

# File tk/lib/multi-tk.rb, line 71
    def initialize(ip, cmd)
      @ip = ip
      @cmd = cmd
      freeze
    end
new_master(safe=nil, keys={})

[Source]

# File tk/lib/multi-tk.rb, line 1121
  def new_master(safe=nil, keys={})
    if safe.kind_of?(Hash)
      keys = safe
    elsif safe.kind_of?(Integer)
      raise ArgumentError, "unexpected argument(s)" unless keys.kind_of?(Hash)
      if !keys.key?(:safe) && !keys.key?('safe')
        keys[:safe] = safe
      end
    elsif safe == nil
      # do nothing
    else
      raise ArgumentError, "unexpected argument(s)"
    end

    ip = __new(__getip, nil, keys)
    #ip.eval_proc(proc{$SAFE=ip.safe_level; Proc.new}.call) if block_given?
     if block_given?
       Thread.new{ip.eval_proc(proc{$SAFE=ip.safe_level; Proc.new}.call)}
     end
    ip
  end
new_safe_slave(safe=4, keys={})

[Source]

# File tk/lib/multi-tk.rb, line 1168
  def new_safe_slave(safe=4, keys={})
    if safe.kind_of?(Hash)
      keys = safe
    elsif safe.kind_of?(Integer)
      raise ArgumentError, "unexpected argument(s)" unless keys.kind_of?(Hash)
      if !keys.key?(:safe) && !keys.key?('safe')
        keys[:safe] = safe
      end
    else
      raise ArgumentError, "unexpected argument(s)"
    end

    ip = __new(__getip, true, keys)
    # ip.eval_proc(proc{$SAFE=ip.safe_level; Proc.new}.call) if block_given?
    if block_given?
      Thread.new{ip.eval_proc(proc{$SAFE=ip.safe_level; Proc.new}.call)}
    end
    ip
  end
new_slave(safe=nil, keys={})

[Source]

# File tk/lib/multi-tk.rb, line 1145
  def new_slave(safe=nil, keys={})
    if safe.kind_of?(Hash)
      keys = safe
    elsif safe.kind_of?(Integer)
      raise ArgumentError, "unexpected argument(s)" unless keys.kind_of?(Hash)
      if !keys.key?(:safe) && !keys.key?('safe')
        keys[:safe] = safe
      end
    elsif safe == nil
      # do nothing
    else
      raise ArgumentError, "unexpected argument(s)"
    end

    ip = __new(__getip, false, keys)
    # ip.eval_proc(proc{$SAFE=ip.safe_level; Proc.new}.call) if block_given?
    if block_given?
      Thread.new{ip.eval_proc(proc{$SAFE=ip.safe_level; Proc.new}.call)}
    end
    ip
  end
path()

[Source]

# File tk/lib/multi-tk.rb, line 1248
  def self.path
    __getip.path
  end
recursion_limit(slave = '', limit = None)

[Source]

# File tk/lib/multi-tk.rb, line 2479
  def self.recursion_limit(slave = '', limit = None)
    __getip.recursion_limit(slave)
  end
restart(app_name = nil, keys = {})

[Source]

# File tk/lib/multi-tk.rb, line 1714
  def restart(app_name = nil, keys = {})
    init_ip_internal

    __getip._invoke('set', 'argv0', app_name) if app_name
    if keys.kind_of?(Hash)
      __getip._invoke('set', 'argv', _keys2opts(keys))
    end

    __getip.restart
  end
safe?()

[Source]

# File tk/lib/multi-tk.rb, line 1666
  def safe?
    __getip.safe?
  end
safe_base?()

[Source]

# File tk/lib/multi-tk.rb, line 1670
  def safe_base?
    begin
      __getip.safe_base?
    rescue
      false
    end
  end
safe_level()

[Source]

# File tk/lib/multi-tk.rb, line 212
  def self.safe_level
    __getip.safe_level
  end
safe_level=(safe)

[Source]

# File tk/lib/multi-tk.rb, line 206
  def self.safe_level=(safe)
    self.set_safe_level(safe)
  end
set_eventloop_tick(tick)

[Source]

# File tk/lib/multi-tk.rb, line 1636
  def set_eventloop_tick(tick)
    __getip.set_eventloop_tick(tick)
  end
set_eventloop_weight(loop_max, no_event_tick)

[Source]

# File tk/lib/multi-tk.rb, line 1648
  def set_eventloop_weight(loop_max, no_event_tick)
    __getip.set_eventloop_weight(loop_max, no_event_tick)
  end
set_limit(limit_type, slave = '', opts = {})

[Source]

# File tk/lib/multi-tk.rb, line 2448
  def self.set_limit(limit_type, slave = '', opts = {})
    __getip.set_limit(limit_type, slave, opts)
  end
set_no_event_wait(tick)

[Source]

# File tk/lib/multi-tk.rb, line 1642
  def set_no_event_wait(tick)
    __getip.set_no_event_wait(tick)
  end
set_safe_level(safe)

[Source]

# File tk/lib/multi-tk.rb, line 203
  def self.set_safe_level(safe)
    __getip.set_safe_level(safe)
  end
share_stderr(dist, src = '')

[Source]

# File tk/lib/multi-tk.rb, line 2512
  def self.share_stderr(dist, src = '')
    __getip.share_stderr(dist, src)
    self
  end
share_stdin(dist, src = '')

[Source]

# File tk/lib/multi-tk.rb, line 2494
  def self.share_stdin(dist, src = '')
    __getip.share_stdin(dist, src)
    self
  end
share_stdio(dist, src = '')

[Source]

# File tk/lib/multi-tk.rb, line 2550
  def self.share_stdio(dist, src = '')
    __getip.share_stdio(dist, src)
    self
  end
share_stdout(dist, src = '')

[Source]

# File tk/lib/multi-tk.rb, line 2503
  def self.share_stdout(dist, src = '')
    __getip.share_stdout(dist, src)
    self
  end
slave?()

[Source]

# File tk/lib/multi-tk.rb, line 1227
  def self.slave?
    not self.master?
  end
slaves(all = false)

[Source]

# File tk/lib/multi-tk.rb, line 1275
  def self.slaves(all = false)
    __getip.slaves(all)
  end
tk_cmd_tbl()

[Source]

# File tk/lib/multi-tk.rb, line 1331
  def self.tk_cmd_tbl
    @@TK_CMD_TBL
  end
tk_object_table(id)

[Source]

# File tk/lib/multi-tk.rb, line 1337
  def self.tk_object_table(id)
    __getip._tk_table_list[id]
  end
tk_windows()

[Source]

# File tk/lib/multi-tk.rb, line 1334
  def self.tk_windows
    __getip._tk_windows
  end
to_eval()

[Source]

# File tk/lib/multi-tk.rb, line 1260
  def self.to_eval
    __getip.to_eval
  end
transfer_stderr(dist, src = '')

[Source]

# File tk/lib/multi-tk.rb, line 2539
  def self.transfer_stderr(dist, src = '')
    __getip.transfer_stderr(dist, src)
    self
  end
transfer_stdin(dist, src = '')

[Source]

# File tk/lib/multi-tk.rb, line 2521
  def self.transfer_stdin(dist, src = '')
    __getip.transfer_stdin(dist, src)
    self
  end
transfer_stdio(dist, src = '')

[Source]

# File tk/lib/multi-tk.rb, line 2561
  def self.transfer_stdio(dist, src = '')
    __getip.transfer_stdio(dist, src)
    self
  end
transfer_stdout(dist, src = '')

[Source]

# File tk/lib/multi-tk.rb, line 2530
  def self.transfer_stdout(dist, src = '')
    __getip.transfer_stdout(dist, src)
    self
  end

Public Instance methods

__create_safe_slave_obj(safe_opts, app_name, tk_opts)

[Source]

# File tk/lib/multi-tk.rb, line 878
  def __create_safe_slave_obj(safe_opts, app_name, tk_opts)
    # safe interpreter
    ip_name = _create_slave_ip_name
    slave_ip = @interp.create_slave(ip_name, true)
    @slave_ip_tbl[ip_name] = slave_ip
    def slave_ip.safe_base?
      true
    end

    @interp._eval("::safe::interpInit #{ip_name}")

    slave_ip._invoke('set', 'argv0', app_name) if app_name.kind_of?(String)

    if tk_opts
      tk_opts = __check_safetk_optkeys(tk_opts)
      if tk_opts.key?('use')
        @slave_ip_top[ip_name] = ''
      else
        tk_opts, top_path = __create_safetk_frame(slave_ip, ip_name, app_name,
                                                  tk_opts)
        @slave_ip_top[ip_name] = top_path
      end
      @interp._eval("::safe::loadTk #{ip_name} #{_keys2opts(tk_opts)}")
    else
      @slave_ip_top[ip_name] = nil
    end

    if safe_opts.key?('deleteHook') || safe_opts.key?(:deleteHook)
      @interp._eval("::safe::interpConfigure #{ip_name} " +
                    _keys2opts(safe_opts))
    else
      @interp._eval("::safe::interpConfigure #{ip_name} " +
                    _keys2opts(safe_opts) + '-deleteHook {' +
                    TkComm._get_eval_string(proc{|slave|
                                              self._default_delete_hook(slave)
                                            }) + '}')
    end

    [slave_ip, ip_name]
  end
__create_trusted_slave_obj(name, keys)

[Source]

# File tk/lib/multi-tk.rb, line 919
  def  __create_trusted_slave_obj__create_trusted_slave_obj(name, keys)
    ip_name = _create_slave_ip_name
    slave_ip = @interp.create_slave(ip_name, false)
    slave_ip._invoke('set', 'argv0', name) if name.kind_of?(String)
    slave_ip._invoke('set', 'argv', _keys2opts(keys))
    @interp._invoke('load', '', 'Tk', ip_name)
    @slave_ip_tbl[ip_name] = slave_ip
    [slave_ip, ip_name]
  end
__eval(str)

[Source]

# File tk/lib/multi-tk.rb, line 2118
  def __eval(str)
    @interp.__eval(str)
  end
__invoke(*args)

[Source]

# File tk/lib/multi-tk.rb, line 2122
  def __invoke(*args)
    @interp.__invoke(*args)
  end
_add_new_tables()

[Source]

# File tk/lib/multi-tk.rb, line 1297
  def _add_new_tables
    (@@TK_TABLE_LIST.size - @tk_table_list.size).times{
      (tbl = {}).tainted? || tbl.taint
      @tk_table_list << tbl
    }
  end
_add_tk_procs(name, args, body)

[Source]

# File tk/lib/multi-tk.rb, line 1308
  def _add_tk_procs(name, args, body)
    return if slave?
    @interp._invoke('proc', name, args, body) if args && body
    @interp._invoke('interp', 'slaves').split.each{|slave|
      @interp._invoke('interp', 'alias', slave, name, '', name)
    }
  end
_conv_listelement(arg)

[Source]

# File tk/lib/multi-tk.rb, line 2214
  def _conv_listelement(arg)
    @interp._conv_listelement(arg)
  end
_create_slave_object(keys={})

[Source]

# File tk/lib/multi-tk.rb, line 931
  def _create_slave_object(keys={})
    ip = MultiTkIp.new_slave(self, keys={})
    @slave_ip_tbl[ip.name] = ip
  end
_default_delete_hook(slave)

[Source]

# File tk/lib/multi-tk.rb, line 1058
  def _default_delete_hook(slave)
    @slave_ip_tbl.delete(slave)
    top = @slave_ip_top.delete(slave)
    if top.kind_of?(String)
      # call default hook of safetk.tcl (ignore exceptions)
      if top == ''
        begin
          @interp._eval("::safe::disallowTk #{slave}")
        rescue
          warn("Waring: fail to call '::safe::disallowTk'") if $DEBUG
        end
      else # toplevel path
        begin
          @interp._eval("::safe::tkDelete {} #{top} #{slave}")
        rescue
          warn("Waring: fail to call '::safe::tkDelete'") if $DEBUG
          begin
            @interp._eval("destroy #{top}")
          rescue
            warn("Waring: fail to destroy toplevel") if $DEBUG
          end
        end
      end
    end
  end
_destroy_slaves_of_slaveIP(ip)

[Source]

# File tk/lib/multi-tk.rb, line 227
  def _destroy_slaves_of_slaveIP(ip)
    unless ip.deleted?
      # ip._split_tklist(ip._invoke('interp', 'slaves')).each{|name|
      ip._split_tklist(ip._invoke_without_enc('interp', 'slaves')).each{|name|
        name = _fromUTF8(name)
        begin
          # ip._eval_without_enc("#{name} eval {foreach i [after info] {after cancel $i}}")
          after_ids = ip._eval_without_enc("#{name} eval {after info}")
          ip._eval_without_enc("#{name} eval {foreach i {#{after_ids}} {after cancel $i}}")
        rescue Exception
        end
        begin
          # ip._invoke('interp', 'eval', name, 'destroy', '.')
          ip._invoke(name, 'eval', 'destroy', '.')
        rescue Exception
        end

        # safe_base?
        if ip._eval_without_enc("catch {::safe::interpConfigure #{name}}") == '0'
          begin
            ip._eval_without_enc("::safe::interpDelete #{name}")
          rescue Exception
          end
        end
??
        unless ip.deleted?
          if ip._invoke('interp', 'exists', name) == '1'
            begin
              ip._invoke('interp', 'delete', name)
            rescue Exception
            end
          end
        end
      }
    end
  end
_eval(str)

[Source]

# File tk/lib/multi-tk.rb, line 2126
  def _eval(str)
    @interp._eval(str)
  end
_eval_with_enc(str)

[Source]

# File tk/lib/multi-tk.rb, line 2142
  def _eval_with_enc(str)
    @interp._eval_with_enc(str)
  end
_eval_without_enc(str)

[Source]

# File tk/lib/multi-tk.rb, line 2134
  def _eval_without_enc(str)
    @interp._eval_without_enc(str)
  end
_fromUTF8(str, encoding=nil)

[Source]

# File tk/lib/multi-tk.rb, line 2154
  def _fromUTF8(str, encoding=nil)
    @interp._fromUTF8(str, encoding)
  end
_get_global_var(var)

[Source]

# File tk/lib/multi-tk.rb, line 2189
  def _get_global_var(var)
    @interp._get_global_var(var)
  end
_get_global_var2(var, idx)

[Source]

# File tk/lib/multi-tk.rb, line 2192
  def _get_global_var2(var, idx)
    @interp._get_global_var2(var, idx)
  end
_get_variable(var, flag)

[Source]

# File tk/lib/multi-tk.rb, line 2170
  def _get_variable(var, flag)
    @interp._get_variable(var, flag)
  end
_get_variable2(var, idx, flag)

[Source]

# File tk/lib/multi-tk.rb, line 2173
  def _get_variable2(var, idx, flag)
    @interp._get_variable2(var, idx, flag)
  end
_init_ip_env(script)

[Source]

# File tk/lib/multi-tk.rb, line 1304
  def _init_ip_env(script)
    script.call(self)
  end
_init_ip_internal(init_ip_env, add_tk_procs)

[Source]

# File tk/lib/multi-tk.rb, line 1316
  def _init_ip_internal(init_ip_env, add_tk_procs)
    init_ip_env.each{|script| script.call(self)}
    add_tk_procs.each{|name, args, body|
      if master?
        @interp._invoke('proc', name, args, body) if args && body
      else
        @set_alias_proc.call(name)
      end
    }
  end
_invoke(*args)

[Source]

# File tk/lib/multi-tk.rb, line 2130
  def _invoke(*args)
    @interp._invoke(*args)
  end
_invoke_with_enc(*args)

[Source]

# File tk/lib/multi-tk.rb, line 2146
  def _invoke_with_enc(*args)
    @interp._invoke_with_enc(*args)
  end
_invoke_without_enc(*args)

[Source]

# File tk/lib/multi-tk.rb, line 2138
  def _invoke_without_enc(*args)
    @interp._invoke_without_enc(*args)
  end
_ip_id_()

[Source]

# File tk/lib/multi-tk.rb, line 1092
  def _ip_id_
    ''
  end
_merge_tklist(*args)

[Source]

# File tk/lib/multi-tk.rb, line 2211
  def _merge_tklist(*args)
    @interp._merge_tklist(*args)
  end
_receiver_mainloop(check_root)

[Source]

# File tk/lib/multi-tk.rb, line 473
  def _receiver_mainloop(check_root)
    if @evloop_thread[0] && @evloop_thread[0].alive?
      @evloop_thread[0]
    else
      @evloop_thread[0] = Thread.new{
        while !@interp.deleted?
          #if check_root
          #  inf = @interp._invoke_without_enc('info', 'command', '.')
          #  break if !inf.kind_of?(String) || inf != '.'
          #end
          break if check_root && !@interp.has_mainwindow?
          sleep 0.5
        end
      }
      @evloop_thread[0]
    end
  end
_return_value()

[Source]

# File tk/lib/multi-tk.rb, line 2166
  def _return_value
    @interp._return_value
  end
_set_global_var(var, value)

[Source]

# File tk/lib/multi-tk.rb, line 2195
  def _set_global_var(var, value)
    @interp._set_global_var(var, value)
  end
_set_global_var2(var, idx, value)

[Source]

# File tk/lib/multi-tk.rb, line 2198
  def _set_global_var2(var, idx, value)
    @interp._set_global_var2(var, idx, value)
  end
_set_variable(var, value, flag)

[Source]

# File tk/lib/multi-tk.rb, line 2176
  def _set_variable(var, value, flag)
    @interp._set_variable(var, value, flag)
  end
_set_variable2(var, idx, value, flag)

[Source]

# File tk/lib/multi-tk.rb, line 2179
  def _set_variable2(var, idx, value, flag)
    @interp._set_variable2(var, idx, value, flag)
  end
_split_tklist(str)

[Source]

# File tk/lib/multi-tk.rb, line 2208
  def _split_tklist(str)
    @interp._split_tklist(str)
  end
_thread_tkwait(mode, target)

[Source]

# File tk/lib/multi-tk.rb, line 2162
  def _thread_tkwait(mode, target)
    @interp._thread_tkwait(mode, target)
  end
_thread_vwait(var)

[Source]

# File tk/lib/multi-tk.rb, line 2158
  def _thread_vwait(var)
    @interp._thread_vwait(var)
  end
_tk_cmd_tbl()

[Source]

# File tk/lib/multi-tk.rb, line 1283
  def _tk_cmd_tbl
    tbl = {}
    MultiTkIp.tk_cmd_tbl.each{|id, ent| tbl[id] = ent if ent.ip == self }
    tbl
  end
_tk_table_list()

[Source]

# File tk/lib/multi-tk.rb, line 1293
  def _tk_table_list
    @tk_table_list
  end
_tk_windows()

[Source]

# File tk/lib/multi-tk.rb, line 1289
  def _tk_windows
    @tk_windows
  end
_toUTF8(str, encoding=nil)

[Source]

# File tk/lib/multi-tk.rb, line 2150
  def _toUTF8(str, encoding=nil)
    @interp._toUTF8(str, encoding)
  end
_unset_global_var(var)

[Source]

# File tk/lib/multi-tk.rb, line 2201
  def _unset_global_var(var)
    @interp._unset_global_var(var)
  end
_unset_global_var2(var, idx)

[Source]

# File tk/lib/multi-tk.rb, line 2204
  def _unset_global_var2(var, idx)
    @interp._unset_global_var2(var, idx)
  end
_unset_variable(var, flag)

[Source]

# File tk/lib/multi-tk.rb, line 2182
  def _unset_variable(var, flag)
    @interp._unset_variable(var, flag)
  end
_unset_variable2(var, idx, flag)

[Source]

# File tk/lib/multi-tk.rb, line 2185
  def _unset_variable2(var, idx, flag)
    @interp._unset_variable2(var, idx, flag)
  end
abort(msg = nil)

[Source]

# File tk/lib/multi-tk.rb, line 2075
  def abort(msg = nil)
    if master?
      if msg
        Kernel.abort(msg)
      else
        Kernel.abort
      end
    else
      # ignore msg
      delete
      1
    end
  end
alias_delete(slave, cmd_name)

[Source]

# File tk/lib/multi-tk.rb, line 2271
  def alias_delete(slave, cmd_name)
    @interp._invoke('interp', 'alias', _slavearg(slave), cmd_name, '')
    self
  end
alias_info(slave, cmd_name)

[Source]

# File tk/lib/multi-tk.rb, line 2264
  def alias_info(slave, cmd_name)
    _lst2ary(@interp._invoke('interp', 'alias', _slavearg(slave), cmd_name))
  end
alias_target(aliascmd, slave = '')

[Source]

# File tk/lib/multi-tk.rb, line 2483
  def alias_target(aliascmd, slave = '')
    @interp._invoke('interp', 'target', _slavearg(slave), aliascmd)
  end
aliases(slave = '')

[Source]

# File tk/lib/multi-tk.rb, line 2290
  def aliases(slave = '')
    _lst2ary(@interp._invoke('interp', 'aliases', _slavearg(slave)))
  end
alive?()

[Source]

# File tk/lib/multi-tk.rb, line 1231
  def alive?
    begin
      return false unless @cmd_receiver.alive?
      return false if @interp.deleted?
      return false if @interp._invoke('interp', 'exists', '') == '0'
    rescue Exception
      return false
    end
    true
  end
allow_ruby_exit=(mode)

[Source]

# File tk/lib/multi-tk.rb, line 1997
  def allow_ruby_exit= (mode)
    @interp.allow_ruby_exit = mode
  end
allow_ruby_exit?()

[Source]

# File tk/lib/multi-tk.rb, line 1993
  def allow_ruby_exit?
    @interp.allow_ruby_exit?
  end
background_call(*args)

Alias for bg_eval_proc

background_eval_proc(*args)

Alias for bg_eval_proc

background_eval_str(cmd, *eval_args)

Alias for bg_eval_string

background_eval_string(cmd, *eval_args)

Alias for bg_eval_string

bg_call(*args)

Alias for bg_eval_proc

bg_eval_proc(*args)

[Source]

# File tk/lib/multi-tk.rb, line 1548
  def bg_eval_proc(*args)
    if block_given?
      cmd = Proc.new
    else
      unless (cmd = args.shift)
        fail ArgumentError, "A Proc or Method object is expected for 1st argument"
      end
    end
    Thread.new{
      eval_proc(cmd, *args)
??
    }
  end
bg_eval_str(cmd, *eval_args)

Alias for bg_eval_string

bg_eval_string(cmd, *eval_args)

[Source]

# File tk/lib/multi-tk.rb, line 1587
  def bg_eval_string(cmd, *eval_args)
    # cmd string ==> proc
    unless cmd.kind_of?(String)
      raise RuntimeError, "A String object is expected for the 'cmd' argument"
    end
    Thread.new{
      eval_proc_core(true,
                     proc{|safe|
                       Kernel.eval("$SAFE=#{safe} if $SAFE < #{safe};" << cmd,
                                   *eval_args)
                     })
    }
  end
call(*args)

Alias for eval_proc

call(*args)

[Source]

# File tk/lib/multi-tk.rb, line 80
    def call(*args)
      unless @ip.deleted?
        current = Thread.current
        backup_ip = current['callback_ip']
        current['callback_ip'] = @ip
        begin
          @ip.cb_eval(@cmd, *args)
        rescue TkCallbackBreak, TkCallbackContinue => e
          fail e
        rescue SecurityError => e
          # in 'exit', 'exit!', and 'abort' : security error --> delete IP
          if e.backtrace[0] =~ /^(.+?):(\d+):in `(exit|exit!|abort)'/
            @ip.delete
          elsif @ip.safe?
            if @ip.respond_to?(:cb_error)
              @ip.cb_error(e)
            else
              nil # ignore
            end
          else
            fail e
          end
        rescue Exception => e
          if @ip.safe?
            if @ip.respond_to?(:cb_error)
              @ip.cb_error(e)
            else
              nil # ignore
            end
          else
            fail e
          end
        ensure
          current['callback_ip'] = backup_ip
        end
      end
    end
call(*args)

Alias for eval_proc

cb_error(e)

[Source]

# File tk/lib/multi-tk.rb, line 185
  def cb_error(e)
    if @cb_error_proc[0].respond_to?(:call)
      @cb_error_proc[0].call(e)
    end
  end
cb_eval(cmd, *args)

[Source]

# File tk/lib/multi-tk.rb, line 1387
  def cb_eval(cmd, *args)
    #self.eval_callback{ TkComm._get_eval_string(TkUtil.eval_cmd(cmd, *args)) }
    #ret = self.eval_callback{ TkComm._get_eval_string(TkUtil.eval_cmd(cmd, *args)) }
    ret = self.eval_callback(*args){|safe, *params|
      $SAFE=safe if $SAFE < safe
      TkComm._get_eval_string(TkUtil.eval_cmd(cmd, *params))
    }
    if ret.kind_of?(Exception)
      raise ret
    end
    ret
  end
def_alias(slave, new_cmd, org_cmd, *args)

[Source]

# File tk/lib/multi-tk.rb, line 2280
  def def_alias(slave, new_cmd, org_cmd, *args)
    ret = @interp._invoke('interp', 'alias', _slavearg(slave), new_cmd,
                          '', org_cmd, *args)
    (ret == new_cmd)? self: nil
  end
delete()

[Source]

# File tk/lib/multi-tk.rb, line 2001
  def delete
    @slave_ip_tbl.each{|name, subip|
      _destroy_slaves_of_slaveIP(subip)
??
      begin
        # subip._eval_without_enc("foreach i [after info] {after cancel $i}")
        unless subip.deleted?
          after_ids = subip._eval_without_enc("after info")
          subip._eval_without_enc("foreach i {#{after_ids}} {after cancel $i}")
        end
      rescue Exception
      end

      # safe_base?
      if @interp._eval_without_enc("catch {::safe::interpConfigure #{name}}") == '0'
        begin
          @interp._eval_without_enc("::safe::interpDelete #{name}")
        rescue Exception
        else
          next if subip.deleted?
        end
      end
      if subip.respond_to?(:safe_base?) && subip.safe_base? &&
          !subip.deleted?
        # do 'exit' to call the delete_hook procedure
        begin
          subip._eval_without_enc('exit')
        rescue Exception
        end
      else
        begin
          subip.delete unless subip.deleted?
        rescue Exception
        end
      end
    }

    begin
      # @interp._eval_without_enc("foreach i [after info] {after cancel $i}")
      after_ids = @interp._eval_without_enc("after info")
      @interp._eval_without_enc("foreach i {#{after_ids}} {after cancel $i}")
    rescue Exception
    end

    begin
      @interp._invoke('destroy', '.') unless @interp.deleted?
    rescue Exception
    end

    if @safe_base && !@interp.deleted?
      # do 'exit' to call the delete_hook procedure
      @interp._eval_without_enc('exit')
    end
    @interp.delete
    self
  end
delete_cmd(slave, cmd)

[Source]

# File tk/lib/multi-tk.rb, line 2315
  def delete_cmd(slave, cmd)
    slave_invoke = @interp._invoke('list', 'rename', cmd, '')
    @interp._invoke('interp', 'eval', _slavearg(slave), slave_invoke)
    self
  end
delete_slaves(*args)

[Source]

# File tk/lib/multi-tk.rb, line 2297
  def delete_slaves(*args)
    slaves = args.collect{|s| _slavearg(s)}
    @interp._invoke('interp', 'delete', *slaves) if slaves.size > 0
    self
  end
deleted?()

[Source]

# File tk/lib/multi-tk.rb, line 2063
  def deleted?
    @interp.deleted?
  end
encoding()

[Source]

# File tk/lib/multi-tk.rb, line 2639
  def encoding
    @interp.encoding
  end
encoding=(enc)

[Source]

# File tk/lib/multi-tk.rb, line 2642
  def encoding=(enc)
    @interp.encoding = enc
  end
encoding_convert_from(str, enc=None)

Alias for encoding_convertfrom

encoding_convert_to(str, enc=None)

Alias for encoding_convertto

encoding_convertfrom(str, enc=None)

[Source]

# File tk/lib/multi-tk.rb, line 2646
  def encoding_convertfrom(str, enc=None)
    @interp.encoding_convertfrom(str, enc)
  end
encoding_convertto(str, enc=None)

[Source]

# File tk/lib/multi-tk.rb, line 2651
  def encoding_convertto(str, enc=None)
    @interp.encoding_convertto(str, enc)
  end
eval_callback(*args)

[Source]

# File tk/lib/multi-tk.rb, line 1496
  def eval_callback(*args)
    if block_given?
      cmd = Proc.new
    else
      cmd = args.shift
    end
    current = Thread.current
    backup_ip = current['callback_ip']
    current['callback_ip'] = self
    begin
      eval_proc_core(false, cmd, *args)
    ensure
      current['callback_ip'] = backup_ip
    end
  end
eval_proc(*args)

[Source]

# File tk/lib/multi-tk.rb, line 1512
  def eval_proc(*args)
    # The scope of the eval-block of 'eval_proc' method is different from
    # the external. If you want to pass local values to the eval-block,
    # use arguments of eval_proc method. They are passed to block-arguments.
    if block_given?
      cmd = Proc.new
    else
      unless (cmd = args.shift)
        fail ArgumentError, "A Proc or Method object is expected for 1st argument"
      end
    end
    if TclTkLib.mainloop_thread? == true
      # call from eventloop
      current = Thread.current
      backup_ip = current['callback_ip']
      current['callback_ip'] = self
      begin
        eval_proc_core(false,
                       proc{|safe, *params|
                         $SAFE=safe if $SAFE < safe
                         cmd.call(*params)
                       }, *args)
      ensure
        current['callback_ip'] = backup_ip
      end
    else
      eval_proc_core(true,
                     proc{|safe, *params|
                       $SAFE=safe if $SAFE < safe
                       Thread.new(*params, &cmd).value
                     },
                     *args)
    end
  end
eval_str(cmd, *eval_args)

Alias for eval_string

eval_string(cmd, *eval_args)

[Source]

# File tk/lib/multi-tk.rb, line 1573
  def eval_string(cmd, *eval_args)
    # cmd string ==> proc
    unless cmd.kind_of?(String)
      raise RuntimeError, "A String object is expected for the 'cmd' argument"
    end

    eval_proc_core(true,
                   proc{|safe|
                     Kernel.eval("$SAFE=#{safe} if $SAFE < #{safe};" << cmd,
                                 *eval_args)
                   })
  end
eval_string(*args)

Alias for eval_proc

exist?(slave = '')

[Source]

# File tk/lib/multi-tk.rb, line 2307
  def exist?(slave = '')
    ret = @interp._invoke('interp', 'exists', _slavearg(slave))
    (ret == '1')? true: false
  end
exit(st = true)

[Source]

# File tk/lib/multi-tk.rb, line 2089
  def exit(st = true)
    if master?
      Kernel.exit(st)
    else
      delete
      st
    end
  end
exit!(st = false)

[Source]

# File tk/lib/multi-tk.rb, line 2098
  def exit!(st = false)
    if master? && !safe? && allow_ruby_exit?
      Kernel.exit!(st)
    else
      delete
      st
    end
  end
expose_cmd(slave, cmd, aliasname = nil)

[Source]

# File tk/lib/multi-tk.rb, line 2325
  def expose_cmd(slave, cmd, aliasname = nil)
    if aliasname
      @interp._invoke('interp', 'expose', _slavearg(slave), cmd, aliasname)
    else
      @interp._invoke('interp', 'expose', _slavearg(slave), cmd)
    end
    self
  end
get_bgerror_handler(slave = '')

[Source]

# File tk/lib/multi-tk.rb, line 2438
  def get_bgerror_handler(slave = '')
    procedure(@interp._invoke('interp', 'bgerror', _slavearg(slave)))
  end
get_limit(limit_type, slave = '', slot = nil)

[Source]

# File tk/lib/multi-tk.rb, line 2452
  def get_limit(limit_type, slave = '', slot = nil)
    if slot
      num_or_str(@interp._invoke('interp', 'limit', _slavearg(slave),
                                 limit_type, slot))
    else
      l = @interp._split_tklist(@interp._invoke_without_enc('interp', 'limit',
                                                            _slavearg(slave),
                                                            limit_type))
      l.map!{|s| _fromUTF8(s)}
      r = {}
      until l.empty?
        key = l.shift[1..-1]
        val = l.shift
        val = num_or_str(val) if val
        r[key] = val
      end
      r
    end
  end
has_mainwindow?()

[Source]

# File tk/lib/multi-tk.rb, line 2067
  def has_mainwindow?
    @interp.has_mainwindow?
  end
hidden_cmds(slave = '')

[Source]

# File tk/lib/multi-tk.rb, line 2351
  def hidden_cmds(slave = '')
    _lst2ary(@interp._invoke('interp', 'hidden', _slavearg(slave)))
  end
hide_cmd(slave, cmd, aliasname = nil)

[Source]

# File tk/lib/multi-tk.rb, line 2338
  def hide_cmd(slave, cmd, aliasname = nil)
    if aliasname
      @interp._invoke('interp', 'hide', _slavearg(slave), cmd, aliasname)
    else
      @interp._invoke('interp', 'hide', _slavearg(slave), cmd)
    end
    self
  end
inspect()

[Source]

# File tk/lib/multi-tk.rb, line 1193
  def inspect
    s = self.to_s.chop!
    if master?
      if @interp.deleted?
        s << ':deleted-master'
      else
        s << ':master'
      end
    else
      if @interp.deleted?
        s << ':deleted-slave'
      elsif @interp.safe?
        s << ':safe-slave'
      else
        s << ':trusted-slave'
      end
    end
    s << '>'
  end
inspect()

[Source]

# File tk/lib/multi-tk.rb, line 77
    def inspect
      cmd.inspect
    end
invalid_namespace?()

[Source]

# File tk/lib/multi-tk.rb, line 2071
  def invalid_namespace?
    @interp.invalid_namespace?
  end
invoke_hidden(slave, cmd, *args)

[Source]

# File tk/lib/multi-tk.rb, line 2358
  def invoke_hidden(slave, cmd, *args)
    if args[-1].kind_of?(Hash)
      keys = _symbolkey2str(args.pop)
    else
      keys = []
    end
    keys << _slavearg(slave)
    if Tk::TCL_MAJOR_VERSION > 8 ||
        (Tk::TCL_MAJOR_VERSION == 8 && Tk::TCL_MINOR_VERSION >= 5)
      keys << '--'
    end
    keys << cmd
    keys.concat(args)
    @interp._invoke('interp', 'invokehidden', *keys)
  end
invoke_hidden_on_global(slave, cmd, *args)

[Source]

# File tk/lib/multi-tk.rb, line 2377
  def invoke_hidden_on_global(slave, cmd, *args)
    if args[-1].kind_of?(Hash)
      keys = _symbolkey2str(args.pop)
    else
      keys = []
    end
    keys << _slavearg(slave)
    keys << '-global'
    if Tk::TCL_MAJOR_VERSION > 8 ||
        (Tk::TCL_MAJOR_VERSION == 8 && Tk::TCL_MINOR_VERSION >= 5)
      keys << '--'
    end
    keys << cmd
    keys.concat(args)
    @interp._invoke('interp', 'invokehidden', *keys)
  end
invoke_hidden_on_namespace(slave, ns, cmd, *args)

[Source]

# File tk/lib/multi-tk.rb, line 2397
  def invoke_hidden_on_namespace(slave, ns, cmd, *args)
    # for Tcl8.5 or later
    if args[-1].kind_of?(Hash)
      keys = _symbolkey2str(args.pop)
    else
      keys = []
    end
    keys << _slavearg(slave)
    keys << '-namespace' << TkComm._get_eval_string(ns)
    keys << '--' << cmd
    keys.concat(args)
    @interp._invoke('interp', 'invokehidden', *keys)
  end
ip_name()

[Source]

# File tk/lib/multi-tk.rb, line 1251
  def ip_name
    @ip_name || ''
  end
mainloop(check_root = true, restart_on_dead = true)

[Source]

# File tk/lib/multi-tk.rb, line 1873
  def mainloop(check_root = true, restart_on_dead = true)
    #return self if self.slave?
    #return self if self != @@DEFAULT_MASTER
    if self != @@DEFAULT_MASTER
      if @wait_on_mainloop[0]
        begin
          @wait_on_mainloop[1] += 1
          if $SAFE >= 4
            _receiver_mainloop(check_root).join
          else
            @cmd_queue.enq([@system, 'call_mainloop',
                            Thread.current, check_root])
            Thread.stop
          end
        rescue MultiTkIp_OK => ret
          # return value
          if ret.value.kind_of?(Thread)
            return ret.value.value
          else
            return ret.value
          end
        rescue SystemExit => e
          # exit IP
          warn("Warning: " + $! + " on " + self.inspect) if $DEBUG
          begin
            self._eval_without_enc('exit')
          rescue Exception
          end
          self.delete
        rescue StandardError => e
          if $DEBUG
            warn("Warning: " + e.class.inspect +
                 ((e.message.length > 0)? ' "' + e.message + '"': '') +
                 " on " + self.inspect)
          end
          return e
        rescue Exception => e
          return e
        ensure
          @wait_on_mainloop[1] -= 1
        end
      end
      return
    end

    unless restart_on_dead
      @wait_on_mainloop[1] += 1
??
      begin
        @interp.mainloop(check_root)
      ensure
        @wait_on_mainloop[1] -= 1
      end
    else
      loop do
        break unless self.alive?
        if check_root
          begin
            break if TclTkLib.num_of_mainwindows == 0
          rescue StandardError
            break
          end
        end
        break if @interp.deleted?
        begin
          @wait_on_mainloop[1] += 1
          @interp.mainloop(check_root)
        rescue StandardError => e
          if TclTkLib.mainloop_abort_on_exception != nil
            #STDERR.print("Warning: Tk mainloop receives ", $!.class.inspect,
            #             " exception (ignore) : ", $!.message, "\n");
            if $DEBUG
              warn("Warning: Tk mainloop receives " << e.class.inspect <<
                   " exception (ignore) : " << e.message);
            end
          end
          #raise e
        rescue Exception => e
??
          raise e
        ensure
          @wait_on_mainloop[1] -= 1
          Thread.pass  # avoid eventloop conflict
        end
      end
    end
    self
  end
make_safe()

[Source]

# File tk/lib/multi-tk.rb, line 1981
  def make_safe
    @interp.make_safe
  end
mark_trusted(slave = '')

[Source]

# File tk/lib/multi-tk.rb, line 2414
  def mark_trusted(slave = '')
    @interp._invoke('interp', 'marktrusted', _slavearg(slave))
    self
  end
master?()

[Source]

# File tk/lib/multi-tk.rb, line 1213
  def master?
    if @ip_name
      false
    else
      true
    end
  end
path()

[Source]

# File tk/lib/multi-tk.rb, line 1245
  def path
    @ip_name || ''
  end
recursion_limit(slave = '', limit = None)

[Source]

# File tk/lib/multi-tk.rb, line 2475
  def recursion_limit(slave = '', limit = None)
    number(@interp._invoke('interp', 'recursionlimit',
                           _slavearg(slave), limit))
  end
restart(app_name = nil, keys = {})

[Source]

# File tk/lib/multi-tk.rb, line 2107
  def restart(app_name = nil, keys = {})
    _init_ip_internal(@@INIT_IP_ENV, @@ADD_TK_PROCS)

    @interp._invoke('set', 'argv0', app_name) if app_name
    if keys.kind_of?(Hash)
      @interp._invoke('set', 'argv', _keys2opts(keys))
    end

    @interp.restart
  end
running_mainloop?()

[Source]

# File tk/lib/multi-tk.rb, line 223
  def running_mainloop?
    @wait_on_mainloop[1] > 0
  end
safe?()

[Source]

# File tk/lib/multi-tk.rb, line 1985
  def safe?
    @interp.safe?
  end
safe_base?()

[Source]

# File tk/lib/multi-tk.rb, line 1989
  def safe_base?
    @safe_base
  end
safe_level()

[Source]

# File tk/lib/multi-tk.rb, line 209
  def safe_level
    @safe_level[0]
  end
safe_level=(safe)

[Source]

# File tk/lib/multi-tk.rb, line 200
  def safe_level=(safe)
    set_safe_level(safe)
  end
safeip_add_to_access_path(dir)

[Source]

# File tk/lib/multi-tk.rb, line 2620
  def safeip_add_to_access_path(dir)
    ip = MultiTkIp.__getip
    ip._eval("::safe::interpAddToAccessPath #{@ip_name} #{dir}")
  end
safeip_configinfo(slot = nil)

[Source]

# File tk/lib/multi-tk.rb, line 2583
  def safeip_configinfo(slot = nil)
    ip = MultiTkIp.__getip
    ret = {}
    if slot
      conf = _lst2ary(ip._eval("::safe::interpConfigure " +
                               @ip_name + " -#{slot}"))
      if conf[0] == '-deleteHook'
        if conf[1] =~ /^rb_out\S* (c(_\d+_)?\d+)/
          ret[conf[0][1..-1]] = MultiTkIp._tk_cmd_tbl[$1]
        else
          ret[conf[0][1..-1]] = conf[1]
        end
      else
        ret[conf[0][1..-1]] = conf[1]
      end
    else
      Hash[*_lst2ary(ip._eval("::safe::interpConfigure " +
                              @ip_name))].each{|k, v|
        if k == '-deleteHook'
          if v =~ /^rb_out\S* (c(_\d+_)?\d+)/
            ret[k[1..-1]] = MultiTkIp._tk_cmd_tbl[$1]
          else
            ret[k[1..-1]] = v
          end
        else
          ret[k[1..-1]] = v
        end
      }
    end
    ret
  end
safeip_configure(slot, value=None)

[Source]

# File tk/lib/multi-tk.rb, line 2570
  def safeip_configure(slot, value=None)
    # use for '-noStatics' option ==> {statics=>false}
    #     for '-nestedLoadOk' option ==> {nested=>true}
    if slot.kind_of?(Hash)
      ip = MultiTkIp.__getip
      ip._eval('::safe::interpConfigure ' + @ip_name + ' ' + _keys2opts(slot))
    else
      ip._eval('::safe::interpConfigure ' + @ip_name + ' ' +
               "-#{slot} #{_get_eval_string(value)}")
    end
    self
  end
safeip_delete()

[Source]

# File tk/lib/multi-tk.rb, line 2615
  def safeip_delete
    ip = MultiTkIp.__getip
    ip._eval("::safe::interpDelete " + @ip_name)
  end
safeip_find_in_access_path(dir)

[Source]

# File tk/lib/multi-tk.rb, line 2625
  def safeip_find_in_access_path(dir)
    ip = MultiTkIp.__getip
    ip._eval("::safe::interpFindInAccessPath #{@ip_name} #{dir}")
  end
safeip_set_log_cmd(cmd = Proc.new)

[Source]

# File tk/lib/multi-tk.rb, line 2630
  def safeip_set_log_cmd(cmd = Proc.new)
    ip = MultiTkIp.__getip
    ip._eval("::safe::setLogCmd #{@ip_name} #{_get_eval_string(cmd)}")
  end
set_bgerror_handler(cmd = Proc.new, slave = nil, &b)

[Source]

# File tk/lib/multi-tk.rb, line 2423
  def set_bgerror_handler(cmd = Proc.new, slave = nil, &b)
    unless TkComm._callback_entry?(cmd)
      if !slave && b
        slave = cmd
        cmd = Proc.new(&b)
      end
    end
    slave = '' unless slave

    @interp._invoke('interp', 'bgerror', _slavearg(slave), cmd)
  end
set_cb_error(cmd = Proc.new)

[Source]

# File tk/lib/multi-tk.rb, line 181
  def set_cb_error(cmd = Proc.new)
    @cb_error_proc[0] = cmd
  end
set_limit(limit_type, slave = '', opts = {})

[Source]

# File tk/lib/multi-tk.rb, line 2445
  def set_limit(limit_type, slave = '', opts = {})
    @interp._invoke('interp', 'limit', _slavearg(slave), limit_type, opts)
  end
set_safe_level(safe)

[Source]

# File tk/lib/multi-tk.rb, line 193
  def set_safe_level(safe)
    if safe > @safe_level[0]
      @safe_level[0] = safe
      @cmd_queue.enq([@system, 'set_safe_level', safe])
    end
    @safe_level[0]
  end
share_stderr(dist, src = '')

[Source]

# File tk/lib/multi-tk.rb, line 2508
  def share_stderr(dist, src = '')
    @interp._invoke('interp', 'share', src, 'stderr', dist)
    self
  end
share_stdin(dist, src = '')

[Source]

# File tk/lib/multi-tk.rb, line 2490
  def share_stdin(dist, src = '')
    @interp._invoke('interp', 'share', src, 'stdin', dist)
    self
  end
share_stdio(dist, src = '')

[Source]

# File tk/lib/multi-tk.rb, line 2544
  def share_stdio(dist, src = '')
    @interp._invoke('interp', 'share', src, 'stdin',  dist)
    @interp._invoke('interp', 'share', src, 'stdout', dist)
    @interp._invoke('interp', 'share', src, 'stderr', dist)
    self
  end
share_stdout(dist, src = '')

[Source]

# File tk/lib/multi-tk.rb, line 2499
  def share_stdout(dist, src = '')
    @interp._invoke('interp', 'share', src, 'stdout', dist)
    self
  end
slave?()

[Source]

# File tk/lib/multi-tk.rb, line 1224
  def slave?
    not master?
  end
slaves(all = false)

[Source]

# File tk/lib/multi-tk.rb, line 1264
  def slaves(all = false)
    @interp._invoke('interp','slaves').split.map!{|name|
      if @slave_ip_tbl.key?(name)
        @slave_ip_tbl[name]
      elsif all
        name
      else
        nil
      end
    }.compact!
  end
thread_eval_proc(*args)

Alias for bg_eval_proc

to_eval()

[Source]

# File tk/lib/multi-tk.rb, line 1257
  def to_eval
    @ip_name || ''
  end
transfer_stderr(dist, src = '')

[Source]

# File tk/lib/multi-tk.rb, line 2535
  def transfer_stderr(dist, src = '')
    @interp._invoke('interp', 'transfer', src, 'stderr', dist)
    self
  end
transfer_stdin(dist, src = '')

[Source]

# File tk/lib/multi-tk.rb, line 2517
  def transfer_stdin(dist, src = '')
    @interp._invoke('interp', 'transfer', src, 'stdin', dist)
    self
  end
transfer_stdio(dist, src = '')

[Source]

# File tk/lib/multi-tk.rb, line 2555
  def transfer_stdio(dist, src = '')
    @interp._invoke('interp', 'transfer', src, 'stdin',  dist)
    @interp._invoke('interp', 'transfer', src, 'stdout', dist)
    @interp._invoke('interp', 'transfer', src, 'stderr', dist)
    self
  end
transfer_stdout(dist, src = '')

[Source]

# File tk/lib/multi-tk.rb, line 2526
  def transfer_stdout(dist, src = '')
    @interp._invoke('interp', 'transfer', src, 'stdout', dist)
    self
  end
wait_on_mainloop=(bool)

[Source]

# File tk/lib/multi-tk.rb, line 219
  def wait_on_mainloop=(bool)
    @wait_on_mainloop[0] = bool
  end
wait_on_mainloop?()

[Source]

# File tk/lib/multi-tk.rb, line 216
  def wait_on_mainloop?
    @wait_on_mainloop[0]
  end


Class: MultiTkIp_OK

Class | MultiTkIp_OK
In: | tk/lib/multi-tk.rb
Parent: | Exception

exceptiopn to treat the return value from IP

Methods

new send

External Aliases

return_value -> value

Attributes

return_value [R]

Public Class methods

new(ret=nil)

[Source]

# File tk/lib/multi-tk.rb, line 43
  def initialize(ret=nil)
    super('succeed')
    @return_value = ret
  end
send(thread, ret=nil)

[Source]

# File tk/lib/multi-tk.rb, line 39
  def self.send(thread, ret=nil)
    thread.raise self.new(ret)
  end


Class: RemoteTkIp

Class | RemoteTkIp
In: | tk/lib/remote-tk.rb
Parent: | MultiTkIp

Methods

__eval __invoke _conv_listelement _create_console _eval _eval_with_enc _eval_without_enc _fromUTF8 _get_global_var _get_global_var2 _get_variable _get_variable2 _invoke _invoke _invoke_with_enc _invoke_without_enc _ip_id_ _merge_tklist _return_value _set_global_var _set_global_var2 _set_variable _set_variable2 _split_tklist _thread_tkwait _thread_vwait _toUTF8 _unset_global_var _unset_global_var2 _unset_variable _unset_variable2 allow_ruby_exit= allow_ruby_exit? appsend create_slave delete deleted? do_one_evant do_one_evant get_eventloop_tick get_eventloop_tick get_eventloop_weight get_eventloop_weight get_no_event_wait get_no_event_wait has_mainwindow? invalid_namespace? is_rubytk? mainloop mainloop mainloop_abort_on_exception mainloop_abort_on_exception mainloop_abort_on_exception= mainloop_abort_on_exception= mainloop_watchdog mainloop_watchdog make_safe new new rb_appsend ready? restart safe? safe_base? set_eventloop_tick set_eventloop_tick set_eventloop_weight set_eventloop_weight set_no_event_wait set_no_event_wait

Public Class methods

do_one_evant(flag = nil)

[Source]

# File tk/lib/remote-tk.rb, line 463
  def do_one_evant(flag = nil)
    fail RuntimeError, 'not support "do_one_event" on the remote interpreter'
  end
get_eventloop_tick()

[Source]

# File tk/lib/remote-tk.rb, line 475
  def get_eventloop_tick
    fail RuntimeError, 'not support "get_eventloop_tick" on the remote interpreter'
  end
get_eventloop_weight()

[Source]

# File tk/lib/remote-tk.rb, line 487
  def get_eventloop_weight
    fail RuntimeError, 'not support "get_eventloop_weight" on the remote interpreter'
  end
get_no_event_wait()

[Source]

# File tk/lib/remote-tk.rb, line 481
  def get_no_event_wait
    fail RuntimeError, 'not support "get_no_event_wait" on the remote interpreter'
  end
mainloop(*args)

[Source]

# File tk/lib/remote-tk.rb, line 457
  def mainloop(*args)
    fail RuntimeError, 'not support "mainloop" on the remote interpreter'
  end
mainloop_abort_on_exception()

[Source]

# File tk/lib/remote-tk.rb, line 466
  def mainloop_abort_on_exception
    fail RuntimeError, 'not support "mainloop_abort_on_exception" on the remote interpreter'
  end
mainloop_abort_on_exception=(mode)

[Source]

# File tk/lib/remote-tk.rb, line 469
  def mainloop_abort_on_exception=(mode)
    fail RuntimeError, 'not support "mainloop_abort_on_exception=" on the remote interpreter'
  end
mainloop_watchdog(*args)

[Source]

# File tk/lib/remote-tk.rb, line 460
  def mainloop_watchdog(*args)
    fail RuntimeError, 'not support "mainloop_watchdog" on the remote interpreter'
  end
new(remote_ip, displayof=nil, timeout=5)

[Source]

# File tk/lib/remote-tk.rb, line 63
  def initialize(remote_ip, displayof=nil, timeout=5)
    if $SAFE >= 4
      fail SecurityError, "cannot access another interpreter at level #{$SAFE}"
    end

    @interp = MultiTkIp.__getip
    @interp.allow_ruby_exit = false
    @appname = @interp._invoke('tk', 'appname')
    @remote = remote_ip.to_s.dup.freeze
    if displayof.kind_of?(TkWindow)
      @displayof = displayof.path.dup.freeze
    else
      @displayof = nil
    end
    if self.deleted?
      fail RuntimeError, "no Tk application named \"#{@remote}\""
    end

    @tk_windows = {}
    @tk_table_list = []
    @slave_ip_tbl = {}
    @slave_ip_top = {}

    @tk_windows.taint unless @tk_windows.tainted?
    @tk_table_list.taint unless @tk_table_list.tainted?
    @slave_ip_tbl.taint unless @slave_ip_tbl.tainted?
    @slave_ip_top.taint unless @slave_ip_top.tainted?

    @system = Object.new

    @threadgroup  = ThreadGroup.new

    @safe_level = [$SAFE]

    @wait_on_mainloop = [true, 0]

    @cmd_queue = Queue.new

??
    @@DEFAULT_MASTER.assign_receiver_and_watchdog(self)

    @@IP_TABLE[@threadgroup] = self
    @@TK_TABLE_LIST.size.times{
      (tbl = {}).tainted? || tbl.taint
      @tk_table_list << tbl
    }

    @ret_val = TkVariable.new
    if timeout > 0 && ! _available_check(timeout)
      fail RuntimeError, "cannot create connection"
    end
    @ip_id = _create_connection

    class << self
      undef :instance_eval
    end

    self.freeze  # defend against modification
  end
new(*args, &b)

[Source]

# File tk/lib/remote-tk.rb, line 55
  def new(*args, &b)
    ip = __new(*args)
    ip.eval_proc(&b) if b
    ip
  end
set_eventloop_tick(*args)

[Source]

# File tk/lib/remote-tk.rb, line 472
  def set_eventloop_tick(*args)
    fail RuntimeError, 'not support "set_eventloop_tick" on the remote interpreter'
  end
set_eventloop_weight(*args)

[Source]

# File tk/lib/remote-tk.rb, line 484
  def set_eventloop_weight(*args)
    fail RuntimeError, 'not support "set_eventloop_weight" on the remote interpreter'
  end
set_no_event_wait(*args)

[Source]

# File tk/lib/remote-tk.rb, line 478
  def set_no_event_wait(*args)
    fail RuntimeError, 'not support "set_no_event_wait" on the remote interpreter'
  end

Public Instance methods

__eval(str)

[Source]

# File tk/lib/remote-tk.rb, line 307
  def __eval(str)
    _appsend(false, false, str)
  end
__invoke(*args)

[Source]

# File tk/lib/remote-tk.rb, line 324
  def __invoke(*args)
    _appsend(false, false, *args)
  end
_conv_listelement(str)

[Source]

# File tk/lib/remote-tk.rb, line 413
  def _conv_listelement(str)
    @interp._conv_listelement(str)
  end
_create_console()

[Source]

# File tk/lib/remote-tk.rb, line 417
  def _create_console
    fail RuntimeError, 'not support "_create_console" on the remote interpreter'
  end
_eval(str)

[Source]

# File tk/lib/remote-tk.rb, line 310
  def _eval(str)
    _appsend(nil, false, str)
  end
_eval_with_enc(str)

[Source]

# File tk/lib/remote-tk.rb, line 316
  def _eval_with_enc(str)
    _appsend(true, false, str)
  end
_eval_without_enc(str)

[Source]

# File tk/lib/remote-tk.rb, line 313
  def _eval_without_enc(str)
    _appsend(false, false, str)
  end
_fromUTF8(str, encoding=nil)

[Source]

# File tk/lib/remote-tk.rb, line 341
  def _fromUTF8(str, encoding=nil)
    @interp._fromUTF8(str, encoding)
  end
_get_global_var(var_name)

[Source]

# File tk/lib/remote-tk.rb, line 384
  def _get_global_var(var_name)
    _appsend(false, 'set', TkComm::_get_eval_string(var_name))
  end
_get_global_var2(var_name, index_name)

[Source]

# File tk/lib/remote-tk.rb, line 387
  def _get_global_var2(var_name, index_name)
    _appsend(false, 'set', "#{TkComm::_get_eval_string(var_name)}(#{TkComm::_get_eval_string(index_name)})")
  end
_get_variable(var_name, flag)

[Source]

# File tk/lib/remote-tk.rb, line 357
  def _get_variable(var_name, flag)
    # ignore flag
    _appsend(false, 'set', TkComm::_get_eval_string(var_name))
  end
_get_variable2(var_name, index_name, flag)

[Source]

# File tk/lib/remote-tk.rb, line 361
  def _get_variable2(var_name, index_name, flag)
    # ignore flag
    _appsend(false, 'set', "#{TkComm::_get_eval_string(var_name)}(#{TkComm::_get_eval_string(index_name)})")
  end
_invoke(*args)

[Source]

# File tk/lib/remote-tk.rb, line 320
  def _invoke(*args)
    _appsend(nil, false, *args)
  end
_invoke(*args)

[Source]

# File tk/lib/remote-tk.rb, line 327
  def _invoke(*args)
    _appsend(nil, false, *args)
  end
_invoke_with_enc(*args)

[Source]

# File tk/lib/remote-tk.rb, line 333
  def _invoke_with_enc(*args)
    _appsend(true, false, *args)
  end
_invoke_without_enc(*args)

[Source]

# File tk/lib/remote-tk.rb, line 330
  def _invoke_without_enc(*args)
    _appsend(false, false, *args)
  end
_ip_id_()

[Source]

# File tk/lib/remote-tk.rb, line 130
  def _ip_id_
    @ip_id
  end
_merge_tklist(*args)

[Source]

# File tk/lib/remote-tk.rb, line 409
  def _merge_tklist(*args)
    @interp._merge_tklist(*args)
  end
_return_value()

[Source]

# File tk/lib/remote-tk.rb, line 353
  def _return_value
    @interp._return_value
  end
_set_global_var(var_name, value)

[Source]

# File tk/lib/remote-tk.rb, line 391
  def _set_global_var(var_name, value)
    _appsend(false, 'set', TkComm::_get_eval_string(var_name), TkComm::_get_eval_string(value))
  end
_set_global_var2(var_name, index_name, value)

[Source]

# File tk/lib/remote-tk.rb, line 394
  def _set_global_var2(var_name, index_name, value)
    _appsend(false, 'set', "#{TkComm::_get_eval_string(var_name)}(#{TkComm::_get_eval_string(index_name)})", TkComm::_get_eval_string(value))
  end
_set_variable(var_name, value, flag)

[Source]

# File tk/lib/remote-tk.rb, line 366
  def _set_variable(var_name, value, flag)
    # ignore flag
    _appsend(false, 'set', TkComm::_get_eval_string(var_name), TkComm::_get_eval_string(value))
  end
_set_variable2(var_name, index_name, value, flag)

[Source]

# File tk/lib/remote-tk.rb, line 370
  def _set_variable2(var_name, index_name, value, flag)
    # ignore flag
    _appsend(false, 'set', "#{TkComm::_get_eval_string(var_name)}(#{TkComm::_get_eval_string(index_name)})", TkComm::_get_eval_string(value))
  end
_split_tklist(str)

[Source]

# File tk/lib/remote-tk.rb, line 405
  def _split_tklist(str)
    @interp._split_tklist(str)
  end
_thread_tkwait(mode, target)

[Source]

# File tk/lib/remote-tk.rb, line 349
  def _thread_tkwait(mode, target)
    _appsend(false, 'thread_tkwait', mode, target)
  end
_thread_vwait(var_name)

[Source]

# File tk/lib/remote-tk.rb, line 345
  def _thread_vwait(var_name)
    _appsend(false, 'thread_vwait', varname)
  end
_toUTF8(str, encoding=nil)

[Source]

# File tk/lib/remote-tk.rb, line 337
  def _toUTF8(str, encoding=nil)
    @interp._toUTF8(str, encoding)
  end
_unset_global_var(var_name)

[Source]

# File tk/lib/remote-tk.rb, line 398
  def _unset_global_var(var_name)
    _appsend(false, 'unset', TkComm::_get_eval_string(var_name))
  end
_unset_global_var2(var_name, index_name)

[Source]

# File tk/lib/remote-tk.rb, line 401
  def _unset_global_var2(var_name, index_name)
    _appsend(false, 'unset', "#{var_name}(#{index_name})")
  end
_unset_variable(var_name, flag)

[Source]

# File tk/lib/remote-tk.rb, line 375
  def _unset_variable(var_name, flag)
    # ignore flag
    _appsend(false, 'unset', TkComm::_get_eval_string(var_name))
  end
_unset_variable2(var_name, index_name, flag)

[Source]

# File tk/lib/remote-tk.rb, line 379
  def _unset_variable2(var_name, index_name, flag)
    # ignore flag
    _appsend(false, 'unset', "#{var_name}(#{index_name})")
  end
allow_ruby_exit=(mode)

[Source]

# File tk/lib/remote-tk.rb, line 263
  def allow_ruby_exit= (mode)
    fail RuntimeError, 'cannot change mode of the remote interpreter'
  end
allow_ruby_exit?()

[Source]

# File tk/lib/remote-tk.rb, line 259
  def allow_ruby_exit?
    false
  end
appsend(async, *args)

[Source]

# File tk/lib/remote-tk.rb, line 214
  def appsend(async, *args)
    if async != true && async != false && async != nil
      args.unshift(async)
      async = false
    end
    if @displayof
      Tk.appsend_displayof(@remote, @displayof, async, *args)
    else
      Tk.appsend(@remote, async, *args)
    end
  end
create_slave(name, safe=false)

[Source]

# File tk/lib/remote-tk.rb, line 238
  def create_slave(name, safe=false)
    if safe
      safe_opt = ''
    else
      safe_opt = '-safe'
    end
    _appsend(false, false, "interp create #{safe_opt} -- #{name}")
  end
delete()

[Source]

# File tk/lib/remote-tk.rb, line 267
  def delete
    _appsend(false, true, 'exit')
  end
deleted?()

[Source]

# File tk/lib/remote-tk.rb, line 271
  def deleted?
    if @displayof
      lst = @interp._invoke_without_enc('winfo', 'interps',
                                        '-displayof', @displayof)
    else
      lst = @interp._invoke_without_enc('winfo', 'interps')
    end
    # unless @interp._split_tklist(lst).index(@remote)
    unless @interp._split_tklist(lst).index(_toUTF8(@remote))
      true
    else
      false
    end
  end
do_one_evant(flag = nil)

[Source]

# File tk/lib/remote-tk.rb, line 427
  def do_one_evant(flag = nil)
    fail RuntimeError, 'not support "do_one_event" on the remote interpreter'
  end
get_eventloop_tick()

[Source]

# File tk/lib/remote-tk.rb, line 439
  def get_eventloop_tick
    fail RuntimeError, 'not support "get_eventloop_tick" on the remote interpreter'
  end
get_eventloop_weight()

[Source]

# File tk/lib/remote-tk.rb, line 451
  def get_eventloop_weight
    fail RuntimeError, 'not support "get_eventloop_weight" on the remote interpreter'
  end
get_no_event_wait()

[Source]

# File tk/lib/remote-tk.rb, line 445
  def get_no_event_wait
    fail RuntimeError, 'not support "get_no_event_wait" on the remote interpreter'
  end
has_mainwindow?()

[Source]

# File tk/lib/remote-tk.rb, line 286
  def has_mainwindow?
    begin
      inf = @interp._invoke_without_enc('info', 'command', '.')
    rescue Exception
      return nil
    end
    if !inf.kind_of?(String) || inf != '.'
      false
    else
      true
    end
  end
invalid_namespace?()

[Source]

# File tk/lib/remote-tk.rb, line 299
  def invalid_namespace?
    false
  end
is_rubytk?()

[Source]

# File tk/lib/remote-tk.rb, line 208
  def is_rubytk?
    return false if _appsend(false, false, 'info', 'command', 'ruby') == ""
    [ _appsend(false, false, 'ruby', 'RUBY_VERSION'),
      _appsend(false, false, 'set', 'tk_patchLevel') ]
  end
mainloop()

[Source]

# File tk/lib/remote-tk.rb, line 421
  def mainloop
    fail RuntimeError, 'not support "mainloop" on the remote interpreter'
  end
mainloop_abort_on_exception()

[Source]

# File tk/lib/remote-tk.rb, line 430
  def mainloop_abort_on_exception
    fail RuntimeError, 'not support "mainloop_abort_on_exception" on the remote interpreter'
  end
mainloop_abort_on_exception=(mode)

[Source]

# File tk/lib/remote-tk.rb, line 433
  def mainloop_abort_on_exception=(mode)
    fail RuntimeError, 'not support "mainloop_abort_on_exception=" on the remote interpreter'
  end
mainloop_watchdog()

[Source]

# File tk/lib/remote-tk.rb, line 424
  def mainloop_watchdog
    fail RuntimeError, 'not support "mainloop_watchdog" on the remote interpreter'
  end
make_safe()

[Source]

# File tk/lib/remote-tk.rb, line 247
  def make_safe
    fail RuntimeError, 'cannot change safe mode of the remote interpreter'
  end
rb_appsend(async, *args)

[Source]

# File tk/lib/remote-tk.rb, line 226
  def rb_appsend(async, *args)
    if async != true && async != false && async != nil
      args.unshift(async)
      async = false
    end
    if @displayof
      Tk.rb_appsend_displayof(@remote, @displayof, async, *args)
    else
      Tk.rb_appsend(@remote, async, *args)
    end
  end
ready?(timeout=5)

[Source]

# File tk/lib/remote-tk.rb, line 201
  def ready?(timeout=5)
    if timeout < 0
      fail ArgumentError, "timeout must be positive number"
    end
    _available_check(timeout)
  end
restart()

[Source]

# File tk/lib/remote-tk.rb, line 303
  def restart
    fail RuntimeError, 'cannot restart the remote interpreter'
  end
safe?()

[Source]

# File tk/lib/remote-tk.rb, line 251
  def safe?
    _appsend(false, false, 'interp issafe')
  end
safe_base?()

[Source]

# File tk/lib/remote-tk.rb, line 255
  def safe_base?
    false
  end
set_eventloop_tick(*args)

[Source]

# File tk/lib/remote-tk.rb, line 436
  def set_eventloop_tick(*args)
    fail RuntimeError, 'not support "set_eventloop_tick" on the remote interpreter'
  end
set_eventloop_weight(*args)

[Source]

# File tk/lib/remote-tk.rb, line 448
  def set_eventloop_weight(*args)
    fail RuntimeError, 'not support "set_eventloop_weight" on the remote interpreter'
  end
set_no_event_wait(*args)

[Source]

# File tk/lib/remote-tk.rb, line 442
  def set_no_event_wait(*args)
    fail RuntimeError, 'not support "set_no_event_wait" on the remote interpreter'
  end


Class: TclTkIp

Class | TclTkIp
In: | tk/lib/tk.rb
Parent: | Object

dummy methods

Methods

__eval __invoke _eval _eval_with_enc _eval_with_enc _invoke _invoke_with_enc _invoke_with_enc _ip_id_ new

External Aliases

_eval | -> | _eval_without_enc
 | backup original (without encoding) _eval and _invoke
_invoke | -> | _invoke_without_enc
_eval | -> | __eval
_invoke | -> | __invoke
_toUTF8 | -> | __toUTF8
_fromUTF8 | -> | __fromUTF8
new | -> | __new__

Attributes

encoding | [RW] | from tkencoding.rb by ttate@jaist.ac.jp
encoding | [RW] |

Public Class methods

new(*args)

[Source]

# File tk/lib/multi-tk.rb, line 27
  def new(*args)
    if Thread.current.group != ThreadGroup::Default
      raise SecurityError, 'only ThreadGroup::Default can call TclTkIp.new'
    end
    __new__(*args)
  end

Public Instance methods

__eval(cmd)

Alias for _eval

__invoke(*cmds)

Alias for _invoke

_eval(cmd)

[Source]

# File tk/lib/tk.rb, line 2136
    def _eval(cmd)
      _fromUTF8(__eval(_toUTF8(cmd)))
    end
_eval_with_enc(cmd)

Alias for _eval

_eval_with_enc(cmd)

Alias for _eval

_invoke(*cmds)

[Source]

# File tk/lib/tk.rb, line 2140
    def _invoke(*cmds)
      _fromUTF8(__invoke(*(cmds.collect{|cmd| _toUTF8(cmd)})))
    end
_invoke_with_enc(*cmds)

Alias for _invoke

_invoke_with_enc(*cmds)

Alias for _invoke

_ip_id_()

[Source]

# File tk/lib/tk.rb, line 18
  def _ip_id_
    ''
  end


Module: TclTkLib

Module | TclTkLib
In: | tk/lib/tk.rb

Methods

encoding encoding=

Public Class methods

encoding()

[Source]

# File tk/lib/tk.rb, line 2205
    def self.encoding
      TkCore::INTERP.encoding
    end
encoding=(name)

[Source]

# File tk/lib/tk.rb, line 2202
    def self.encoding=(name)
      TkCore::INTERP.encoding = name
    end


Module: Tk::BLT
In: tk/lib/tkextlib/blt.rb
tk/lib/tkextlib/blt/win_printer.rb
tk/lib/tkextlib/blt/winop.rb
tk/lib/tkextlib/blt/watch.rb
tk/lib/tkextlib/blt/vector.rb
tk/lib/tkextlib/blt/unix_dnd.rb
tk/lib/tkextlib/blt/treeview.rb
tk/lib/tkextlib/blt/tree.rb
tk/lib/tkextlib/blt/tile.rb
tk/lib/tkextlib/blt/tile/toplevel.rb
tk/lib/tkextlib/blt/tile/scrollbar.rb
tk/lib/tkextlib/blt/tile/radiobutton.rb
tk/lib/tkextlib/blt/tile/label.rb
tk/lib/tkextlib/blt/tile/frame.rb
tk/lib/tkextlib/blt/tile/checkbutton.rb
tk/lib/tkextlib/blt/tile/button.rb
tk/lib/tkextlib/blt/ted.rb
tk/lib/tkextlib/blt/tabset.rb
tk/lib/tkextlib/blt/tabnotebook.rb
tk/lib/tkextlib/blt/table.rb
tk/lib/tkextlib/blt/stripchart.rb
tk/lib/tkextlib/blt/spline.rb
tk/lib/tkextlib/blt/htext.rb
tk/lib/tkextlib/blt/graph.rb
tk/lib/tkextlib/blt/eps.rb
tk/lib/tkextlib/blt/dragdrop.rb
tk/lib/tkextlib/blt/cutbuffer.rb
tk/lib/tkextlib/blt/container.rb
tk/lib/tkextlib/blt/component.rb
tk/lib/tkextlib/blt/busy.rb
tk/lib/tkextlib/blt/bitmap.rb
tk/lib/tkextlib/blt/barchart.rb

Methods

active_legend beep bgexec bltdebug closest_point crc32_data crc32_file crosshairs detach_bgexec find_command find_name package_name package_version print_key zoom_stack

Classes and Modules

Module Tk::BLT::Busy
Module Tk::BLT::CutBuffer
Module Tk::BLT::DnD
Module Tk::BLT::DragDrop
Module Tk::BLT::GraphCommand
Module Tk::BLT::PlotComponent
Module Tk::BLT::Spline
Module Tk::BLT::Table
Module Tk::BLT::Ted
Module Tk::BLT::Tile
Module Tk::BLT::Winop
Class Tk::BLT::Barchart
Class Tk::BLT::Bitmap
Class Tk::BLT::Container
Class Tk::BLT::EPS
Class Tk::BLT::Graph
Class Tk::BLT::Hiertable
Class Tk::BLT::Htext
Class Tk::BLT::Printer
Class Tk::BLT::Stripchart
Class Tk::BLT::Tabnotebook
Class Tk::BLT::Tabset
Class Tk::BLT::Tree
Class Tk::BLT::Treeview
Class Tk::BLT::Vector
Class Tk::BLT::VectorAccess
Class Tk::BLT::Watch

Constants

VERSION | = | tk_call('set', 'blt_version')
PATCH_LEVEL | = | tk_call('set', 'blt_patchLevel')
LIBRARY | = | TkVarAccess.new('blt_library', lib)
LIB_PATH | = | TkVarAccess.new('blt_libPath', lib)
PACKAGE_NAME | = | 'BLT'.freeze
WinOp | = | Winop

Public Class methods

active_legend(graph)

[Source]

# File tk/lib/tkextlib/blt.rb, line 112
    def self.active_legend(graph)
      tk_call_without_enc('Blt_ActiveLegend', graph)
    end
beep(percent = 50)

[Source]

# File tk/lib/tkextlib/blt.rb, line 57
    def self.beep(percent = 50)
      tk_call('::blt::beep', percent)
    end
bgexec(*args)

[Source]

# File tk/lib/tkextlib/blt.rb, line 61
    def self.bgexec(*args)
      if args[0].kind_of?(TkVariable)
        var = args.shift
      else
        var = TkVariable.new
      end
      params = [var]

      params.concat(hash_kv(args.shift, true)) if args[0].kind_of?(Hash)

      params << '--'
      params.concat(args)

      tk_call('::blt::bgexec', *params)
      var
    end
bltdebug(lvl = nil)

[Source]

# File tk/lib/tkextlib/blt.rb, line 95
    def self.bltdebug(lvl = nil)
      if lvl
        tk_call('::blt::bltdebug', lvl)
      else
        number(tk_call('::blt::bltdebug'))
      end
    end
closest_point(graph)

[Source]

# File tk/lib/tkextlib/blt.rb, line 124
    def self.closest_point(graph)
      tk_call_without_enc('Blt_ClosestPoint', graph)
    end
crc32_data(dat)

[Source]

# File tk/lib/tkextlib/blt.rb, line 106
    def self.crc32_data(dat)
      tk_call_without_enc('::blt::crc32', '-data', dat)
    end
crc32_file(name)

[Source]

# File tk/lib/tkextlib/blt.rb, line 103
    def self.crc32_file(name)
      tk_call_without_enc('::blt::crc32', name)
    end
crosshairs(graph)

[Source]

# File tk/lib/tkextlib/blt.rb, line 115
    def self.crosshairs(graph)
      tk_call_without_enc('Blt_Crosshairs', graph)
    end
detach_bgexec(*args)

[Source]

# File tk/lib/tkextlib/blt.rb, line 78
    def self.detach_bgexec(*args)
      if args[0].kind_of?(TkVariable)
        var = args.shift
      else
        var = TkVariable.new
      end
      params = [var]

      params.concat(hash_kv(args.shift, true)) if args[0].kind_of?(Hash)

      params << '--'
      params.concat(args)
      params << '&'

      [var, tk_split_list(tk_call('::blt::bgexec', *params))]
    end
package_name()

[Source]

# File tk/lib/tkextlib/blt.rb, line 43
    def self.package_name
      PACKAGE_NAME
    end
package_version()

[Source]

# File tk/lib/tkextlib/blt.rb, line 47
    def self.package_version
      begin
        TkPackage.require('BLT')
      rescue
        ''
      end
    end
print_key(graph)

[Source]

# File tk/lib/tkextlib/blt.rb, line 121
    def self.print_key(graph)
      tk_call_without_enc('Blt_PrintKey', graph)
    end
zoom_stack(graph)

[Source]

# File tk/lib/tkextlib/blt.rb, line 118
    def self.zoom_stack(graph)
      tk_call_without_enc('Blt_ZoomStack', graph)
    end

Public Instance methods

find_command(pat)

[Source]

# File tk/lib/tkextlib/blt/container.rb, line 21
  def find_command(pat)
    list(tk_send_without_enc(tk_call(self.path, 'find', '-command', pat)))
  end
find_name(pat)

[Source]

# File tk/lib/tkextlib/blt/container.rb, line 25
  def find_name(pat)
    list(tk_send_without_enc(tk_call(self.path, 'find', '-name', pat)))
  end


Class: Tk::BLT::Barchart

Class | Tk::BLT::Barchart
In: | tk/lib/tkextlib/blt/barchart.rb
Parent: | TkWindow

Methods

extents inside invtransform metafile snap transform

Included Modules

PlotComponent GraphCommand

Constants

TkCommandNames | = | ['::blt::barchart'.freeze].freeze
WidgetClassName | = | 'Barchart'.freeze

Public Instance methods

extents(item)

[Source]

# File tk/lib/tkextlib/blt/barchart.rb, line 52
    def extents(item)
      num_or_str(tk_send_without_enc('extents', item))
    end
inside(x, y)

[Source]

# File tk/lib/tkextlib/blt/barchart.rb, line 60
    def inside(x, y)
      bool(tk_send_without_enc('inside', x, y))
    end
invtransform(x, y)

[Source]

# File tk/lib/tkextlib/blt/barchart.rb, line 56
    def invtransform(x, y)
      list(tk_send_without_enc('invtransform', x, y))
    end
metafile(file=None)

[Source]

# File tk/lib/tkextlib/blt/barchart.rb, line 64
    def metafile(file=None)
      # Windows only
      tk_send('metafile', file)
      self
    end
snap(output, keys={})

[Source]

# File tk/lib/tkextlib/blt/barchart.rb, line 70
    def snap(output, keys={})
      tk_send_without_enc('snap', *(hash_kv(keys, false) + output))
      self
    end
transform(x, y)

[Source]

# File tk/lib/tkextlib/blt/barchart.rb, line 75
    def transform(x, y)
      list(tk_send_without_enc('transform', x, y))
    end


Class: Tk::BLT::Bitmap

Class | Tk::BLT::Bitmap
In: | tk/lib/tkextlib/blt/bitmap.rb
Parent: | TkObject

Methods

compose compose_with_name data exist? exist? height height new new new_with_name source source width width

Constants

TkCommandNames | = | ['::blt::bitmap'.freeze].freeze
BITMAP_ID_TBL | = | TkCore::INTERP.create_table
BITMAP_ID | = | ['blt_bitmap_id'.freeze, '00000'.taint].freeze

External Aliases

new | -> | _new
new | -> | define
new_with_name | -> | define_with_name

Public Class methods

compose(text, keys={})

[Source]

# File tk/lib/tkextlib/blt/bitmap.rb, line 54
      def compose(text, keys={})
        _new(:text, nil, text, keys)
      end
compose_with_name(name, text, keys={})

[Source]

# File tk/lib/tkextlib/blt/bitmap.rb, line 58
      def compose_with_name(name, text, keys={})
        _new(:text, name, text, keys)
      end
data(name)

[Source]

# File tk/lib/tkextlib/blt/bitmap.rb, line 18
    def self.data(name)
      dat = tk_simple_list(tk_call('::blt::bitmap', 'data', name))
      [ tk_split_list(dat[0]), tk_simple_list(dat[1]) ]
    end
exist?(name)

[Source]

# File tk/lib/tkextlib/blt/bitmap.rb, line 23
    def self.exist?(name)
      bool(tk_call('::blt::bitmap', 'exists', name))
    end
height(name)

[Source]

# File tk/lib/tkextlib/blt/bitmap.rb, line 27
    def self.height(name)
      number(tk_call('::blt::bitmap', 'height', name))
    end
new(data, keys={})

[Source]

# File tk/lib/tkextlib/blt/bitmap.rb, line 44
      def new(data, keys={})
        _new(:data, nil, data, keys)
      end
new(type, name, data, keys = {})

[Source]

# File tk/lib/tkextlib/blt/bitmap.rb, line 63
    def initialize(type, name, data, keys = {})
      if name
        @id = name
      else
        @id = BITMAP_ID.join(TkCore::INTERP._ip_id_)
        BITMAP_ID[1].succ!
        BITMAP_ID_TBL[@id] = self
      end

      @path = @id

      unless bool(tk_call('::blt::bitmap', 'exists', @id))
        if type == :text
          tk_call('::blt::bitmap', 'compose', @id, data, *hash_kv(keys))
        else # :data
          tk_call('::blt::bitmap', 'define', @id, data, *hash_kv(keys))
        end
      end
    end
new_with_name(name, data, keys={})

[Source]

# File tk/lib/tkextlib/blt/bitmap.rb, line 49
      def new_with_name(name, data, keys={})
        _new(:data, name, data, keys)
      end
source(name)

[Source]

# File tk/lib/tkextlib/blt/bitmap.rb, line 35
    def self.source(name)
      tk_simple_list(tk_call('::blt::bitmap', 'source', name))
    end
width(name)

[Source]

# File tk/lib/tkextlib/blt/bitmap.rb, line 31
    def self.width(name)
      number(tk_call('::blt::bitmap', 'width', name))
    end

Public Instance methods

exist?()

[Source]

# File tk/lib/tkextlib/blt/bitmap.rb, line 83
    def exist?
      bool(tk_call('::blt::bitmap', 'exists', @id))
    end
height()

[Source]

# File tk/lib/tkextlib/blt/bitmap.rb, line 87
    def height
      number(tk_call('::blt::bitmap', 'height', @id))
    end
source()

[Source]

# File tk/lib/tkextlib/blt/bitmap.rb, line 95
    def source
      tk_simple_list(tk_call('::blt::bitmap', 'source', @id))
    end
width()

[Source]

# File tk/lib/tkextlib/blt/bitmap.rb, line 91
    def width
      number(tk_call('::blt::bitmap', 'width', @id))
    end


Module: Tk::BLT::Busy

Module | Tk::BLT::Busy
In: | tk/lib/tkextlib/blt/busy.rb

Methods

shield_path

Classes and Modules

Class Tk::BLT::Busy::Shield

Constants

TkCommandNames = ['::blt::busy'.freeze].freeze

Public Class methods

shield_path(win)

[Source]

# File tk/lib/tkextlib/blt/busy.rb, line 34
    def self.shield_path(win)
      Tk::BLT::Busy::Shield.shield_path(win)
    end


Class: Tk::BLT::Busy::Shield

Class | Tk::BLT::Busy::Shield
In: | tk/lib/tkextlib/blt/busy.rb
Parent: | TkWindow

Methods

new shield_path

Public Class methods

new(win)

[Source]

# File tk/lib/tkextlib/blt/busy.rb, line 29
      def initialize(win)
        @path = self.class.shield_path(win)
      end
shield_path(win)

[Source]

# File tk/lib/tkextlib/blt/busy.rb, line 20
      def self.shield_path(win)
        win = window(win) unless win.kind_of?(TkWindow)
        if win.kind_of?(TkToplevel)
          win.path + '._Busy'
        else
          win.path + '_Busy'
        end
      end


Class: Tk::BLT::Container

Class | Tk::BLT::Container
In: | tk/lib/tkextlib/blt/container.rb
Parent: | TkWindow

Constants

TkCommandNames | = | ['::blt::container'.freeze].freeze
WidgetClassName | = | 'Container'.freeze


Module: Tk::BLT::CutBuffer

Module | Tk::BLT::CutBuffer
In: | tk/lib/tkextlib/blt/cutbuffer.rb

Methods

get rotate set

Constants

TkCommandNames = ['::blt::cutbuffer'.freeze].freeze

Public Class methods

get(num = 0)

[Source]

# File tk/lib/tkextlib/blt/cutbuffer.rb, line 13
    def self.get(num = 0)
      Tk.tk_call('::blt::cutbuffer', 'get', num)
    end
rotate(count = 1)

[Source]

# File tk/lib/tkextlib/blt/cutbuffer.rb, line 16
    def self.rotate(count = 1)
      Tk.tk_call('::blt::cutbuffer', 'rotate', count)
    end
set(val, num = 0)

[Source]

# File tk/lib/tkextlib/blt/cutbuffer.rb, line 19
    def self.set(val, num = 0)
      Tk.tk_call('::blt::cutbuffer', 'set', val, num)
    end


Module: Tk::BLT::DnD

Module | Tk::BLT::DnD
In: | tk/lib/tkextlib/blt/unix_dnd.rb

Methods

cancel cget configinfo configure current_configinfo current_token_configinfo current_token_windowconfiginfo delete delete_source delete_target drag drop get_data names pull register select set_data source_names target_names token token_configinfo token_configure token_windowconfiginfo token_windowconfigure tokwn_cget

Constants

TkCommandNames = ['::blt::dnd'.freeze].freeze

Public Class methods

cancel(win)

[Source]

# File tk/lib/tkextlib/blt/unix_dnd.rb, line 75
    def self.cancel(win)
      tk_call('::blt::dnd', 'cancel', *wins)
    end
cget(win, option)

[Source]

# File tk/lib/tkextlib/blt/unix_dnd.rb, line 36
      def cget(win, option)
        itemconfigure(['cget', win], slot, value)
      end
configinfo(win, slot=nil)

[Source]

# File tk/lib/tkextlib/blt/unix_dnd.rb, line 42
      def configinfo(win, slot=nil)
        itemconfiginfo(['configure', win], slot)
      end
configure(win, slot, value=None)

[Source]

# File tk/lib/tkextlib/blt/unix_dnd.rb, line 39
      def configure(win, slot, value=None)
        itemconfigure(['configure', win], slot, value)
      end
current_configinfo(win, slot=nil)

[Source]

# File tk/lib/tkextlib/blt/unix_dnd.rb, line 45
      def current_configinfo(win, slot=nil)
        current_itemconfiginfo(['configure', win], slot)
      end
current_token_configinfo(win, slot=nil)

[Source]

# File tk/lib/tkextlib/blt/unix_dnd.rb, line 58
      def current_token_configinfo(win, slot=nil)
        current_itemconfiginfo(['token', 'configure', win], slot)
      end
current_token_windowconfiginfo(win, slot=nil)

[Source]

# File tk/lib/tkextlib/blt/unix_dnd.rb, line 68
      def current_token_windowconfiginfo(win, slot=nil)
        current_itemconfiginfo(['token', 'window', win], slot)
      end
delete(*wins)

[Source]

# File tk/lib/tkextlib/blt/unix_dnd.rb, line 78
    def self.delete(*wins)
      tk_call('::blt::dnd', 'delete', *wins)
    end
delete_source(*wins)

[Source]

# File tk/lib/tkextlib/blt/unix_dnd.rb, line 81
    def self.delete_source(*wins)
      tk_call('::blt::dnd', 'delete', '-source', *wins)
    end
delete_target(*wins)

[Source]

# File tk/lib/tkextlib/blt/unix_dnd.rb, line 84
    def self.delete_target(*wins)
      tk_call('::blt::dnd', 'delete', '-target', *wins)
    end
drag(win, x, y, token=None)

[Source]

# File tk/lib/tkextlib/blt/unix_dnd.rb, line 87
    def self.drag(win, x, y, token=None)
      tk_call('::blt::dnd', 'drag', win, x, y, token)
    end
drop(win, x, y, token=None)

[Source]

# File tk/lib/tkextlib/blt/unix_dnd.rb, line 90
    def self.drop(win, x, y, token=None)
      tk_call('::blt::dnd', 'drop', win, x, y, token)
    end
get_data(win, fmt=nil, cmd=nil)

[Source]

# File tk/lib/tkextlib/blt/unix_dnd.rb, line 93
    def self.get_data(win, fmt=nil, cmd=nil)
      if fmt
        tk_call('::blt::dnd', 'getdata', win, fmt, cmd)
      else
        list(tk_call('::blt::dnd', 'getdata', win))
      end
    end
names(pat=None)

[Source]

# File tk/lib/tkextlib/blt/unix_dnd.rb, line 100
    def self.names(pat=None)
      list(tk_call('::blt::dnd', 'names', pat))
    end
pull(win, fmt)

[Source]

# File tk/lib/tkextlib/blt/unix_dnd.rb, line 109
    def self.pull(win, fmt)
      tk_call('::blt::dnd', 'pull', win, fmt)
    end
register(win, keys={})

[Source]

# File tk/lib/tkextlib/blt/unix_dnd.rb, line 112
    def self.register(win, keys={})
      tk_call('::blt::dnd', 'register', win, keys)
    end
select(win, x, y, timestamp)

[Source]

# File tk/lib/tkextlib/blt/unix_dnd.rb, line 115
    def self.select(win, x, y, timestamp)
      tk_call('::blt::dnd', 'select', win, x, y, timestamp)
    end
set_data(win, fmt=nil, cmd=nil)

[Source]

# File tk/lib/tkextlib/blt/unix_dnd.rb, line 118
    def self.set_data(win, fmt=nil, cmd=nil)
      if fmt
        tk_call('::blt::dnd', 'setdata', win, fmt, cmd)
      else
        list(tk_call('::blt::dnd', 'setdata', win))
      end
    end
source_names(pat=None)

[Source]

# File tk/lib/tkextlib/blt/unix_dnd.rb, line 103
    def self.source_names(pat=None)
      list(tk_call('::blt::dnd', 'names', '-source', pat))
    end
target_names(pat=None)

[Source]

# File tk/lib/tkextlib/blt/unix_dnd.rb, line 106
    def self.target_names(pat=None)
      list(tk_call('::blt::dnd', 'names', '-target', pat))
    end
token(*args)

[Source]

# File tk/lib/tkextlib/blt/unix_dnd.rb, line 125
    def self.token(*args)
      tk_call('::blt::dnd', 'token', *args)
    end
token_configinfo(win, slot=nil)

[Source]

# File tk/lib/tkextlib/blt/unix_dnd.rb, line 55
      def token_configinfo(win, slot=nil)
        itemconfiginfo(['token', 'configure', win], slot)
      end
token_configure(win, slot, value=None)

[Source]

# File tk/lib/tkextlib/blt/unix_dnd.rb, line 52
      def token_configure(win, slot, value=None)
        itemconfigure(['token', 'configure', win], slot, value)
      end
token_windowconfiginfo(win, slot=nil)

[Source]

# File tk/lib/tkextlib/blt/unix_dnd.rb, line 65
      def token_windowconfiginfo(win, slot=nil)
        itemconfiginfo(['token', 'window', win], slot)
      end
token_windowconfigure(win, slot, value=None)

[Source]

# File tk/lib/tkextlib/blt/unix_dnd.rb, line 62
      def token_windowconfigure(win, slot, value=None)
        itemconfigure(['token', 'window', win], slot, value)
      end
tokwn_cget(win, option)

[Source]

# File tk/lib/tkextlib/blt/unix_dnd.rb, line 49
      def tokwn_cget(win, option)
        itemconfigure(['token', 'cget', win], slot, value)
      end


Module: Tk::BLT::DragDrop

Module | Tk::BLT::DragDrop
In: | tk/lib/tkextlib/blt/dragdrop.rb

Methods

__validation_class_list active current_source_configinfo drag drop errors handle_target init_source location source source_configinfo source_configure source_handler source_handler_info source_handler_list target target_handler target_handler_list token

Classes and Modules

Class Tk::BLT::DragDrop::DnD_Handle
Class Tk::BLT::DragDrop::PackageCommand
Class Tk::BLT::DragDrop::SiteCommand
Class Tk::BLT::DragDrop::Token

Constants

TkCommandNames = ['::blt::drag&drop'.freeze].freeze

Public Class methods

__validation_class_list()

[Source]

# File tk/lib/tkextlib/blt/dragdrop.rb, line 122
    def self.__validation_class_list
      super() << PackageCommand << SiteCommand
    end
active()

[Source]

# File tk/lib/tkextlib/blt/dragdrop.rb, line 206
    def self.active
      bool(tk_call('::blt::drag&drop', 'active'))
    end
current_source_configinfo(win, slot=nil)

[Source]

# File tk/lib/tkextlib/blt/dragdrop.rb, line 66
      def current_source_configinfo(win, slot=nil)
        current_itemconfiginfo(['source', win], slot)
      end
drag(win, x, y)

[Source]

# File tk/lib/tkextlib/blt/dragdrop.rb, line 195
    def self.drag(win, x, y)
      tk_call('::blt::drag&drop', 'drag', win, x, y)
    end
drop(win, x, y)

[Source]

# File tk/lib/tkextlib/blt/dragdrop.rb, line 198
    def self.drop(win, x, y)
      tk_call('::blt::drag&drop', 'drop', win, x, y)
    end
errors(cmd=Proc.new)

[Source]

# File tk/lib/tkextlib/blt/dragdrop.rb, line 202
    def self.errors(cmd=Proc.new)
      tk_call('::blt::drag&drop', 'errors', cmd)
    end
handle_target(win, type, val=None)

[Source]

# File tk/lib/tkextlib/blt/dragdrop.rb, line 187
    def self.handle_target(win, type, val=None)
      tk_call('::blt::drag&drop', 'target', win, 'handle', type, val)
    end
init_source(win)

[Source]

# File tk/lib/tkextlib/blt/dragdrop.rb, line 165
    def self.init_source(win)
      tk_call('::blt::drag&drop', 'source', win)
    end
location(x=None, y=None)

[Source]

# File tk/lib/tkextlib/blt/dragdrop.rb, line 210
    def self.location(x=None, y=None)
      list(tk_call('::blt::drag&drop', 'location', x, y))
    end
source()

[Source]

# File tk/lib/tkextlib/blt/dragdrop.rb, line 169
    def self.source()
      list(tk_call('::blt::drag&drop', 'source'))
    end
source_configinfo(win, slot=nil)

[Source]

# File tk/lib/tkextlib/blt/dragdrop.rb, line 63
      def source_configinfo(win, slot=nil)
        itemconfiginfo(['source', win], slot)
      end
source_configure(win, slot, value=None)

[Source]

# File tk/lib/tkextlib/blt/dragdrop.rb, line 60
      def source_configure(win, slot, value=None)
        itemconfigure(['source', win], slot, value)
      end
source_handler(win, datatype, cmd=Proc.new, *args)

[Source]

# File tk/lib/tkextlib/blt/dragdrop.rb, line 151
    def self.source_handler(win, datatype, cmd=Proc.new, *args)
      _bind_for_event_class(DnD_Handle,
                            ['::blt::drag&drop', 'source', win, 'handler'],
                            cmd, *args)
    end
source_handler_info(win, type)

[Source]

# File tk/lib/tkextlib/blt/dragdrop.rb, line 176
    def self.source_handler_info(win, type)
      tk_tcl2ruby(tk_call('::blt::drag&drop', 'source', win, 'handler', type))
    end
source_handler_list(win)

[Source]

# File tk/lib/tkextlib/blt/dragdrop.rb, line 173
    def self.source_handler_list(win)
      simplelist(tk_call('::blt::drag&drop', 'source', win, 'handler'))
    end
target()

[Source]

# File tk/lib/tkextlib/blt/dragdrop.rb, line 180
    def self.target
      list(tk_call('::blt::drag&drop', 'target'))
    end
target_handler(win, datatype, cmd=Proc.new, *args)

[Source]

# File tk/lib/tkextlib/blt/dragdrop.rb, line 157
    def self.target_handler(win, datatype, cmd=Proc.new, *args)
      _bind_for_event_class(DnD_Handle,
                            ['::blt::drag&drop', 'target', win, 'handler'],
                            cmd, *args)
    end
target_handler_list(win)

[Source]

# File tk/lib/tkextlib/blt/dragdrop.rb, line 183
    def self.target_handler_list(win)
      simplelist(tk_call('::blt::drag&drop', 'target', win, 'handler'))
    end
token(win)

[Source]

# File tk/lib/tkextlib/blt/dragdrop.rb, line 191
    def self.token(win)
      window(tk_call('::blt::drag&drop', 'token', win))
    end


Class: Tk::BLT::DragDrop::DnD_Handle

Class | Tk::BLT::DragDrop::DnD_Handle
In: | tk/lib/tkextlib/blt/dragdrop.rb
Parent: | TkUtil::CallbackSubst

Constants

KEY_TBL | = | [ [ ?i, ?s, :ip_name ], [ ?v, ?v, :value ], [ ?W, ?w, :widget ], nil
PROC_TBL | = | [ [ ?i, TkComm.method(:string) ], [ ?v, TkComm.method(:tk_tcl2ruby) ], [ ?w, TkComm.method(:window) ], nil


Class: Tk::BLT::DragDrop::PackageCommand

Class | Tk::BLT::DragDrop::PackageCommand
In: | tk/lib/tkextlib/blt/dragdrop.rb
Parent: | TkValidateCommand

Methods

_config_keys

Classes and Modules

Class Tk::BLT::DragDrop::PackageCommand::ValidateArgs

Public Class methods

_config_keys()

[Source]

# File tk/lib/tkextlib/blt/dragdrop.rb, line 91
      def self._config_keys
        ['packagecmd']
      end


Class: Tk::BLT::DragDrop::PackageCommand::ValidateArgs

Class | Tk::BLT::DragDrop::PackageCommand::ValidateArgs
In: | tk/lib/tkextlib/blt/dragdrop.rb
Parent: | TkUtil::CallbackSubst

Methods

ret_val

Constants

KEY_TBL | = | [ [ ?t, ?w, :token ], [ ?W, ?w, :widget ], nil
PROC_TBL | = | [ [ ?w, TkComm.method(:window) ], nil

Public Class methods

ret_val(val)

[Source]

# File tk/lib/tkextlib/blt/dragdrop.rb, line 86
        def self.ret_val(val)
          val
        end


Class: Tk::BLT::DragDrop::SiteCommand

Class | Tk::BLT::DragDrop::SiteCommand
In: | tk/lib/tkextlib/blt/dragdrop.rb
Parent: | TkValidateCommand

Methods

_config_keys

Classes and Modules

Class Tk::BLT::DragDrop::SiteCommand::ValidateArgs

Public Class methods

_config_keys()

[Source]

# File tk/lib/tkextlib/blt/dragdrop.rb, line 117
      def self._config_keys
        ['sitecmd']
      end


Class: Tk::BLT::DragDrop::SiteCommand::ValidateArgs

Class | Tk::BLT::DragDrop::SiteCommand::ValidateArgs
In: | tk/lib/tkextlib/blt/dragdrop.rb
Parent: | TkUtil::CallbackSubst

Methods

ret_val

Constants

KEY_TBL | = | [ [ ?s, ?b, :compatible ], [ ?t, ?w, :token ], nil
PROC_TBL | = | [ [ ?b, TkComm.method(:bool) ], [ ?w, TkComm.method(:window) ], nil

Public Class methods

ret_val(val)

[Source]

# File tk/lib/tkextlib/blt/dragdrop.rb, line 112
        def self.ret_val(val)
          val
        end


Class: Tk::BLT::DragDrop::Token

Class | Tk::BLT::DragDrop::Token
In: | tk/lib/tkextlib/blt/dragdrop.rb
Parent: | TkWindow

Methods

new

Constants

WidgetClassName = 'DragDropToken'.freeze

Public Class methods

new(arg)

[Source]

# File tk/lib/tkextlib/blt/dragdrop.rb, line 20
      def initialize(arg)
        if arg.kind_of?(Hash) # arg is a hash includes the widgetpath of token
          arg = _symbolkey2str(arg)
          install_win(nil, arg['widgetname'])
        else  # arg is a drag&drop source
          tk_call('::blt::drag&drop', 'source', arg)
          install_win(nil, tk_call('::blt::drag&drop', 'token', arg))
        end
      end


Class: Tk::BLT::EPS

Class | Tk::BLT::EPS
In: | tk/lib/tkextlib/blt/eps.rb
Parent: | TkcItem

Constants

CItemTypeName = 'eps'.freeze


Class: Tk::BLT::Graph

Class | Tk::BLT::Graph
In: | tk/lib/tkextlib/blt/graph.rb
Parent: | TkWindow

Methods

extents inside invtransform snap transform

Included Modules

PlotComponent GraphCommand

Constants

TkCommandNames | = | ['::blt::graph'.freeze].freeze
WidgetClassName | = | 'Graph'.freeze

Public Instance methods

extents(item)

[Source]

# File tk/lib/tkextlib/blt/graph.rb, line 46
    def extents(item)
      num_or_str(tk_send_without_enc('extents', item))
    end
inside(x, y)

[Source]

# File tk/lib/tkextlib/blt/graph.rb, line 54
    def inside(x, y)
      bool(tk_send_without_enc('inside', x, y))
    end
invtransform(x, y)

[Source]

# File tk/lib/tkextlib/blt/graph.rb, line 50
    def invtransform(x, y)
      list(tk_send_without_enc('invtransform', x, y))
    end
snap(output, keys={})

[Source]

# File tk/lib/tkextlib/blt/graph.rb, line 58
    def snap(output, keys={})
      tk_send_without_enc('snap', *(hash_kv(keys, false) + output))
      self
    end
transform(x, y)

[Source]

# File tk/lib/tkextlib/blt/graph.rb, line 63
    def transform(x, y)
      list(tk_send_without_enc('transform', x, y))
    end


Module: Tk::BLT::GraphCommand

Module | Tk::BLT::GraphCommand
In: | tk/lib/tkextlib/blt.rb

Methods

active_legend closest_point crosshairs print_key zoom_stack

Public Instance methods

active_legend()

[Source]

# File tk/lib/tkextlib/blt.rb, line 129
      def active_legend
        tk_call_without_enc('Blt_ActiveLegend', @path)
        self
      end
closest_point()

[Source]

# File tk/lib/tkextlib/blt.rb, line 145
      def closest_point
        tk_call_without_enc('Blt_ClosestPoint', @path)
        self
      end
crosshairs()

[Source]

# File tk/lib/tkextlib/blt.rb, line 133
      def crosshairs
        tk_call_without_enc('Blt_Crosshairs', @path)
        self
      end
print_key()

[Source]

# File tk/lib/tkextlib/blt.rb, line 141
      def print_key
        tk_call_without_enc('Blt_PrintKey', @path)
        self
      end
zoom_stack()

[Source]

# File tk/lib/tkextlib/blt.rb, line 137
      def zoom_stack
        tk_call_without_enc('Blt_ZoomStack', @path)
        self
      end


Class: Tk::BLT::Hiertable

Class | Tk::BLT::Hiertable
In: | tk/lib/tkextlib/blt/treeview.rb
Parent: | Treeview

Constants

TkCommandNames | = | ['::blt::hiertable'.freeze].freeze
WidgetClassName | = | 'Hiertable'.freeze


Class: Tk::BLT::Htext

Class | Tk::BLT::Htext
In: | tk/lib/tkextlib/blt/htext.rb
Parent: | TkWindow

Methods

append current_line goto_line index line_pos range scan_dragto scan_mark search selection_adjust selection_clear selection_from selection_line selection_present selection_range selection_to selection_word windows

Included Modules

TkItemConfigMethod Scrollable

Constants

Htext_Var | = | TkVarAccess.new_hash('htext')
Htext_Widget | = | TkVarAccess.new('htext(widget)', :window)
Htext_File | = | TkVarAccess.new('htext(file)')
Htext_Line | = | TkVarAccess.new('htext(line)')
TkCommandNames | = | ['::blt::htext'.freeze].freeze
WidgetClassName | = | 'Htext'.freeze

External Aliases

itemcget | -> | window_cget
itemconfigure | -> | window_configure
itemconfiginfo | -> | window_configuinfo
current_itemconfiginfo | -> | current_window_configuinfo

Public Instance methods

append(win, keys={})

[Source]

# File tk/lib/tkextlib/blt/htext.rb, line 34
    def append(win, keys={})
      tk_send('append', _epath(win), keys)
      self
    end
current_line()

[Source]

# File tk/lib/tkextlib/blt/htext.rb, line 43
    def current_line
      number(tk_send_without_enc('gotoline'))
    end
goto_line(idx)

[Source]

# File tk/lib/tkextlib/blt/htext.rb, line 39
    def goto_line(idx)
      tk_send_without_enc('gotoline', idx)
      self
    end
index(str)

[Source]

# File tk/lib/tkextlib/blt/htext.rb, line 47
    def index(str)
      number(tk_send('index', str))
    end
line_pos(str)

[Source]

# File tk/lib/tkextlib/blt/htext.rb, line 51
    def line_pos(str)
      tk_send('linepos', str)
    end
range(from=None, to=None)

[Source]

# File tk/lib/tkextlib/blt/htext.rb, line 55
    def range(from=None, to=None)
      tk_send_without_enc('range', from, to)
    end
scan_dragto(pos)

[Source]

# File tk/lib/tkextlib/blt/htext.rb, line 64
    def scan_dragto(pos)
      tk_send_without_enc('scan', 'dragto', pos)
      self
    end
scan_mark(pos)

[Source]

# File tk/lib/tkextlib/blt/htext.rb, line 59
    def scan_mark(pos)
      tk_send_without_enc('scan', 'mark', pos)
      self
    end
search(pat, from=None, to=None)

[Source]

# File tk/lib/tkextlib/blt/htext.rb, line 69
    def search(pat, from=None, to=None)
      num = number(tk_send('search', pat, from, to))
      (num < 0)? nil: num
    end
selection_adjust(index)

[Source]

# File tk/lib/tkextlib/blt/htext.rb, line 74
    def selection_adjust(index)
      tk_send_without_enc('selection', 'adjust', index)
      self
    end
selection_clear()

[Source]

# File tk/lib/tkextlib/blt/htext.rb, line 78
    def selection_clear()
      tk_send_without_enc('selection', 'clear')
      self
    end
selection_from(index)

[Source]

# File tk/lib/tkextlib/blt/htext.rb, line 82
    def selection_from(index)
      tk_send_without_enc('selection', 'from', index)
      self
    end
selection_line(index)

[Source]

# File tk/lib/tkextlib/blt/htext.rb, line 86
    def selection_line(index)
      tk_send_without_enc('selection', 'line', index)
      self
    end
selection_present()

[Source]

# File tk/lib/tkextlib/blt/htext.rb, line 90
    def selection_present()
      bool(tk_send_without_enc('selection', 'present'))
    end
selection_range(first, last)

[Source]

# File tk/lib/tkextlib/blt/htext.rb, line 93
    def selection_range(first, last)
      tk_send_without_enc('selection', 'range', first, last)
      self
    end
selection_to(index)

[Source]

# File tk/lib/tkextlib/blt/htext.rb, line 97
    def selection_to(index)
      tk_send_without_enc('selection', 'to', index)
      self
    end
selection_word(index)

[Source]

# File tk/lib/tkextlib/blt/htext.rb, line 101
    def selection_word(index)
      tk_send_without_enc('selection', 'word', index)
      self
    end
windows(pat=None)

[Source]

# File tk/lib/tkextlib/blt/htext.rb, line 106
    def windows(pat=None)
      list(tk_send('windows', pat))
    end


Module: Tk::BLT::PlotComponent

Module | Tk::BLT::PlotComponent
In: | tk/lib/tkextlib/blt/component.rb

Methods

__destroy_hook__ axis_bind axis_bind_append axis_bind_remove axis_bindinfo axis_cget axis_configinfo axis_configure axis_create axis_delete axis_invtransform axis_limits axis_names axis_transform axis_use axis_view bar bar bar_activate bar_bind bar_bind_append bar_bind_remove bar_bindinfo bar_cget bar_closest bar_configinfo bar_configure bar_create bar_deactivate bar_delete bar_exist? bar_names bar_show bar_type crosshairs_cget crosshairs_configinfo crosshairs_configure crosshairs_off crosshairs_on crosshairs_toggle current_axis_configinfo current_bar_configinfo current_crosshairs_configinfo current_element_configinfo current_gridline_configinfo current_legend_configinfo current_line_configinfo current_marker_configinfo current_pen_configinfo current_postscript_configinfo current_x2axis_configinfo current_xaxis_configinfo current_y2axis_configinfo current_yaxis_configinfo element_activate element_bind element_bind_append element_bind_remove element_bindinfo element_cget element_closest element_configinfo element_configure element_create element_deactivate element_delete element_exist? element_names element_show element_type gridline_cget gridline_configinfo gridline_configure gridline_off gridline_on gridline_toggle legend_activate legend_bind legend_bind_append legend_bind_remove legend_bindinfo legend_cget legend_configinfo legend_configure legend_deactivate legend_get legend_window_create line_activate line_bind line_bind_append line_bind_remove line_bindinfo line_cget line_closest line_configinfo line_configure line_create line_deactivate line_delete line_exist? line_names line_show line_type marker_after marker_before marker_bind marker_bind_append marker_bind_remove marker_bindinfo marker_cget marker_configinfo marker_configure marker_create marker_delete marker_exist? marker_names marker_type pen_cget pen_configinfo pen_configure pen_create pen_delete pen_names postscript_cget postscript_configinfo postscript_configure postscript_output tagid x2axis_bind x2axis_bind_append x2axis_bind_remove x2axis_bindinfo x2axis_cget x2axis_configinfo x2axis_configure x2axis_invtransform x2axis_limits x2axis_transform x2axis_use xaxis_bind xaxis_bind_append xaxis_bind_remove xaxis_bindinfo xaxis_cget xaxis_configinfo xaxis_configure xaxis_invtransform xaxis_limits xaxis_transform xaxis_use y2axis_bind y2axis_bind_append y2axis_bind_remove y2axis_bindinfo y2axis_cget y2axis_configinfo y2axis_configure y2axis_invtransform y2axis_limits y2axis_transform y2axis_use yaxis_bind yaxis_bind_append yaxis_bind_remove yaxis_bindinfo yaxis_cget yaxis_configinfo yaxis_configure yaxis_invtransform yaxis_limits yaxis_transform yaxis_use

Included Modules

TkItemConfigMethod OptKeys

Classes and Modules

Module Tk::BLT::PlotComponent::OptKeys
Class Tk::BLT::PlotComponent::Axis
Class Tk::BLT::PlotComponent::Bar
Class Tk::BLT::PlotComponent::BitmapMarker
Class Tk::BLT::PlotComponent::Crosshairs
Class Tk::BLT::PlotComponent::Element
Class Tk::BLT::PlotComponent::GridLine
Class Tk::BLT::PlotComponent::ImageMarker
Class Tk::BLT::PlotComponent::Legend
Class Tk::BLT::PlotComponent::Line
Class Tk::BLT::PlotComponent::LineMarker
Class Tk::BLT::PlotComponent::Marker
Class Tk::BLT::PlotComponent::Pen
Class Tk::BLT::PlotComponent::PolygonMarker
Class Tk::BLT::PlotComponent::Postscript
Class Tk::BLT::PlotComponent::TextMarker
Class Tk::BLT::PlotComponent::WindowMarker

External Aliases

itemcget | -> | __itemcget
itemconfiginfo | -> | __itemconfiginfo
current_itemconfiginfo | -> | __current_itemconfiginfo

Public Instance methods

__destroy_hook__()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1039
    def __destroy_hook__
      Axis::OBJ_TBL.delete(@path)
      Crosshairs::OBJ_TBL.delete(@path)
      Element::OBJ_TBL.delete(@path)
      GridLine::OBJ_TBL.delete(@path)
      Legend::OBJ_TBL.delete(@path)
      Pen::OBJ_TBL.delete(@path)
      Postscript::OBJ_TBL.delete(@path)
      Marker::OBJ_TBL.delete(@path)
      super()
    end
axis_bind(tag, context, *args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1096
    def axis_bind(tag, context, *args)
      _component_bind('axis', tag, context, *args)
    end
axis_bind_append(tag, context, *args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1099
    def axis_bind_append(tag, context, *args)
      _component_bind_append('axis', tag, context, *args)
    end
axis_bind_remove(tag, context)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1102
    def axis_bind_remove(tag, context)
      _component_bind_remove('axis', tag, context)
    end
axis_bindinfo(tag, context=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1105
    def axis_bindinfo(tag, context=nil)
      _component_bindinfo('axis', tag, context)
    end
axis_cget(id, option)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 85
    def axis_cget(id, option)
      ret = itemcget(['axis', tagid(id)], option)
    end
axis_configinfo(id, slot=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 111
    def axis_configinfo(id, slot=nil)
      itemconfiginfo(['axis', tagid(id)], slot)
    end
axis_configure(*args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 88
    def axis_configure(*args)
      slot = args.pop
      if slot.kind_of?(Hash)
        value = None
        slot = _symbolkey2str(slot)
        if cmd = slot.delete('command')
          slot['command'] = proc{|w, tick|
            cmd.call(TkComm.window(w), TkComm.num_or_str(tick))
          }
        end
      else
        value = slot
        slot = args.pop
        if slot == :command || slot == 'command'
          cmd = value
          value = proc{|w, tick|
            cmd.call(TkComm.window(w), TkComm.num_or_str(tick))
          }
        end
      end
      id_list = args.flatten.collect!{|id| tagid(id)}.unshift('axis')
      itemconfigure(id_list, slot, value)
    end
axis_create(id=nil, keys={})

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1176
    def axis_create(id=nil, keys={})
      # tk_send('axis', 'create', tagid(id), keys)
      Tk::BLT::PlotComponent::Axis.new(self, tagid(id), keys)
    end
axis_delete(*ids)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1180
    def axis_delete(*ids)
      tk_send('axis', 'delete', *(ids.collect{|id| tagid(id)}))
      self
    end
axis_invtransform(id, val)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1184
    def axis_invtransform(id, val)
      list(tk_send('axis', 'invtransform', tagid(id), val))
    end
axis_limits(id)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1187
    def axis_limits(id)
      list(tk_send('axis', 'limits', tagid(id)))
    end
axis_names(*pats)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1190
    def axis_names(*pats)
      simplelist(tk_send('axis', 'names',
                         *(pats.collect{|pat| tagid(pat)}))).collect{|axis|
        Tk::BLT::PlotComponent::Axis.id2obj(self, axis)
      }
    end
axis_transform(id, val)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1196
    def axis_transform(id, val)
      list(tk_send('axis', 'transform', tagid(id), val))
    end
axis_use(id, target=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1203
    def axis_use(id, target=nil)
      if target
        Tk::BLT::PlotComponent::Axis.id2obj(self,
                                            tk_send('axis', 'use',
                                                    tagid(id), tagid(target)))
      else
        Tk::BLT::PlotComponent::Axis.id2obj(self,
                                            tk_send('axis', 'use', tagid(id)))
      end
    end
axis_view(id)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1199
    def axis_view(id)
      tk_send('axis', 'view', tagid(id))
      self
    end
bar(id=nil, keys={})

Alias for bar_create

bar(id=nil, keys={})

Alias for line_create

bar_activate(*args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1292
    def bar_activate(*args)
      if args.empty?
        list(tk_send('bar', 'activate')).collect{|elem|
          Tk::BLT::PlotComponent::Element.id2obj(self, elem)
        }
      else
        # id, *indices
        id = args.shift
        tk_send('bar', 'activate', tagid(id), *args)
      end
    end
bar_bind(tag, context, *args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1122
    def bar_bind(tag, context, *args)
      _component_bind('bar', tag, context, *args)
    end
bar_bind_append(tag, context, *args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1125
    def bar_bind_append(tag, context, *args)
      _component_bind_append('bar', tag, context, *args)
    end
bar_bind_remove(tag, context)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1128
    def bar_bind_remove(tag, context)
      _component_bind_remove('bar', tag, context)
    end
bar_bindinfo(tag, context=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1131
    def bar_bindinfo(tag, context=nil)
      _component_bindinfo('bar', tag, context)
    end
bar_cget(id, option)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 152
    def bar_cget(id, option)
      itemcget(['bar', tagid(id)], option)
    end
bar_closest(x, y, var, *args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1303
    def bar_closest(x, y, var, *args)
      if args[-1].kind_of?(Hash)
        keys = args.pop
        bool(tk_send('bar', 'closest', x, y, var,
                     *(hash_kv(keys).concat(args.collect{|id| tagid(id)}))))
      else
        bool(tk_send('bar', 'closest', x, y, var,
                     *(args.collect{|id| tagid(id)})))
      end
    end
bar_configinfo(id, slot=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 166
    def bar_configinfo(id, slot=nil)
      itemconfiginfo(['bar', tagid(id)], slot)
    end
bar_configure(*args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 155
    def bar_configure(*args)
      slot = args.pop
      if slot.kind_of?(Hash)
        value = None
      else
        value = slot
        slot = args.pop
      end
      id_list = args.flatten.collect!{|id| tagid(id)}.unshift('bar')
      itemconfigure(id_list, slot, value)
    end
bar_create(id=nil, keys={})

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1287
    def bar_create(id=nil, keys={})
      # tk_send('bar', 'create', tagid(id), keys)
      Tk::BLT::PlotComponent::Bar.new(self, tagid(id), keys)
    end
bar_deactivate(*ids)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1313
    def bar_deactivate(*ids)
      tk_send('bar', 'deactivate', *(ids.collect{|id| tagid(id)}))
      self
    end
bar_delete(*ids)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1317
    def bar_delete(*ids)
      tk_send('bar', 'delete', *(ids.collect{|id| tagid(id)}))
      self
    end
bar_exist?(id)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1321
    def bar_exist?(id)
      bool(tk_send('bar', 'exists', tagid(id)))
    end
bar_names(*pats)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1324
    def bar_names(*pats)
      simplelist(tk_send('bar', 'names',
                         *(pats.collect{|pat| tagid(pat)}))).collect{|elem|
        Tk::BLT::PlotComponent::Element.id2obj(self, elem)
      }
    end
bar_show(*names)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1330
    def bar_show(*names)
      if names.empty?
        simplelist(tk_send('bar', 'show'))
      else
        tk_send('bar', 'show', *(names.collect{|n| tagid(n)}))
        self
      end
    end
bar_type(id)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1338
    def bar_type(id)
      tk_send('bar', 'type', tagid(id))
    end
crosshairs_cget(option)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 118
    def crosshairs_cget(option)
      itemcget('crosshairs', option)
    end
crosshairs_configinfo(slot=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 124
    def crosshairs_configinfo(slot=nil)
      itemconfiginfo('crosshairs', slot)
    end
crosshairs_configure(slot, value=None)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 121
    def crosshairs_configure(slot, value=None)
      itemconfigure('crosshairs', slot, value)
    end
crosshairs_off()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1216
    def crosshairs_off
      tk_send_without_enc('crosshairs', 'off')
      self
    end
crosshairs_on()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1220
    def crosshairs_on
      tk_send_without_enc('crosshairs', 'on')
      self
    end
crosshairs_toggle()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1224
    def crosshairs_toggle
      tk_send_without_enc('crosshairs', 'toggle')
      self
    end
current_axis_configinfo(id, slot=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 114
    def current_axis_configinfo(id, slot=nil)
      current_itemconfiginfo(['axis', tagid(id)], slot)
    end
current_bar_configinfo(id, slot=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 169
    def current_bar_configinfo(id, slot=nil)
      current_itemconfiginfo(['bar', tagid(id)], slot)
    end
current_crosshairs_configinfo(slot=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 127
    def current_crosshairs_configinfo(slot=nil)
      current_itemconfiginfo('crosshairs', slot)
    end
current_element_configinfo(id, slot=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 148
    def current_element_configinfo(id, slot=nil)
      current_itemconfiginfo(['element', tagid(id)], slot)
    end
current_gridline_configinfo(slot=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 203
    def current_gridline_configinfo(slot=nil)
      current_itemconfiginfo('grid', slot)
    end
current_legend_configinfo(slot=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 216
    def current_legend_configinfo(slot=nil)
      current_itemconfiginfo('legend', slot)
    end
current_line_configinfo(id, slot=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 190
    def current_line_configinfo(id, slot=nil)
      current_itemconfiginfo(['line', tagid(id)], slot)
    end
current_marker_configinfo(id, slot=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 271
    def current_marker_configinfo(id, slot=nil)
      current_itemconfiginfo(['marker', tagid(id)], slot)
    end
current_pen_configinfo(id, slot=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 237
    def current_pen_configinfo(id, slot=nil)
      current_itemconfiginfo(['pen', tagid(id)], slot)
    end
current_postscript_configinfo(slot=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 250
    def current_postscript_configinfo(slot=nil)
      current_itemconfiginfo('postscript', slot)
    end
current_x2axis_configinfo(slot=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1650
    def current_x2axis_configinfo(slot=nil)
      current_itemconfiginfo('x2axis', slot)
    end
current_xaxis_configinfo(slot=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1581
    def current_xaxis_configinfo(slot=nil)
      current_itemconfiginfo('xaxis', slot)
    end
current_y2axis_configinfo(slot=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1788
    def current_y2axis_configinfo(slot=nil)
      current_itemconfiginfo('y2axis', slot)
    end
current_yaxis_configinfo(slot=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1719
    def current_yaxis_configinfo(slot=nil)
      current_itemconfiginfo('yaxis', slot)
    end
element_activate(*args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1235
    def element_activate(*args)
      if args.empty?
        list(tk_send('element', 'activate')).collect{|elem|
          Tk::BLT::PlotComponent::Element.id2obj(self, elem)
        }
      else
        # id, *indices
        id = args.shift
        tk_send('element', 'activate', tagid(id), *args)
      end
    end
element_bind(tag, context, *args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1109
    def element_bind(tag, context, *args)
      _component_bind('element', tag, context, *args)
    end
element_bind_append(tag, context, *args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1112
    def element_bind_append(tag, context, *args)
      _component_bind_append('element', tag, context, *args)
    end
element_bind_remove(tag, context)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1115
    def element_bind_remove(tag, context)
      _component_bind_remove('element', tag, context)
    end
element_bindinfo(tag, context=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1118
    def element_bindinfo(tag, context=nil)
      _component_bindinfo('element', tag, context)
    end
element_cget(id, option)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 131
    def element_cget(id, option)
      itemcget(['element', tagid(id)], option)
    end
element_closest(x, y, var, *args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1246
    def element_closest(x, y, var, *args)
      if args[-1].kind_of?(Hash)
        keys = args.pop
        bool(tk_send('element', 'closest', x, y, var,
                     *(hash_kv(keys).concat(args.collect{|id| tagid(id)}))))
      else
        bool(tk_send('element', 'closest', x, y, var,
                     *(args.collect{|id| tagid(id)})))
      end
    end
element_configinfo(id, slot=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 145
    def element_configinfo(id, slot=nil)
      itemconfiginfo(['element', tagid(id)], slot)
    end
element_configure(*args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 134
    def element_configure(*args)
      slot = args.pop
      if slot.kind_of?(Hash)
        value = None
      else
        value = slot
        slot = args.pop
      end
      id_list = args.flatten.collect!{|id| tagid(id)}.unshift('element')
      itemconfigure(id_list, slot, value)
    end
element_create(id=nil, keys={})

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1231
    def element_create(id=nil, keys={})
      # tk_send('element', 'create', tagid(id), keys)
      Tk::BLT::PlotComponent::Element.new(self, tagid(id), keys)
    end
element_deactivate(*ids)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1256
    def element_deactivate(*ids)
      tk_send('element', 'deactivate', *(ids.collect{|id| tagid(id)}))
      self
    end
element_delete(*ids)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1260
    def element_delete(*ids)
      tk_send('element', 'delete', *(ids.collect{|id| tagid(id)}))
      self
    end
element_exist?(id)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1264
    def element_exist?(id)
      bool(tk_send('element', 'exists', tagid(id)))
    end
element_names(*pats)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1267
    def element_names(*pats)
      simplelist(tk_send('element', 'names',
                         *(pats.collect{|pat| tagid(pat)}))).collect{|elem|
        Tk::BLT::PlotComponent::Element.id2obj(self, elem)
      }
    end
element_show(*names)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1273
    def element_show(*names)
      if names.empty?
        simplelist(tk_send('element', 'show'))
      else
        tk_send('element', 'show', *(names.collect{|n| tagid(n)}))
        self
      end
    end
element_type(id)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1281
    def element_type(id)
      tk_send('element', 'type', tagid(id))
    end
gridline_cget(option)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 194
    def gridline_cget(option)
      itemcget('grid', option)
    end
gridline_configinfo(slot=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 200
    def gridline_configinfo(slot=nil)
      itemconfiginfo('grid', slot)
    end
gridline_configure(slot, value=None)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 197
    def gridline_configure(slot, value=None)
      itemconfigure('grid', slot, value)
    end
gridline_off()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1401
    def gridline_off
      tk_send_without_enc('grid', 'off')
      self
    end
gridline_on()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1405
    def gridline_on
      tk_send_without_enc('grid', 'on')
      self
    end
gridline_toggle()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1409
    def gridline_toggle
      tk_send_without_enc('grid', 'toggle')
      self
    end
legend_activate(*pats)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1444
    def legend_activate(*pats)
      list(tk_send('legend', 'activate',
                   *(pats.collect{|pat| tagid(pat)}))).collect{|elem|
        Tk::BLT::PlotComponent::Element.id2obj(self, elem)
      }
    end
legend_bind(tag, context, *args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1148
    def legend_bind(tag, context, *args)
      _component_bind('legend', tag, context, *args)
    end
legend_bind_append(tag, context, *args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1151
    def legend_bind_append(tag, context, *args)
      _component_bind_append('legend', tag, context, *args)
    end
legend_bind_remove(tag, context)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1154
    def legend_bind_remove(tag, context)
      _component_bind_remove('legend', tag, context)
    end
legend_bindinfo(tag, context=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1157
    def legend_bindinfo(tag, context=nil)
      _component_bindinfo('legend', tag, context)
    end
legend_cget(option)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 207
    def legend_cget(option)
      itemcget('legend', option)
    end
legend_configinfo(slot=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 213
    def legend_configinfo(slot=nil)
      itemconfiginfo('legend', slot)
    end
legend_configure(slot, value=None)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 210
    def legend_configure(slot, value=None)
      itemconfigure('legend', slot, value)
    end
legend_deactivate(*pats)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1450
    def legend_deactivate(*pats)
      list(tk_send('legend', 'deactivate',
                   *(pats.collect{|pat| tagid(pat)}))).collect{|elem|
        Tk::BLT::PlotComponent::Element.id2obj(self, elem)
      }
    end
legend_get(pos, y=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1456
    def legend_get(pos, y=nil)
      if y
        Tk::BLT::PlotComponent::Element.id2obj(self,
                                               tk_send('legend', 'get',
                                                       _at(pos, y)))
      else
        Tk::BLT::PlotComponent::Element.id2obj(self,
                                               tk_send('legend', 'get', pos))
      end
    end
legend_window_create(parent=nil, keys=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1416
    def legend_window_create(parent=nil, keys=nil)
      if parent.kind_of?(Hash)
        keys = _symbolkey2str(parent)
        parent = keys.delete('parent')
        widgetname = keys.delete('widgetname')
        keys.delete('without_creating')
      elsif keys
        keys = _symbolkey2str(keys)
        widgetname = keys.delete('widgetname')
        keys.delete('without_creating')
      end

      legend = self.class.new(parent, :without_creating=>true,
                              :widgetname=>widgetname)
      class << legend
        def __destroy_hook__
          TkCore::INTERP.tk_windows.delete(@path)
        end
      end

      if keys
        self.legend_configure(keys.update('position'=>legend))
      else
        self.legend_configure('position'=>legend)
      end
      legend
    end
line_activate(*args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1349
    def line_activate(*args)
      if args.empty?
        list(tk_send('line', 'activate')).collect{|elem|
          Tk::BLT::PlotComponent::Element.id2obj(self, elem)
        }
      else
        # id, *indices
        id = args.shift
        tk_send('line', 'activate', tagid(id), *args)
      end
    end
line_bind(tag, context, *args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1135
    def line_bind(tag, context, *args)
      _component_bind('line', tag, context, *args)
    end
line_bind_append(tag, context, *args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1138
    def line_bind_append(tag, context, *args)
      _component_bind_append('line', tag, context, *args)
    end
line_bind_remove(tag, context)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1141
    def line_bind_remove(tag, context)
      _component_bind_remove('line', tag, context)
    end
line_bindinfo(tag, context=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1144
    def line_bindinfo(tag, context=nil)
      _component_bindinfo('line', tag, context)
    end
line_cget(id, option)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 173
    def line_cget(id, option)
      itemcget(['line', tagid(id)], option)
    end
line_closest(x, y, var, *args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1360
    def line_closest(x, y, var, *args)
      if args[-1].kind_of?(Hash)
        keys = args.pop
        bool(tk_send('line', 'closest', x, y, var,
                     *(hash_kv(keys).concat(args.collect{|id| tagid(id)}))))
      else
        bool(tk_send('line', 'closest', x, y, var,
                     *(args.collect{|id| tagid(id)})))
      end
    end
line_configinfo(id, slot=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 187
    def line_configinfo(id, slot=nil)
      itemconfiginfo(['line', tagid(id)], slot)
    end
line_configure(*args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 176
    def line_configure(*args)
      slot = args.pop
      if slot.kind_of?(Hash)
        value = None
      else
        value = slot
        slot = args.pop
      end
      id_list = args.flatten.collect!{|id| tagid(id)}.unshift('line')
      itemconfigure(id_list, slot, value)
    end
line_create(id=nil, keys={})

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1344
    def line_create(id=nil, keys={})
      # tk_send('line', 'create', tagid(id), keys)
      Tk::BLT::PlotComponent::Line.new(self, tagid(id), keys)
    end
line_deactivate(*ids)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1370
    def line_deactivate(*ids)
      tk_send('line', 'deactivate', *(ids.collect{|id| tagid(id)}))
      self
    end
line_delete(*ids)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1374
    def line_delete(*ids)
      tk_send('line', 'delete', *(ids.collect{|id| tagid(id)}))
      self
    end
line_exist?(id)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1378
    def line_exist?(id)
      bool(tk_send('line', 'exists', tagid(id)))
    end
line_names(*pats)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1381
    def line_names(*pats)
      simplelist(tk_send('line', 'names',
                         *(pats.collect{|pat| tagid(pat)}))).collect{|elem|
        Tk::BLT::PlotComponent::Element.id2obj(self, elem)
      }
    end
line_show(*names)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1387
    def line_show(*names)
      if names.empty?
        simplelist(tk_send('line', 'show'))
      else
        tk_send('line', 'show', *(names.collect{|n| tagid(n)}))
        self
      end
    end
line_type(id)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1395
    def line_type(id)
      tk_send('line', 'type', tagid(id))
    end
marker_after(id, target=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1524
    def marker_after(id, target=nil)
      if target
        tk_send_without_enc('marker', 'after', tagid(id), tagid(target))
      else
        tk_send_without_enc('marker', 'after', tagid(id))
      end
      self
    end
marker_before(id, target=None)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1532
    def marker_before(id, target=None)
      if target
        tk_send_without_enc('marker', 'before', tagid(id), tagid(target))
      else
        tk_send_without_enc('marker', 'before', tagid(id))
      end
      self
    end
marker_bind(tag, context, *args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1161
    def marker_bind(tag, context, *args)
      _component_bind('marker', tag, context, *args)
    end
marker_bind_append(tag, context, *args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1164
    def marker_bind_append(tag, context, *args)
      _component_bind_append('marker', tag, context, *args)
    end
marker_bind_remove(tag, context)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1167
    def marker_bind_remove(tag, context)
      _component_bind_remove('marker', tag, context)
    end
marker_bindinfo(tag, context=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1170
    def marker_bindinfo(tag, context=nil)
      _component_bindinfo('marker', tag, context)
    end
marker_cget(id, option)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 254
    def marker_cget(id, option)
      itemcget(['marker', tagid(id)], option)
    end
marker_configinfo(id, slot=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 268
    def marker_configinfo(id, slot=nil)
      itemconfiginfo(['marker', tagid(id)], slot)
    end
marker_configure(*args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 257
    def marker_configure(*args)
      slot = args.pop
      if slot.kind_of?(Hash)
        value = None
      else
        value = slot
        slot = args.pop
      end
      id_list = args.flatten.collect!{|id| tagid(id)}.unshift('marker')
      itemconfigure(id_list, slot, value)
    end
marker_create(type, keys={})

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1502
    def marker_create(type, keys={})
      case type
      when :text, 'text'
        Tk::BLT::PlotComponent::TextMarker.new(self, keys)
      when :line, 'line'
        Tk::BLT::PlotComponent::LineMarker.new(self, keys)
      when :bitmap, 'bitmap'
        Tk::BLT::PlotComponent::BitmapMarker.new(self, keys)
      when :image, 'image'
        Tk::BLT::PlotComponent::ImageMarker.new(self, keys)
      when :polygon, 'polygon'
        Tk::BLT::PlotComponent::PolygonMarker.new(self, keys)
      when :window, 'window'
        Tk::BLT::PlotComponent::WindowMarker.new(self, keys)
      else
        if type.kind_of?(Tk::BLT::PlotComponent::Marker)
          type.new(self, keys)
        else
          Tk::BLT::PlotComponent::Marker.create_type(self, type, keys)
        end
      end
    end
marker_delete(*ids)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1540
    def marker_delete(*ids)
      tk_send('marker', 'delete', *(ids.collect{|id| tagid(id)}))
      self
    end
marker_exist?(id)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1544
    def marker_exist?(id)
      bool(tk_send('marker', 'exists', tagid(id)))
    end
marker_names(*pats)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1547
    def marker_names(*pats)
      simplelist(tk_send('marker', 'names',
                         *(pats.collect{|pat| tagid(pat)}))).collect{|id|
        Tk::BLT::PlotComponent::Marker.id2obj(self, id)
      }
    end
marker_type(id)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1553
    def marker_type(id)
      tk_send('marker', 'type', tagid(id))
    end
pen_cget(id, option)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 220
    def pen_cget(id, option)
      itemcget(['pen', tagid(id)], option)
    end
pen_configinfo(id, slot=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 234
    def pen_configinfo(id, slot=nil)
      itemconfiginfo(['pen', tagid(id)], slot)
    end
pen_configure(*args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 223
    def pen_configure(*args)
      slot = args.pop
      if slot.kind_of?(Hash)
        value = None
      else
        value = slot
        slot = args.pop
      end
      id_list = args.flatten.collect!{|id| tagid(id)}.unshift('pen')
      itemconfigure(id_list, slot, value)
    end
pen_create(id=nil, keys={})

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1469
    def pen_create(id=nil, keys={})
      # tk_send('pen', 'create', tagid(id), keys)
      Tk::BLT::PlotComponent::Pen.new(self, tagid(id), keys)
    end
pen_delete(*ids)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1473
    def pen_delete(*ids)
      tk_send('pen', 'delete', *(ids.collect{|id| tagid(id)}))
      self
    end
pen_names(*pats)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1477
    def pen_names(*pats)
      simplelist(tk_send('pen', 'names',
                         *(pats.collect{|pat| tagid(pat)}))).collect{|pen|
        Tk::BLT::PlotComponent::Pen.id2obj(self, pen)
      }
    end
postscript_cget(option)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 241
    def postscript_cget(option)
      itemcget('postscript', option)
    end
postscript_configinfo(slot=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 247
    def postscript_configinfo(slot=nil)
      itemconfiginfo('postscript', slot)
    end
postscript_configure(slot, value=None)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 244
    def postscript_configure(slot, value=None)
      itemconfigure('postscript', slot, value)
    end
postscript_output(file=nil, keys={})

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1486
    def postscript_output(file=nil, keys={})
      if file.kind_of?(Hash)
        keys = file
        file = nil
      end

      if file
        tk_send('postscript', 'output', file, keys)
        self
      else
        tk_send('postscript', 'output', keys)
      end
    end
tagid(tag)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1053
    def tagid(tag)
      if tag.kind_of?(Axis) ||
          tag.kind_of?(Crosshairs) ||
          tag.kind_of?(Element) ||
          tag.kind_of?(GridLine) ||
          tag.kind_of?(Legend) ||
          tag.kind_of?(Pen) ||
          tag.kind_of?(Postscript) ||
          tag.kind_of?(Marker)
        tag.id
      else
        tag  # maybe an Array of configure paramters
      end
    end
x2axis_bind(context, *args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1653
    def x2axis_bind(context, *args)
      if TkComm._callback_entry?(args[0]) || !block_given?
        cmd = args.shift
      else
        cmd = Proc.new
      end
      _bind([path, 'x2axis', 'bind'], context, cmd, *args)
      self
    end
x2axis_bind_append(context, *args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1662
    def x2axis_bind_append(context, *args)
      if TkComm._callback_entry?(args[0]) || !block_given?
        cmd = args.shift
      else
        cmd = Proc.new
      end
      _bind_append([path, 'x2axis', 'bind'], context, cmd, *args)
      self
    end
x2axis_bind_remove(context)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1671
    def x2axis_bind_remove(context)
      _bind_remove([path, 'x2axis', 'bind'], context)
      self
    end
x2axis_bindinfo(context=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1675
    def x2axis_bindinfo(context=nil)
      _bindinfo([path, 'x2axis', 'bind'], context)
    end
x2axis_cget(option)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1628
    def x2axis_cget(option)
      itemcget('x2axis', option)
    end
x2axis_configinfo(slot=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1647
    def x2axis_configinfo(slot=nil)
      itemconfiginfo('x2axis', slot)
    end
x2axis_configure(slot, value=None)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1631
    def x2axis_configure(slot, value=None)
      if slot.kind_of?(Hash)
        slot = _symbolkey2str(slot)
        if cmd = slot.delete('command')
          slot['command'] = proc{|w, tick|
            cmd.call(TkComm.window(w), TkComm.num_or_str(tick))
          }
        end
      elsif slot == :command || slot == 'command'
        cmd = value
        value = proc{|w, tick|
          cmd.call(TkComm.window(w), TkComm.num_or_str(tick))
        }
      end
      itemconfigure('x2axis', slot, value)
    end
x2axis_invtransform(val)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1678
    def x2axis_invtransform(val)
      list(tk_send('x2axis', 'invtransform', val))
    end
x2axis_limits()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1681
    def x2axis_limits
      list(tk_send('x2axis', 'limits'))
    end
x2axis_transform(val)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1684
    def x2axis_transform(val)
      list(tk_send('x2axis', 'transform', val))
    end
x2axis_use(target=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1687
    def x2axis_use(target=nil)
      if target
        Tk::BLT::PlotComponent::Axis.id2obj(self,
                                            tk_send('x2axis', 'use',
                                                    tagid(target)))
      else
        Tk::BLT::PlotComponent::Axis.id2obj(self, tk_send('x2axis', 'use'))
      end
    end
xaxis_bind(context, *args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1584
    def xaxis_bind(context, *args)
      if TkComm._callback_entry?(args[0]) || !block_given?
        cmd = args.shift
      else
        cmd = Proc.new
      end
      _bind([path, 'xaxis', 'bind'], context, cmd, *args)
      self
    end
xaxis_bind_append(context, *args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1593
    def xaxis_bind_append(context, *args)
      if TkComm._callback_entry?(args[0]) || !block_given?
        cmd = args.shift
      else
        cmd = Proc.new
      end
      _bind_append([path, 'xaxis', 'bind'], context, cmd, *args)
      self
    end
xaxis_bind_remove(context)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1602
    def xaxis_bind_remove(context)
      _bind_remove([path, 'xaxis', 'bind'], context)
      self
    end
xaxis_bindinfo(context=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1606
    def xaxis_bindinfo(context=nil)
      _bindinfo([path, 'xaxis', 'bind'], context)
    end
xaxis_cget(option)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1559
    def xaxis_cget(option)
      itemcget('xaxis', option)
    end
xaxis_configinfo(slot=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1578
    def xaxis_configinfo(slot=nil)
      itemconfiginfo('xaxis', slot)
    end
xaxis_configure(slot, value=None)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1562
    def xaxis_configure(slot, value=None)
      if slot.kind_of?(Hash)
        slot = _symbolkey2str(slot)
        if cmd = slot.delete('command')
          slot['command'] = proc{|w, tick|
            cmd.call(TkComm.window(w), TkComm.num_or_str(tick))
          }
        end
      elsif slot == :command || slot == 'command'
        cmd = value
        value = proc{|w, tick|
          cmd.call(TkComm.window(w), TkComm.num_or_str(tick))
        }
      end
      itemconfigure('xaxis', slot, value)
    end
xaxis_invtransform(val)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1609
    def xaxis_invtransform(val)
      list(tk_send('xaxis', 'invtransform', val))
    end
xaxis_limits()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1612
    def xaxis_limits
      list(tk_send('xaxis', 'limits'))
    end
xaxis_transform(val)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1615
    def xaxis_transform(val)
      list(tk_send('xaxis', 'transform', val))
    end
xaxis_use(target=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1618
    def xaxis_use(target=nil)
      if target
        Tk::BLT::PlotComponent::Axis.id2obj(self,
                                            tk_send('xaxis', 'use',
                                                    tagid(target)))
      else
        Tk::BLT::PlotComponent::Axis.id2obj(self, tk_send('xaxis', 'use'))
      end
    end
y2axis_bind(context, *args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1791
    def y2axis_bind(context, *args)
      if TkComm._callback_entry?(args[0]) || !block_given?
        cmd = args.shift
      else
        cmd = Proc.new
      end
      _bind([path, 'y2axis', 'bind'], context, cmd, *args)
      self
    end
y2axis_bind_append(context, *args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1800
    def y2axis_bind_append(context, *args)
      if TkComm._callback_entry?(args[0]) || !block_given?
        cmd = args.shift
      else
        cmd = Proc.new
      end
      _bind_append([path, 'y2axis', 'bind'], context, cmd, *args)
      self
    end
y2axis_bind_remove(context)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1809
    def y2axis_bind_remove(context)
      _bind_remove([path, 'y2axis', 'bind'], context)
      self
    end
y2axis_bindinfo(context=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1813
    def y2axis_bindinfo(context=nil)
      _bindinfo([path, 'y2axis', 'bind'], context)
    end
y2axis_cget(option)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1766
    def y2axis_cget(option)
      itemcget('y2axis', option)
    end
y2axis_configinfo(slot=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1785
    def y2axis_configinfo(slot=nil)
      axis_configinfo('y2axis', slot)
    end
y2axis_configure(slot, value=None)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1769
    def y2axis_configure(slot, value=None)
      if slot.kind_of?(Hash)
        slot = _symbolkey2str(slot)
        if cmd = slot.delete('command')
          slot['command'] = proc{|w, tick|
            cmd.call(TkComm.window(w), TkComm.num_or_str(tick))
          }
        end
      elsif slot == :command || slot == 'command'
        cmd = value
        value = proc{|w, tick|
          cmd.call(TkComm.window(w), TkComm.num_or_str(tick))
        }
      end
      itemconfigure('y2axis', slot, value)
    end
y2axis_invtransform(val)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1816
    def y2axis_invtransform(val)
      list(tk_send('y2axis', 'invtransform', val))
    end
y2axis_limits()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1819
    def y2axis_limits
      list(tk_send('y2axis', 'limits'))
    end
y2axis_transform(val)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1822
    def y2axis_transform(val)
      list(tk_send('y2axis', 'transform', val))
    end
y2axis_use(target=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1825
    def y2axis_use(target=nil)
      if target
        Tk::BLT::PlotComponent::Axis.id2obj(self,
                                            tk_send('y2axis', 'use',
                                                    tagid(target)))
      else
        Tk::BLT::PlotComponent::Axis.id2obj(self, tk_send('y2axis', 'use'))
      end
    end
yaxis_bind(context, *args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1722
    def yaxis_bind(context, *args)
      if TkComm._callback_entry?(args[0]) || !block_given?
        cmd = args.shift
      else
        cmd = Proc.new
      end
      _bind([path, 'yaxis', 'bind'], context, cmd, *args)
      self
    end
yaxis_bind_append(context, *args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1731
    def yaxis_bind_append(context, *args)
      if TkComm._callback_entry?(args[0]) || !block_given?
        cmd = args.shift
      else
        cmd = Proc.new
      end
      _bind_append([path, 'yaxis', 'bind'], context, cmd, *args)
      self
    end
yaxis_bind_remove(context)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1740
    def yaxis_bind_remove(context)
      _bind_remove([path, 'yaxis', 'bind'], context)
      self
    end
yaxis_bindinfo(context=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1744
    def yaxis_bindinfo(context=nil)
      _bindinfo([path, 'yaxis', 'bind'], context)
    end
yaxis_cget(option)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1697
    def yaxis_cget(option)
      itemcget('yaxis', option)
    end
yaxis_configinfo(slot=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1716
    def yaxis_configinfo(slot=nil)
      itemconfiginfo('yaxis', slot)
    end
yaxis_configure(slot, value=None)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1700
    def yaxis_configure(slot, value=None)
      if slot.kind_of?(Hash)
        slot = _symbolkey2str(slot)
        if cmd = slot.delete('command')
          slot['command'] = proc{|w, tick|
            cmd.call(TkComm.window(w), TkComm.num_or_str(tick))
          }
        end
      elsif slot == :command || slot == 'command'
        cmd = value
        value = proc{|w, tick|
          cmd.call(TkComm.window(w), TkComm.num_or_str(tick))
        }
      end
      itemconfigure('yaxis', slot, value)
    end
yaxis_invtransform(val)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1747
    def yaxis_invtransform(val)
      list(tk_send('yaxis', 'invtransform', val))
    end
yaxis_limits()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1750
    def yaxis_limits
      list(tk_send('yaxis', 'limits'))
    end
yaxis_transform(val)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1753
    def yaxis_transform(val)
      list(tk_send('yaxis', 'transform', val))
    end
yaxis_use(target=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1756
    def yaxis_use(target=nil)
      if target
        Tk::BLT::PlotComponent::Axis.id2obj(self,
                                            tk_send('yaxis', 'use',
                                                    tagid(target)))
      else
        Tk::BLT::PlotComponent::Axis.id2obj(self, tk_send('yaxis', 'use'))
      end
    end


Class: Tk::BLT::PlotComponent::Axis

Class | Tk::BLT::PlotComponent::Axis
In: | tk/lib/tkextlib/blt/component.rb
Parent: | TkObject

Methods

cget command configinfo configure current_configinfo delete id id2obj invtransform limits name new new to_eval transform use use_as view

Constants

OBJ_ID | = | ['blt_chart_axis'.freeze, '00000'.taint].freeze
OBJ_TBL | = | {}

Public Class methods

id2obj(chart, id)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 333
      def self.id2obj(chart, id)
        cpath = chart.path
        return id unless OBJ_TBL[cpath]
        OBJ_TBL[cpath][id]? OBJ_TBL[cpath][id]: id
      end
new(chart, axis=nil, keys={})

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 349
      def initialize(chart, axis=nil, keys={})
        if axis.kind_of?(Hash)
          keys = axis
          axis = nil
        end
        if axis
          @axis = @id = axis.to_s
        else
          @axis = @id = OBJ_ID.join(TkCore::INTERP._ip_id_).freeze
          OBJ_ID[1].succ!
        end
        @path = @id
        @parent = @chart = chart
        @cpath = @chart.path
        Axis::OBJ_TBL[@cpath][@axis] = self
        keys = _symbolkey2str(keys)
        unless keys.delete('without_creating')
          # @chart.axis_create(@axis, keys)
          tk_call(@chart, 'axis', 'create', @axis, keys)
        end
      end
new(chart, axis=nil, keys={})

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 339
      def self.new(chart, axis=nil, keys={})
        if axis.kind_of?(Hash)
          keys = axis
          axis = nil
        end
        OBJ_TBL[chart.path] = {} unless OBJ_TBL[chart.path]
        return OBJ_TBL[chart.path][axis] if axis && OBJ_TBL[chart.path][axis]
        super(chart, axis, keys)
      end

Public Instance methods

cget(option)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 379
      def cget(option)
        @chart.axis_cget(@id, option)
      end
command(cmd=nil, &b)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 393
      def command(cmd=nil, &b)
        if cmd
          configure('command', cmd)
        elsif b
          configure('command', Proc.new(&b))
        else
          cget('command')
        end
      end
configinfo(key=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 386
      def configinfo(key=nil)
        @chart.axis_configinfo(@id, key)
      end
configure(key, value=None)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 382
      def configure(key, value=None)
        @chart.axis_configure(@id, key, value)
        self
      end
current_configinfo(key=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 389
      def current_configinfo(key=nil)
        @chart.current_axis_configinfo(@id, key)
      end
delete()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 403
      def delete
        @chart.axis_delete(@id)
        self
      end
id()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 371
      def id
        @id
      end
invtransform(val)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 408
      def invtransform(val)
        @chart.axis_invtransform(@id, val)
      end
limits()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 412
      def limits
        @chart.axis_limits(@id)
      end
name()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 416
      def name
        @axis
      end
to_eval()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 375
      def to_eval
        @id
      end
transform(val)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 420
      def transform(val)
        @chart.axis_transform(@id, val)
      end
use(name=None)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 429
      def use(name=None) # if @id == xaxis | x2axis | yaxis | y2axis
        @chart.axis_use(@id, name)
      end
use_as(axis)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 433
      def use_as(axis) # axis := xaxis | x2axis | yaxis | y2axis
        @chart.axis_use(axis, @id)
      end
view()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 424
      def view
        @chart.axis_view(@id)
        self
      end


Class: Tk::BLT::PlotComponent::Bar

Class | Tk::BLT::PlotComponent::Bar
In: | tk/lib/tkextlib/blt/component.rb
Parent: | Element

Constants

ElementTypeName = 'bar'.freeze


Class: Tk::BLT::PlotComponent::BitmapMarker

Class | Tk::BLT::PlotComponent::BitmapMarker
In: | tk/lib/tkextlib/blt/component.rb
Parent: | Marker

Constants

MarkerTypeName = 'bitmap'.freeze


Class: Tk::BLT::PlotComponent::Crosshairs

Class | Tk::BLT::PlotComponent::Crosshairs
In: | tk/lib/tkextlib/blt/component.rb
Parent: | TkObject

Methods

cget configinfo configure current_configinfo id new new off on to_eval toggle

Constants

OBJ_TBL = {}

Public Class methods

new(chart, keys={})

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 443
      def self.new(chart, keys={})
        return OBJ_TBL[chart.path] if OBJ_TBL[chart.path]
        super(chart, keys)
      end
new(chart, keys={})

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 448
      def initialize(chart, keys={})
        @parent = @chart = chart
        @cpath = @chart.path
        Crosshairs::OBJ_TBL[@cpath] = self
        @chart.crosshair_configure(keys) unless keys.empty?
        @path = @id = 'crosshairs'
      end

Public Instance methods

cget(option)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 464
      def cget(option)
        @chart.crosshair_cget(option)
      end
configinfo(key=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 471
      def configinfo(key=nil)
        @chart.crosshair_configinfo(key)
      end
configure(key, value=None)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 467
      def configure(key, value=None)
        @chart.crosshair_configure(key, value)
        self
      end
current_configinfo(key=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 474
      def current_configinfo(key=nil)
        @chart.current_crosshair_configinfo(key)
      end
id()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 456
      def id
        @id
      end
off()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 478
      def off
        @chart.crosshair_off
        self
      end
on()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 482
      def on
        @chart.crosshair_on
        self
      end
to_eval()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 460
      def to_eval
        @id
      end
toggle()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 486
      def toggle
        @chart.crosshair_toggle
        self
      end


Class: Tk::BLT::PlotComponent::Element

Class | Tk::BLT::PlotComponent::Element
In: | tk/lib/tkextlib/blt/component.rb
Parent: | TkObject

Methods

activate cget closest configinfo configure current_configinfo deactivate delete exist? id id2obj name new new to_eval type type2class

Constants

ElementTypeName | = | 'element'
ElementTypeToClass | = | { ElementTypeName=>self }
ElementID_TBL | = | TkCore::INTERP.create_table
OBJ_ID | = | ['blt_chart_element'.freeze, '00000'.taint].freeze
OBJ_TBL | = | {}

Public Class methods

id2obj(chart, id)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 514
      def Element.id2obj(chart, id)
        cpath = chart.path
        return id unless OBJ_TBL[cpath]
        OBJ_TBL[cpath][id]? OBJ_TBL[cpath][id]: id
      end
new(chart, element=nil, keys={})

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 532
      def initialize(chart, element=nil, keys={})
        if element.kind_of?(Hash)
          keys = element
          element = nil
        end
        if element
          @element = @id = element.to_s
        else
          @element = @id = OBJ_ID.join(TkCore::INTERP._ip_id_).freeze
          OBJ_ID[1].succ!
        end
        @path = @id
        @parent = @chart = chart
        @cpath = @chart.path
        @typename = self.class::ElementTypeName
        Element::OBJ_TBL[@cpath][@element] = self
        keys = _symbolkey2str(keys)
        unless keys.delete('without_creating')
          # @chart.element_create(@element, keys)
          tk_call(@chart, @typename, 'create', @element, keys)
        end
      end
new(chart, element=nil, keys={})

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 520
      def self.new(chart, element=nil, keys={})
        if element.kind_of?(Hash)
          keys = element
          element = nil
        end
        OBJ_TBL[chart.path] = {} unless OBJ_TBL[chart.path]
        if element && OBJ_TBL[chart.path][element]
          return OBJ_TBL[chart.path][element]
        end
        super(chart, element, keys)
      end
type2class(type)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 510
      def Element.type2class(type)
        ElementTypeToClass[type]
      end

Public Instance methods

activate(*args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 581
      def activate(*args)
        @chart.element_activate(@id, *args)
      end
cget(option)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 563
      def cget(option)
        # @chart.element_cget(@id, option)
        @chart.__send__(@typename + '_cget', @id, option)
      end
closest(x, y, var, keys={})

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 585
      def closest(x, y, var, keys={})
        # @chart.element_closest(x, y, var, @id, keys)
        @chart.__send__(@typename + '_closest', x, y, var, @id, keys)
      end
configinfo(key=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 572
      def configinfo(key=nil)
        # @chart.element_configinfo(@id, key)
        @chart.__send__(@typename + '_configinfo', @id, key)
      end
configure(key, value=None)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 567
      def configure(key, value=None)
        # @chart.element_configure(@id, key, value)
        @chart.__send__(@typename + '_configure', @id, key, value)
        self
      end
current_configinfo(key=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 576
      def current_configinfo(key=nil)
        # @chart.current_element_configinfo(@id, key)
        @chart.__send__('current_' << @typename << '_configinfo', @id, key)
      end
deactivate()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 590
      def deactivate
        @chart.element_deactivate(@id)
        self
      end
delete()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 595
      def delete
        @chart.element_delete(@id)
        self
      end
exist?()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 600
      def exist?
        @chart.element_exist?(@id)
      end
id()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 555
      def id
        @id
      end
name()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 604
      def name
        @element
      end
to_eval()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 559
      def to_eval
        @id
      end
type()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 608
      def type
        @chart.element_type(@id)
      end


Class: Tk::BLT::PlotComponent::GridLine

Class | Tk::BLT::PlotComponent::GridLine
In: | tk/lib/tkextlib/blt/component.rb
Parent: | TkObject

Methods

cget configinfo configure current_configinfo id new new off on to_eval toggle

Constants

OBJ_TBL = {}

Public Class methods

new(chart, keys={})

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 627
      def self.new(chart, keys={})
        return OBJ_TBL[chart.path] if OBJ_TBL[chart.path]
        super(chart, keys)
      end
new(chart, keys={})

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 632
      def initialize(chart, keys={})
        @parent = @chart = chart
        @cpath = @chart.path
        GridLine::OBJ_TBL[@cpath] = self
        @chart.gridline_configure(keys) unless keys.empty?
        @path = @id = 'grid'
      end

Public Instance methods

cget(option)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 648
      def cget(option)
        @chart.gridline_cget(option)
      end
configinfo(key=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 655
      def configinfo(key=nil)
        @chart.gridline_configinfo(key)
      end
configure(key, value=None)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 651
      def configure(key, value=None)
        @chart.gridline_configure(key, value)
        self
      end
current_configinfo(key=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 658
      def current_configinfo(key=nil)
        @chart.current_gridline_configinfo(key)
      end
id()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 640
      def id
        @id
      end
off()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 662
      def off
        @chart.gridline_off
        self
      end
on()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 666
      def on
        @chart.gridline_on
        self
      end
to_eval()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 644
      def to_eval
        @id
      end
toggle()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 670
      def toggle
        @chart.gridline_toggle
        self
      end


Class: Tk::BLT::PlotComponent::ImageMarker

Class | Tk::BLT::PlotComponent::ImageMarker
In: | tk/lib/tkextlib/blt/component.rb
Parent: | Marker

Constants

MarkerTypeName = 'image'.freeze


Class: Tk::BLT::PlotComponent::Legend

Class | Tk::BLT::PlotComponent::Legend
In: | tk/lib/tkextlib/blt/component.rb
Parent: | TkObject

Methods

activate cget configinfo configure current_configinfo deactivate get id new new to_eval

Constants

OBJ_TBL = {}

Public Class methods

new(chart, keys={})

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 681
      def self.new(chart, keys={})
        return OBJ_TBL[chart.path] if OBJ_TBL[chart.path]
        super(chart, keys)
      end
new(chart, keys={})

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 686
      def initialize(chart, keys={})
        @parent = @chart = chart
        @cpath = @chart.path
        Crosshairs::OBJ_TBL[@cpath] = self
        @chart.crosshair_configure(keys) unless keys.empty?
        @path = @id = 'legend'
      end

Public Instance methods

activate(*args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 716
      def activate(*args)
        @chart.legend_activate(*args)
      end
cget(option)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 702
      def cget(option)
        @chart.legend_cget(option)
      end
configinfo(key=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 709
      def configinfo(key=nil)
        @chart.legend_configinfo(key)
      end
configure(key, value=None)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 705
      def configure(key, value=None)
        @chart.legend_configure(key, value)
        self
      end
current_configinfo(key=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 712
      def current_configinfo(key=nil)
        @chart.current_legend_configinfo(key)
      end
deactivate(*args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 720
      def deactivate(*args)
        @chart.legend_deactivate(*args)
      end
get(pos, y=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 724
      def get(pos, y=nil)
        @chart.legend_get(pos, y)
      end
id()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 694
      def id
        @id
      end
to_eval()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 698
      def to_eval
        @id
      end


Class: Tk::BLT::PlotComponent::Line

Class | Tk::BLT::PlotComponent::Line
In: | tk/lib/tkextlib/blt/component.rb
Parent: | Element

Constants

ElementTypeName = 'line'.freeze


Class: Tk::BLT::PlotComponent::LineMarker

Class | Tk::BLT::PlotComponent::LineMarker
In: | tk/lib/tkextlib/blt/component.rb
Parent: | Marker

Constants

MarkerTypeName = 'line'.freeze


Class: Tk::BLT::PlotComponent::Marker

Class | Tk::BLT::PlotComponent::Marker
In: | tk/lib/tkextlib/blt/component.rb
Parent: | TkObject

Methods

after before cget configinfo configure create create_type current_configinfo delete exist? id id2obj new to_eval type type2class

Constants

MarkerTypeName | = | nil
MarkerTypeToClass | = | {}
MarkerID_TBL | = | TkCore::INTERP.create_table

Public Class methods

create(chart, keys={})

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 924
      def self.create(chart, keys={})
        unless self::MarkerTypeName
          fail RuntimeError, "#{self} is an abstract class"
        end
        args, fontkeys = _parse_create_args(keys)
        idnum = tk_call_without_enc(chart.path, 'marker', 'create',
                                    self::MarkerTypeName, *args)
        chart.marker_configure(idnum, fontkeys) unless fontkeys.empty?
        idnum.to_i  # 'item id' is an integer number
      end
create_type(chart, type, keys={})

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 935
      def self.create_type(chart, type, keys={})
        args, fontkeys = _parse_create_args(keys)
        idnum = tk_call_without_enc(chart.path, 'marker', 'create',
                                    type, *args)
        chart.marker_configure(idnum, fontkeys) unless fontkeys.empty?
        id = idnum.to_i  # 'item id' is an integer number
        obj = self.allocate
        obj.instance_eval{
          @parent = @chart = chart
          @cpath = chart.path
          @id = id
          unless Tk::BLT::PlotComponent::Marker::MarkerID_TBL[@cpath]
            Tk::BLT::PlotComponent::Marker::MarkerID_TBL[@cpath] = {}
          end
          Tk::BLT::PlotComponent::Marker::MarkerID_TBL[@cpath][@id] = self
        }
        obj
      end
id2obj(chart, id)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 879
      def Marker.id2obj(chart, id)
        cpath = chart.path
        return id unless MarkerID_TBL[cpath]
        MarkerID_TBL[cpath][id]? MarkerID_TBL[cpath][id]: id
      end
new(parent, *args)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 954
      def initialize(parent, *args)
        @parent = @chart = parent
        @cpath = parent.path

        @path = @id = create_self(*args) # an integer number as 'item id'
        unless Tk::BLT::PlotComponent::Marker::MarkerID_TBL[@cpath]
          Tk::BLT::PlotComponent::Marker::MarkerID_TBL[@cpath] = {}
        end
        Tk::BLT::PlotComponent::Marker::MarkerID_TBL[@cpath][@id] = self
      end
type2class(type)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 875
      def Marker.type2class(type)
        MarkerTypeToClass[type]
      end

Public Instance methods

after(target=None)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 991
      def after(target=None)
        @chart.marker_after(@id, target)
      end
before(target=None)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 995
      def before(target=None)
        @chart.marker_before(@id, target)
      end
cget(option)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 977
      def cget(option)
        @chart.marker_cget(@id, option)
      end
configinfo(key=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 984
      def configinfo(key=nil)
        @chart.marker_configinfo(@id, key)
      end
configure(key, value=None)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 980
      def configure(key, value=None)
        @chart.marker_configure(@id, key, value)
        self
      end
current_configinfo(key=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 987
      def current_configinfo(key=nil)
        @chart.current_marker_configinfo(@id, key)
      end
delete()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 999
      def delete
        @chart.marker_delete(@id)
      end
exist?()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1003
      def exist?
        @chart.marker_exist(@id)
      end
id()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 969
      def id
        @id
      end
to_eval()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 973
      def to_eval
        @id
      end
type()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 1007
      def type
        @chart.marker_type(@id)
      end


Module: Tk::BLT::PlotComponent::OptKeys

Module | Tk::BLT::PlotComponent::OptKeys
In: | tk/lib/tkextlib/blt/component.rb


Class: Tk::BLT::PlotComponent::Pen

Class | Tk::BLT::PlotComponent::Pen
In: | tk/lib/tkextlib/blt/component.rb
Parent: | TkObject

Methods

cget configinfo configure current_configinfo delete id id2obj name new new to_eval

Constants

OBJ_ID | = | ['blt_chart_pen'.freeze, '00000'.taint].freeze
OBJ_TBL | = | {}

Public Class methods

id2obj(chart, id)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 735
      def self.id2obj(chart, id)
        cpath = chart.path
        return id unless OBJ_TBL[cpath]
        OBJ_TBL[cpath][id]? OBJ_TBL[cpath][id]: id
      end
new(chart, pen=nil, keys={})

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 751
      def initialize(chart, pen=nil, keys={})
        if pen.kind_of?(Hash)
          keys = pen
          pen = nil
        end
        if pen
          @pen = @id = pen.to_s
        else
          @pen = @id = OBJ_ID.join(TkCore::INTERP._ip_id_).freeze
          OBJ_ID[1].succ!
        end
        @path = @id
        @parent = @chart = chart
        @cpath = @chart.path
        Pen::OBJ_TBL[@cpath][@pen] = self
        keys = _symbolkey2str(keys)
        unless keys.delete('without_creating')
          # @chart.pen_create(@pen, keys)
          tk_call(@chart, 'pen', 'create', @pen, keys)
        end
      end
new(chart, pen=nil, keys={})

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 741
      def self.new(chart, pen=nil, keys={})
        if pen.kind_of?(Hash)
          keys = pen
          pen = nil
        end
        OBJ_TBL[chart.path] = {} unless OBJ_TBL[chart.path]
        return OBJ_TBL[chart.path][pen] if pen && OBJ_TBL[chart.path][pen]
        super(chart, pen, keys)
      end

Public Instance methods

cget(option)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 781
      def cget(option)
        @chart.pen_cget(@id, option)
      end
configinfo(key=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 788
      def configinfo(key=nil)
        @chart.pen_configinfo(@id, key)
      end
configure(key, value=None)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 784
      def configure(key, value=None)
        @chart.pen_configure(@id, key, value)
        self
      end
current_configinfo(key=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 791
      def current_configinfo(key=nil)
        @chart.current_pen_configinfo(@id, key)
      end
delete()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 795
      def delete
        @chart.pen_delete(@id)
        self
      end
id()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 773
      def id
        @id
      end
name()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 800
      def name
        @pen
      end
to_eval()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 777
      def to_eval
        @id
      end


Class: Tk::BLT::PlotComponent::PolygonMarker

Class | Tk::BLT::PlotComponent::PolygonMarker
In: | tk/lib/tkextlib/blt/component.rb
Parent: | Marker

Constants

MarkerTypeName = 'polygon'.freeze


Class: Tk::BLT::PlotComponent::Postscript

Class | Tk::BLT::PlotComponent::Postscript
In: | tk/lib/tkextlib/blt/component.rb
Parent: | TkObject

Methods

cget configinfo configure current_configinfo id new new output to_eval

Constants

OBJ_TBL = {}

Public Class methods

new(chart, keys={})

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 810
      def self.new(chart, keys={})
        return OBJ_TBL[chart.path] if OBJ_TBL[chart.path]
        super(chart, keys)
      end
new(chart, keys={})

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 815
      def initialize(chart, keys={})
        @parent = @chart = chart
        @cpath = @chart.path
        Postscript::OBJ_TBL[@cpath] = self
        @chart.postscript_configure(keys) unless keys.empty?
        @path = @id = 'postscript'
      end

Public Instance methods

cget(option)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 831
      def cget(option)
        @chart.postscript_cget(option)
      end
configinfo(key=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 838
      def configinfo(key=nil)
        @chart.postscript_configinfo(key)
      end
configure(key, value=None)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 834
      def configure(key, value=None)
        @chart.postscript_configure(key, value)
        self
      end
current_configinfo(key=nil)

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 841
      def current_configinfo(key=nil)
        @chart.current_postscript_configinfo(key)
      end
id()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 823
      def id
        @id
      end
output(file=nil, keys={})

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 845
      def output(file=nil, keys={})
        if file.kind_of?(Hash)
          keys = file
          file = nil
        end

        ret = @chart.postscript_output(file, keys)

        if file
          self
        else
          ret
        end
      end
to_eval()

[Source]

# File tk/lib/tkextlib/blt/component.rb, line 827
      def to_eval
        @id
      end


Class: Tk::BLT::PlotComponent::TextMarker

Class | Tk::BLT::PlotComponent::TextMarker
In: | tk/lib/tkextlib/blt/component.rb
Parent: | Marker

Constants

MarkerTypeName = 'text'.freeze


Class: Tk::BLT::PlotComponent::WindowMarker

Class | Tk::BLT::PlotComponent::WindowMarker
In: | tk/lib/tkextlib/blt/component.rb
Parent: | Marker

Constants

MarkerTypeName = 'window'.freeze


Class: Tk::BLT::Printer

Class | Tk::BLT::Printer
In: | tk/lib/tkextlib/blt/win_printer.rb
Parent: | TkObject

Methods

close enum get_attrs names new open set_attrs snap write write_with_title

Constants

TkCommandNames = ['::blt::printer'.freeze].freeze

Public Class methods

enum(attribute)

[Source]

# File tk/lib/tkextlib/blt/win_printer.rb, line 18
    def self.enum(attribute)
      simplelist(tk_call('::blt::printer', 'enum', attribute))
    end
names(pat=None)

[Source]

# File tk/lib/tkextlib/blt/win_printer.rb, line 22
    def self.names(pat=None)
      simplelist(tk_call('::blt::printer', 'names', pat))
    end
new(printer)

[Source]

# File tk/lib/tkextlib/blt/win_printer.rb, line 32
    def initialize(printer)
      @printer_id = tk_call('::blt::printer', 'open', printer)
    end
open(printer)

[Source]

# File tk/lib/tkextlib/blt/win_printer.rb, line 26
    def self.open(printer)
      self.new(printer)
    end

Public Instance methods

close()

[Source]

# File tk/lib/tkextlib/blt/win_printer.rb, line 36
    def close
      tk_call('::blt::print', 'close', @printer_id)
      self
    end
get_attrs(var)

[Source]

# File tk/lib/tkextlib/blt/win_printer.rb, line 40
    def get_attrs(var)
      tk_call('::blt::print', 'getattrs', @printer_id, var)
      var
    end
set_attrs(var)

[Source]

# File tk/lib/tkextlib/blt/win_printer.rb, line 44
    def set_attrs(var)
      tk_call('::blt::print', 'setattrs', @printer_id, var)
      self
    end
snap(win)

[Source]

# File tk/lib/tkextlib/blt/win_printer.rb, line 48
    def snap(win)
      tk_call('::blt::print', 'snap', @printer_id, win)
      self
    end
write(str)

[Source]

# File tk/lib/tkextlib/blt/win_printer.rb, line 52
    def write(str)
      tk_call('::blt::print', 'write', @printer_id, str)
      self
    end
write_with_title(title, str)

[Source]

# File tk/lib/tkextlib/blt/win_printer.rb, line 56
    def write_with_title(title, str)
      tk_call('::blt::print', 'write', @printer_id, title, str)
      self
    end


Module: Tk::BLT::Spline

Module | Tk::BLT::Spline
In: | tk/lib/tkextlib/blt/spline.rb

Methods

natural quadratic

Constants

TkCommandNames = ['::blt::spline'.freeze].freeze

Public Class methods

natural(x, y, sx, sy)

[Source]

# File tk/lib/tkextlib/blt/spline.rb, line 15
    def self.natural(x, y, sx, sy)
      tk_call('::blt::spline', 'natural', x, y, sx, sy)
    end
quadratic(x, y, sx, sy)

[Source]

# File tk/lib/tkextlib/blt/spline.rb, line 19
    def self.quadratic(x, y, sx, sy)
      tk_call('::blt::spline', 'quadratic', x, y, sx, sy)
    end


Class: Tk::BLT::Stripchart

Class | Tk::BLT::Stripchart
In: | tk/lib/tkextlib/blt/stripchart.rb
Parent: | TkWindow

Methods

extents inside invtransform metafile snap transform

Included Modules

PlotComponent GraphCommand

Constants

TkCommandNames | = | ['::blt::stripchart'.freeze].freeze
WidgetClassName | = | 'Stripchart'.freeze

Public Instance methods

extents(item)

[Source]

# File tk/lib/tkextlib/blt/stripchart.rb, line 47
    def extents(item)
      num_or_str(tk_send_without_enc('extents', item))
    end
inside(x, y)

[Source]

# File tk/lib/tkextlib/blt/stripchart.rb, line 55
    def inside(x, y)
      bool(tk_send_without_enc('inside', x, y))
    end
invtransform(x, y)

[Source]

# File tk/lib/tkextlib/blt/stripchart.rb, line 51
    def invtransform(x, y)
      list(tk_send_without_enc('invtransform', x, y))
    end
metafile(file=None)

[Source]

# File tk/lib/tkextlib/blt/stripchart.rb, line 59
    def metafile(file=None)
      # Windows only
      tk_send('metafile', file)
      self
    end
snap(output, keys={})

[Source]

# File tk/lib/tkextlib/blt/stripchart.rb, line 65
    def snap(output, keys={})
      tk_send_without_enc('snap', *(hash_kv(keys, false) + output))
      self
    end
transform(x, y)

[Source]

# File tk/lib/tkextlib/blt/stripchart.rb, line 70
    def transform(x, y)
      list(tk_send_without_enc('transform', x, y))
    end


Module: Tk::BLT::Table

Module | Tk::BLT::Table
In: | tk/lib/tkextlib/blt/table.rb

Included Modules

Tk

Classes and Modules

Module Tk::BLT::Table::TableContainer

Constants

TkCommandNames = ['::blt::table'.freeze].freeze


Module: Tk::BLT::Table::TableContainer

Module | Tk::BLT::Table::TableContainer
In: | tk/lib/tkextlib/blt/table.rb

Methods

blt_table_add blt_table_arrange blt_table_cget blt_table_configinfo blt_table_configure blt_table_current_configinfo blt_table_current_itemconfiginfo blt_table_delete blt_table_extents blt_table_insert blt_table_insert_after blt_table_insert_before blt_table_itemcget blt_table_itemconfiginfo blt_table_itemconfigure blt_table_iteminfo blt_table_join blt_table_locate blt_table_save blt_table_search blt_table_split

Public Instance methods

blt_table_add(*args)

[Source]

# File tk/lib/tkextlib/blt/table.rb, line 19
      def blt_table_add(*args)
        Tk::BLT::Table.add(@path, *args)
        self
      end
blt_table_arrange()

[Source]

# File tk/lib/tkextlib/blt/table.rb, line 24
      def blt_table_arrange()
        Tk::BLT::Table.arrange(@path)
        self
      end
blt_table_cget(*args)

[Source]

# File tk/lib/tkextlib/blt/table.rb, line 29
      def blt_table_cget(*args)
        Tk::BLT::Table.cget(@path, *args)
      end
blt_table_configinfo(*args)

[Source]

# File tk/lib/tkextlib/blt/table.rb, line 38
      def blt_table_configinfo(*args)
        Tk::BLT::Table.configinfo(@path, *args)
      end
blt_table_configure(*args)

[Source]

# File tk/lib/tkextlib/blt/table.rb, line 33
      def blt_table_configure(*args)
        Tk::BLT::Table.configure(@path, *args)
        self
      end
blt_table_current_configinfo(*args)

[Source]

# File tk/lib/tkextlib/blt/table.rb, line 42
      def blt_table_current_configinfo(*args)
        Tk::BLT::Table.current_configinfo(@path, *args)
      end
blt_table_current_itemconfiginfo(*args)

[Source]

# File tk/lib/tkextlib/blt/table.rb, line 105
      def blt_table_current_itemconfiginfo(*args)
        Tk::BLT::Table.current_itemconfiginfo(@path, *args)
      end
blt_table_delete(*args)

[Source]

# File tk/lib/tkextlib/blt/table.rb, line 50
      def blt_table_delete(*args)
        Tk::BLT::Table.delete(@path, *args)
        self
      end
blt_table_extents(item)

[Source]

# File tk/lib/tkextlib/blt/table.rb, line 55
      def blt_table_extents(item)
        Tk::BLT::Table.extents(@path, item)
      end
blt_table_insert(*args)

[Source]

# File tk/lib/tkextlib/blt/table.rb, line 59
      def blt_table_insert(*args)
        Tk::BLT::Table.insert(@path, *args)
        self
      end
blt_table_insert_after(*args)

[Source]

# File tk/lib/tkextlib/blt/table.rb, line 69
      def blt_table_insert_after(*args)
        Tk::BLT::Table.insert_after(@path, *args)
        self
      end
blt_table_insert_before(*args)

[Source]

# File tk/lib/tkextlib/blt/table.rb, line 64
      def blt_table_insert_before(*args)
        Tk::BLT::Table.insert_before(@path, *args)
        self
      end
blt_table_itemcget(*args)

[Source]

# File tk/lib/tkextlib/blt/table.rb, line 92
      def blt_table_itemcget(*args)
        Tk::BLT::Table.itemcget(@path, *args)
      end
blt_table_itemconfiginfo(*args)

[Source]

# File tk/lib/tkextlib/blt/table.rb, line 101
      def blt_table_itemconfiginfo(*args)
        Tk::BLT::Table.itemconfiginfo(@path, *args)
      end
blt_table_itemconfigure(*args)

[Source]

# File tk/lib/tkextlib/blt/table.rb, line 96
      def blt_table_itemconfigure(*args)
        Tk::BLT::Table.itemconfigure(@path, *args)
        self
      end
blt_table_iteminfo(item)

[Source]

# File tk/lib/tkextlib/blt/table.rb, line 109
      def blt_table_iteminfo(item)
        Tk::BLT::Table.iteminfo(@path, item)
      end
blt_table_join(first, last)

[Source]

# File tk/lib/tkextlib/blt/table.rb, line 74
      def blt_table_join(first, last)
        Tk::BLT::Table.join(@path, first, last)
        self
      end
blt_table_locate(x, y)

[Source]

# File tk/lib/tkextlib/blt/table.rb, line 46
      def blt_table_locate(x, y)
        Tk::BLT::Table.locate(@path, x, y)
      end
blt_table_save()

[Source]

# File tk/lib/tkextlib/blt/table.rb, line 79
      def blt_table_save()
        Tk::BLT::Table.save(@path)
      end
blt_table_search(*args)

[Source]

# File tk/lib/tkextlib/blt/table.rb, line 83
      def blt_table_search(*args)
        Tk::BLT::Table.search(@path, *args)
      end
blt_table_split(*args)

[Source]

# File tk/lib/tkextlib/blt/table.rb, line 87
      def blt_table_split(*args)
        Tk::BLT::Table.split(@path, *args)
        self
      end


Class: Tk::BLT::Tabnotebook

Class | Tk::BLT::Tabnotebook
In: | tk/lib/tkextlib/blt/tabnotebook.rb
Parent: | Tabset

Methods

get_id get_tab

Constants

TkCommandNames | = | ['::blt::tabnotebook'.freeze].freeze
WidgetClassName | = | 'Tabnotebook'.freeze

Public Instance methods

get_id(index)

Alias for get_tab

get_tab(index)

[Source]

# File tk/lib/tkextlib/blt/tabnotebook.rb, line 16
    def get_tab(index)
      Tk::BLT::Tabset::Tab.id2obj(tk_send_without_enc('id', tagindex(index)))
    end


Class: Tk::BLT::Tabset

Class | Tk::BLT::Tabset
In: | tk/lib/tkextlib/blt/tabset.rb
Parent: | TkWindow

Methods

__boolval_optkeys __destroy_hook__ activate delete focus get_tab highlight index index_name insert invoke move_after move_before nearest perforation_highlight perforation_invoke scan_dragto scan_mark scrollcommand see select size tab_names tab_tearoff tabbind tabbind_append tabbind_remove tabbindinfo tagid tagindex view xscrollcommand xview

Included Modules

X_Scrollable TkItemConfigMethod

Classes and Modules

Class Tk::BLT::Tabset::NamedTab
Class Tk::BLT::Tabset::Tab

Constants

TkCommandNames | = | ['::blt::tabset'.freeze].freeze
WidgetClassName | = | 'Tabset'.freeze

External Aliases

itemcget | -> | tab_cget
itemconfigure | -> | tab_configure
itemconfiginfo | -> | tab_configinfo
current_itemconfiginfo | -> | current_tab_configinfo
xview_moveto | -> | view_moveto
xview_scroll | -> | view_scroll
xscrollbar | -> | scrollbar

Public Instance methods

__boolval_optkeys()

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 192
    def __boolval_optkeys
      super() << 'samewidth' << 'tearoff'
    end
__destroy_hook__()

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 186
    def __destroy_hook__
      Tk::BLT::Tabset::Tab::TabID_TBL.delete(@path)
    end
activate(index)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 249
    def activate(index)
      tk_send('activate', tagindex(index))
      self
    end
delete(first, last=None)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 291
    def delete(first, last=None)
      tk_send('delete', tagindex(first), tagindex(last))
      if first.kind_of?(Tk::BLT::Tabset::Tab)
        TabID_TBL[@path].delete(first.id)
      end
      # middle tabs of the range are unknown
      if last.kind_of?(Tk::BLT::Tabset::Tab)
        TabID_TBL[@path].delete(last.id)
      end
      self
    end
focus(index)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 303
    def focus(index)
      tk_send('focus', tagindex(index))
      self
    end
get_tab(index)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 308
    def get_tab(index)
      Tk::BLT::Tabset::Tab.id2obj(tk_send_without_enc('get', tagindex(index)))
    end
highlight(index)

Alias for activate

index(str)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 312
    def index(str)
      num_or_str(tk_send('index', str))
    end
index_name(tab)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 315
    def index_name(tab)
      num_or_str(tk_send('index', '-mame', tagid(tab)))
    end
insert(pos, tab, keys={})

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 319
    def insert(pos, tab, keys={})
      Tk::BLT::Tabset::Tab.new(self, tagindex(pos), tagid(tab), keys)
    end
invoke(index)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 323
    def invoke(index)
      tk_send('invoke', tagindex(index))
    end
move_after(index, base_idx)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 331
    def move_after(index, base_idx)
      tk_send('move', tagindex(index), 'after', tagindex(base_idx))
      self
    end
move_before(index, base_idx)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 327
    def move_before(index, base_idx)
      tk_send('move', tagindex(index), 'before', tagindex(base_idx))
      self
    end
nearest(x, y)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 336
    def nearest(x, y)
      Tk::BLT::Tabset::Tab.id2obj(num_or_str(tk_send_without_enc('nearest', x, y)))
    end
perforation_highlight(index, mode)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 340
    def perforation_highlight(index, mode)
      tk_send('perforation', 'highlight', tagindex(index), mode)
      self
    end
perforation_invoke(index)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 344
    def perforation_invoke(index)
      tk_send('perforation', 'invoke', tagindex(index))
    end
scan_dragto(x, y)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 352
    def scan_dragto(x, y)
      tk_send_without_enc('scan', 'dragto', x, y)
      self
    end
scan_mark(x, y)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 348
    def scan_mark(x, y)
      tk_send_without_enc('scan', 'mark', x, y)
      self
    end
scrollcommand(cmd=Proc.new)

Alias for xscrollcommand

see(index)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 357
    def see(index)
      tk_send('see', tagindex(index))
      self
    end
select(index)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 366
    def select(index)
      tk_send('select', tagindex(index))
      self
    end
size()

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 362
    def size()
      number(tk_send_without_enc('size'))
    end
tab_names(pat=None)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 371
    def tab_names(pat=None)
      simplelist(tk_send('tab', 'names', pat)).collect{|name|
        Tk::BLT::Tabset::Tab.id2obj(name)
      }
    end
tab_tearoff(index, name=None)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 377
    def tab_tearoff(index, name=None)
      window(tk_send('tab', 'tearoff', tagindex(index), name))
    end
tabbind(tag, context, *args)

def tabbind(tag, context, cmd=Proc.new, *args)

  _bind([path, "bind", tagid(tag)], context, cmd, *args)
  self

end

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 259
    def tabbind(tag, context, *args)
      # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
      if TkComm._callback_entry?(args[0]) || !block_given?
        cmd = args.shift
      else
        cmd = Proc.new
      end
      _bind([path, "bind", tagid(tag)], context, cmd, *args)
      self
    end
tabbind_append(tag, context, *args)

def tabbind_append(tag, context, cmd=Proc.new, *args)

  _bind_append([path, "bind", tagid(tag)], context, cmd, *args)
  self

end

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 273
    def tabbind_append(tag, context, *args)
      # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
      if TkComm._callback_entry?(args[0]) || !block_given?
        cmd = args.shift
      else
        cmd = Proc.new
      end
      _bind_append([path, "bind", tagid(tag)], context, cmd, *args)
      self
    end
tabbind_remove(tag, context)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 283
    def tabbind_remove(tag, context)
      _bind_remove([path, "bind", tagid(tag)], context)
      self
    end
tabbindinfo(tag, context=nil)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 287
    def tabbindinfo(tag, context=nil)
      _bindinfo([path, "bind", tagid(tag)], context)
    end
tagid(tab)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 231
    def tagid(tab)
      if tab.kind_of?(Tk::BLT::Tabset::Tab)
        tab.id
      else
        tab
      end
    end
tagindex(tab)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 239
    def tagindex(tab)
      if tab.kind_of?(Tk::BLT::Tabset::Tab)
        tab.index
      else
        tab
      end
    end
view(*index)

Alias for xview

xscrollcommand(cmd=Proc.new)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 381
    def xscrollcommand(cmd=Proc.new)
      configure_cmd 'scrollcommand', cmd
      self
    end
xview(*index)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 387
    def xview(*index)
      if index.empty?
        list(tk_send_without_enc('view'))
      else
        tk_send_without_enc('view', *index)
        self
      end
    end


Class: Tk::BLT::Tabset::NamedTab

Class | Tk::BLT::Tabset::NamedTab
In: | tk/lib/tkextlib/blt/tabset.rb
Parent: | Tab

Methods

new

Public Class methods

new(parent, name)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 172
      def self.new(parent, name)
        super(parent, nil, name, {})
      end


Class: Tk::BLT::Tabset::Tab

Class | Tk::BLT::Tabset::Tab
In: | tk/lib/tkextlib/blt/tabset.rb
Parent: | TkObject

Methods

bind bind_append bind_remove bindinfo cget configinfo configure current_configinfo delete focus get_name id2obj index invoke move_after move_before new new perforation_highlight perforation_invoke see tearoff

Included Modules

TkTreatItemFont

Constants

TabID_TBL | = | TkCore::INTERP.create_table
TabsetTab_ID | = | ['blt_tabset_tab'.freeze, '00000'.taint].freeze

Public Class methods

id2obj(tabset, id)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 19
      def self.id2obj(tabset, id)
        tpath = tabset.path
        return id unless TabID_TBL[tpath]
        TabID_TBL[tpath][id]? TabID_TBL[tpath]: id
      end
new(parent, pos, name, keys)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 43
      def initialize(parent, pos, name, keys)
        @t = parent
        @tpath = parent.path
        if name
          @path = @id = name
          TabID_TBL[@tpath] = {} unless TabID_TBL[@tpath]
          TabID_TBL[@tpath][@id] = self

          unless (list(tk_call(@tpath, 'tab', 'names', @id)).empty?)
            if pos
              idx = tk_call(@tpath, 'index', '-name', @id)
              if pos.to_s == 'end'
                tk_call(@tpath, idx, 'moveto', 'after', 'end')
              else
                tk_call(@tpath, idx, 'moveto', 'before', pos)
              end
            end
            tk_call(@tpath, 'tab', 'configure', @id, keys)
            return
          end

        else
          @path = @id = TabsetTab_ID.join(TkCore::INTERP._ip_id_)
          TabID_TBL[@tpath] = {} unless TabID_TBL[@tpath]
          TabID_TBL[@tpath][@id] = self
          TabsetTab_ID[1].succ!
        end

        pos = 'end' unless pos
        tk_call(@tpath, 'insert', pos, @id, keys)
      end
new(parent, pos=nil, name=nil, keys={})

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 25
      def self.new(parent, pos=nil, name=nil, keys={})
        if pos.kind_of?(Hash)
          keys = pos
          name = nil
          pos  = nil
        end
        if name.kind_of?(Hash)
          keys = name
          name = nil
        end

        if name && TabID_TBL[parent.path] && TabID_TBL[parent.path][name]
          TabID_TBL[parent.path][name]
        else
          super(parent, pos, name, keys)
        end
      end

Public Instance methods

bind(context, *args)

def bind(context, cmd=Proc.new, *args)

  @t.tab_bind(@id, context, cmd, *args)
  self

end

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 79
      def bind(context, *args)
        # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
        if TkComm._callback_entry?(args[0]) || !block_given?
          cmd = args.shift
        else
          cmd = Proc.new
        end
        @t.tab_bind(@id, context, cmd, *args)
        self
      end
bind_append(context, *args)

def bind_append(context, cmd=Proc.new, *args)

  @t.tab_bind_append(@id, context, cmd, *args)
  self

end

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 93
      def bind_append(context, *args)
        # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
        if TkComm._callback_entry?(args[0]) || !block_given?
          cmd = args.shift
        else
          cmd = Proc.new
        end
        @t.tab_bind_append(@id, context, cmd, *args)
        self
      end
bind_remove(context)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 103
      def bind_remove(context)
        @t.tab_bind_remove(@id, context)
        self
      end
bindinfo(context=nil)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 107
      def bindinfo(context=nil)
        @t.tab_bindinfo(@id, context)
      end
cget(*args)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 111
      def cget(*args)
        @t.tab_cget(@id, *args)
      end
configinfo(*args)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 117
      def configinfo(*args)
        @t.tab_configinfo(@id, *args)
      end
configure(*args)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 114
      def configure(*args)
        @t.tab_configure(@id, *args)
      end
current_configinfo(*args)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 120
      def current_configinfo(*args)
        @t.current_tab_configinfo(@id, *args)
      end
delete()

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 124
      def delete()
        @t.delete(@id)
        TabID_TBL[@tpath].delete(@id)
        self
      end
focus()

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 134
      def focus()
        @t.focus(self.index)
      end
get_name()

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 130
      def get_name()
        @id.dup
      end
index()

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 138
      def index()
        @t.index_name(@id)
      end
invoke()

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 142
      def invoke()
        @t.invoke(self.index)
      end
move_after(idx)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 149
      def move_after(idx)
        @t.move_after(self.index, idx)
      end
move_before(idx)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 146
      def move_before(idx)
        @t.move_before(self.index, idx)
      end
perforation_highlight(mode)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 153
      def perforation_highlight(mode)
        @t.perforation.highlight(self.index, mode)
      end
perforation_invoke()

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 156
      def perforation_invoke()
        @t.perforation.invoke(self.index)
      end
see()

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 160
      def see()
        @t.see(self.index)
      end
tearoff(name=None)

[Source]

# File tk/lib/tkextlib/blt/tabset.rb, line 164
      def tearoff(name=None)
        @t.tab_tearoff(self.index, *args)
      end


Module: Tk::BLT::Ted

Module | Tk::BLT::Ted
In: | tk/lib/tkextlib/blt/ted.rb

Methods

cget configinfo configure current_configinfo edit rep select

Constants

TkCommandNames = ['::blt::ted'.freeze].freeze

Public Class methods

cget(master, option)

[Source]

# File tk/lib/tkextlib/blt/ted.rb, line 36
      def cget(master, option)
        itemconfigure(master, slot, value)
      end
configinfo(master, slot=nil)

[Source]

# File tk/lib/tkextlib/blt/ted.rb, line 42
      def configinfo(master, slot=nil)
        itemconfiginfo(master, slot)
      end
configure(master, slot, value=None)

[Source]

# File tk/lib/tkextlib/blt/ted.rb, line 39
      def configure(master, slot, value=None)
        itemconfigure(master, slot, value)
      end
current_configinfo(master, slot=nil)

[Source]

# File tk/lib/tkextlib/blt/ted.rb, line 45
      def current_configinfo(master, slot=nil)
        current_itemconfiginfo(master, slot)
      end
edit(master, *args)

[Source]

# File tk/lib/tkextlib/blt/ted.rb, line 52
    def self.edit(master, *args)
      tk_call('::blt::ted', 'edit', master, *args)
    end
rep(master, *args)

[Source]

# File tk/lib/tkextlib/blt/ted.rb, line 55
    def self.rep(master, *args)
      tk_call('::blt::ted', 'rep', master, *args)
    end
select(master, *args)

[Source]

# File tk/lib/tkextlib/blt/ted.rb, line 58
    def self.select(master, *args)
      tk_call('::blt::ted', 'select', master, *args)
    end


Module: Tk::BLT::Tile

Module | Tk::BLT::Tile
In: | tk/lib/tkextlib/blt/tile.rb tk/lib/tkextlib/blt/tile/toplevel.rb tk/lib/tkextlib/blt/tile/scrollbar.rb tk/lib/tkextlib/blt/tile/radiobutton.rb tk/lib/tkextlib/blt/tile/label.rb tk/lib/tkextlib/blt/tile/frame.rb tk/lib/tkextlib/blt/tile/checkbutton.rb tk/lib/tkextlib/blt/tile/button.rb

Classes and Modules

Class Tk::BLT::Tile::Button
Class Tk::BLT::Tile::Checkbutton
Class Tk::BLT::Tile::Frame
Class Tk::BLT::Tile::Label
Class Tk::BLT::Tile::Radiobutton
Class Tk::BLT::Tile::Scrollbar
Class Tk::BLT::Tile::Toplevel

Constants

RadioButton | = | Radiobutton
CheckButton | = | Checkbutton


Class: Tk::BLT::Tile::Button

Class | Tk::BLT::Tile::Button
In: | tk/lib/tkextlib/blt/tile/button.rb
Parent: | TkButton

Constants

TkCommandNames = ['::blt::tile::button'.freeze].freeze


Class: Tk::BLT::Tile::Checkbutton

Class | Tk::BLT::Tile::Checkbutton
In: | tk/lib/tkextlib/blt/tile/checkbutton.rb
Parent: | TkCheckbutton

Constants

TkCommandNames = ['::blt::tile::checkbutton'.freeze].freeze


Class: Tk::BLT::Tile::Frame

Class | Tk::BLT::Tile::Frame
In: | tk/lib/tkextlib/blt/tile/frame.rb
Parent: | TkFrame

Constants

TkCommandNames = ['::blt::tile::frame'.freeze].freeze


Class: Tk::BLT::Tile::Label

Class | Tk::BLT::Tile::Label
In: | tk/lib/tkextlib/blt/tile/label.rb
Parent: | TkLabel

Constants

TkCommandNames = ['::blt::tile::label'.freeze].freeze


Class: Tk::BLT::Tile::Radiobutton

Class | Tk::BLT::Tile::Radiobutton
In: | tk/lib/tkextlib/blt/tile/radiobutton.rb
Parent: | TkRadiobutton

Constants

TkCommandNames = ['::blt::tile::radiobutton'.freeze].freeze


Class: Tk::BLT::Tile::Scrollbar

Class | Tk::BLT::Tile::Scrollbar
In: | tk/lib/tkextlib/blt/tile/scrollbar.rb
Parent: | TkScrollbar

Constants

TkCommandNames = ['::blt::tile::scrollbar'.freeze].freeze


Class: Tk::BLT::Tile::Toplevel

Class | Tk::BLT::Tile::Toplevel
In: | tk/lib/tkextlib/blt/tile/toplevel.rb
Parent: | TkToplevel

Constants

TkCommandNames = ['::blt::tile::toplevel'.freeze].freeze


Class: Tk::BLT::Tree

Class | Tk::BLT::Tree
In: | tk/lib/tkextlib/blt/tree.rb
Parent: | TkObject

Methods

__destroy_hook__ __keyonly_optkeys ancestor ancestor? apply attach before? children copy copy_to degree delete depth destroy destroy dump dump_to_file exist? find find_child first_child fullpath get get_value id2obj index initialzie insert keys label last_child leaf? link link? move names new next next_sibling notify_create notify_delete notify_info notify_names parent position prev_sibling previous restore restore_from_file restore_overwrite restore_overwrite_from_file root root? set size sort tag_add tag_delete tag_forget tag_get tag_names tag_nodes tag_set tag_unset tagid trace_create trace_delete trace_info trace_names type unset values

Classes and Modules

Class Tk::BLT::Tree::Node
Class Tk::BLT::Tree::Notify
Class Tk::BLT::Tree::Tag
Class Tk::BLT::Tree::Trace

Constants

TkCommandNames | = | ['::blt::tree'.freeze].freeze
TreeID_TBL | = | TkCore::INTERP.create_table
Tree_ID | = | ['blt_tree'.freeze, '00000'.taint].freeze

Public Class methods

destroy(*names)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 510
    def self.destroy(*names)
      tk_call('::blt::tree', 'destroy',
              *(names.collect{|n| (n.kind_of?(Tk::BLT::Tree))? n.id: n }) )
    end
id2obj(id)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 500
    def self.id2obj(id)
      TreeID_TBL[id]? TreeID_TBL[id]: id
    end
names(pat = None)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 504
    def self.names(pat = None)
      simplelist(tk_call('::blt::tree', 'names', pat)).collect{|name|
        id2obj(name)
      }
    end
new(name = nil)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 515
    def self.new(name = nil)
      return TreeID_TBL[name] if name && TreeID_TBL[name]
      super(name)
    end

Public Instance methods

__destroy_hook__()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 532
    def __destroy_hook__
      Tk::BLT::Tree::Node::TreeNodeID_TBL.delete(@path)
      Tk::BLT::Tree::Tag::TreeTagID_TBL.delete(@path)
      Tk::BLT::Tree::Notify::NotifyID_TBL.delete(@path)
      Tk::BLT::Tree::Trace::TraceID_TBL.delete(@path)
    end
__keyonly_optkeys()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 480
    def __keyonly_optkeys
      {
        # apply / find  command
        'invert'=>nil, 'leafonly'=>nil, 'nocase'=>nil,

        # apply / find / sort command
        'path'=>nil,

        # copy / restore / restorefile command
        'overwrite'=>nil,

        # copy command
        'recurse'=>nil, 'tags'=>nil,

        # sort command
        'ascii'=>nil, 'decreasing'=>nil, 'disctionary'=>nil,
        'integer'=>nil, 'real'=>nil, 'recurse'=>nil, 'reorder'=>nil,
      }
    end
ancestor(node1, node2)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 555
    def ancestor(node1, node2)
      Tk::BLT::Tree::Node.id2obj(self, tk_call('::blt::tree', 'ancestor',
                                               tagid(node1), tagid(node2)))
    end
ancestor?(node1, node2)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 658
    def ancestor?(node1, node2)
      bool(tk_call('::blt::tree', 'is', 'ancestor',
                   tagid(node1), tagid(node2)))
    end
apply(node, keys={})

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 560
    def apply(node, keys={})
      tk_call('::blt::tree', 'apply', tagid(node), __conv_keyonly_opts(keys))
      self
    end
attach(tree_obj)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 565
    def attach(tree_obj)
      tk_call('::blt::tree', 'attach', tree_obj)
      self
    end
before?(node1, node2)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 662
    def before?(node1, node2)
      bool(tk_call('::blt::tree', 'is', 'before',
                   tagid(node1), tagid(node2)))
    end
children(node)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 570
    def children(node)
      simplelist(tk_call('::blt::tree', 'children', tagid(node))).collect{|n|
        Tk::BLT::Tree::Node.id2obj(self, n)
      }
    end
copy(src, parent, keys={})

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 576
    def copy(src, parent, keys={})
      id = tk_call('::blt::tree', 'copy', tagid(src), tagid(parent),
                   __conv_keyonly_opts(keys))
      Tk::BLT::Tree::Node.new(self, nil, 'node'=>id)
    end
copy_to(src, dest_tree, parent, keys={})

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 581
    def copy_to(src, dest_tree, parent, keys={})
      return copy(src, parent, keys={}) unless dest_tree

      id = tk_call('::blt::tree', 'copy', tagid(src), dest_tree,
                   tagid(parent), __conv_keyonly_opts(keys))
      Tk::BLT::Tree::Node.new(dest_tree, nil, 'node'=>id)
    end
degree(node)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 589
    def degree(node)
      number(tk_call('::blt::tree', 'degree', tagid(node)))
    end
delete(*nodes)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 593
    def delete(*nodes)
      tk_call('::blt::tree', 'delete', *(nodes.collect{|node| tagid(node)}))
      nodes.each{|node|
        if node.kind_of?(Tk::BLT::Tree::Node)
          Tk::BLT::Tree::Node::TreeNodeID_TBL[@path].delete(node.id)
        else
          Tk::BLT::Tree::Node::TreeNodeID_TBL[@path].delete(node.to_s)
        end
      }
      self
    end
depth(node)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 605
    def depth(node)
      number(tk_call('::blt::tree', 'depth', tagid(node)))
    end
destroy()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 550
    def destroy()
      tk_call('::blt::tree', 'destroy', @id)
      self
    end
dump(node)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 609
    def dump(node)
      simplelist(tk_call('::blt::tree', 'dump', tagid(node))).collect{|n|
        simplelist(n)
      }
    end
dump_to_file(node, file)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 615
    def dump_to_file(node, file)
      tk_call('::blt::tree', 'dumpfile', tagid(node), file)
      self
    end
exist?(node, key=None)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 620
    def exist?(node, key=None)
      bool(tk_call('::blt::tree', 'exists', tagid(node), key))
    end
find(node, keys={})

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 624
    def find(node, keys={})
      simplelist(tk_call('::blt::tree', 'find', tagid(node),
                         __conv_keyonly_opts(keys))).collect{|n|
        Tk::BLT::Tree::Node.id2obj(self, n)
      }
    end
find_child(node, label)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 631
    def find_child(node, label)
      ret = tk_call('::blt::tree', 'findchild', tagid(node), label)
      (ret == '-1')? nil: Tk::BLT::Tree::Node.id2obj(self, ret)
    end
first_child(node)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 636
    def first_child(node)
      ret = tk_call('::blt::tree', 'firstchild', tagid(node))
      (ret == '-1')? nil: Tk::BLT::Tree::Node.id2obj(self, ret)
    end
fullpath(node)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 755
    def fullpath(node)
      tk_call('::blt::tree', 'path', tagid(node))
    end
get(node)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 641
    def get(node)
      Hash[*simplelist(tk_call('::blt::tree', 'get', tagid(node)))]
    end
get_value(node, key, default_val=None)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 644
    def get_value(node, key, default_val=None)
      tk_call('::blt::tree', 'get', tagid(node), key, default_val)
    end
index(node)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 648
    def index(node)
      Tk::BLT::Tree::Node.id2obj(self,
                                 tk_call('::blt::tree', 'index', tagid(node)))
    end
initialzie(name = nil)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 520
    def initialzie(name = nil)
      if name
        @path = @id = name
      else
        @path = @id = Tree_ID.join(TkCore::INTERP._ip_id_)
        TreeID_TBL[@id] = self
        Tree_ID[1].succ!
      end
      TreeID_TBL[@id] = self
      tk_call('::blt::tree', 'create', @id)
    end
insert(parent, keys={})

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 653
    def insert(parent, keys={})
      id = tk_call('::blt::tree', 'insert', tagid(parent), keys)
      Tk::BLT::Tree::Node.new(self, nil, 'node'=>id)
    end
keys(node, *nodes)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 676
    def keys(node, *nodes)
      if nodes.empty?
        simplelist(tk_call('blt::tree', 'keys', tagid(node)))
      else
        simplelist(tk_call('blt::tree', 'keys', tagid(node),
                           *(nodes.collect{|n| tagid(n)}))).collect{|lst|
          simplelist(lst)
        }
      end
    end
label(node, text=nil)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 687
    def label(node, text=nil)
      if text
        tk_call('::blt::tree', 'label', tagid(node), text)
        text
      else
        tk_call('::blt::tree', 'label', tagid(node))
      end
    end
last_child(node)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 696
    def last_child(node)
      ret = tk_call('::blt::tree', 'lastchild', tagid(node))
      (ret == '-1')? nil: Tk::BLT::Tree::Node.id2obj(self, ret)
    end
leaf?(node)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 666
    def leaf?(node)
      bool(tk_call('::blt::tree', 'is', 'leaf', tagid(node)))
    end
link(parent, node, keys={})

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 701
    def link(parent, node, keys={})
      ret = tk_call('::blt::tree', 'link', tagid(parent), tagid(node),
                    __conv_keyonly_opts(keys))
      (ret == '-1')? nil: Tk::BLT::Tree::Node.id2obj(self, ret)
    end
link?(node)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 669
    def link?(node)
      bool(tk_call('::blt::tree', 'is', 'link', tagid(node)))
    end
move(node, dest, keys={})

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 707
    def move(node, dest, keys={})
      tk_call('::blt::tree', 'move', tagid(node), tagid(dest), keys)
      self
    end
next(node)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 712
    def next(node)
      ret = tk_call('::blt::tree', 'next', tagid(node))
      (ret == '-1')? nil: Tk::BLT::Tree::Node.id2obj(self, ret)
    end
next_sibling(node)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 717
    def next_sibling(node)
      ret = tk_call('::blt::tree', 'nextsibling', tagid(node))
      (ret == '-1')? nil: Tk::BLT::Tree::Node.id2obj(self, ret)
    end
notify_create(*args, &b)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 722
    def notify_create(*args, &b)
      Tk::BLT::Tree::Notify.new(self, *args, &b)
    end
notify_delete(id)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 726
    def notify_delete(id)
      if id.kind_of?(Tk::BLT::Tree::Notify)
        id.delete
      else
        tk_call(@path, 'notify', 'delete', id)
        Tk::BLT::Tree::Notify::NotifyID_TBL[@path].delete(id.to_s)
      end
      self
    end
notify_info(id)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 736
    def notify_info(id)
      lst = simplelist(tk_call(@path, 'notify', 'info', tagid(id)))
      lst[0] = Tk::BLT::Tree::Notify.id2obj(self, lst[0])
      lst[1] = simplelist(lst[1]).collect{|flag| flag[1..-1]}
      lst[2] = tk_tcl2ruby(lst[2])
      lst
    end
notify_names()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 744
    def notify_names()
      tk_call(@path, 'notify', 'names').collect{|id|
        Tk::BLT::Tree::Notify.id2obj(self, id)
      }
    end
parent(node)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 750
    def parent(node)
      ret = tk_call('::blt::tree', 'parent', tagid(node))
      (ret == '-1')? nil: Tk::BLT::Tree::Node.id2obj(self, ret)
    end
position(node)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 759
    def position(node)
      number(tk_call('::blt::tree', 'position', tagid(node)))
    end
prev_sibling(node)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 768
    def prev_sibling(node)
      ret = tk_call('::blt::tree', 'prevsibling', tagid(node))
      (ret == '-1')? nil: Tk::BLT::Tree::Node.id2obj(self, ret)
    end
previous(node)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 763
    def previous(node)
      ret = tk_call('::blt::tree', 'previous', tagid(node))
      (ret == '-1')? nil: Tk::BLT::Tree::Node.id2obj(self, ret)
    end
restore(node, str, keys={})

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 773
    def restore(node, str, keys={})
      tk_call('::blt::tree', 'restore', tagid(node), str,
              __conv_keyonly_opts(keys))
      self
    end
restore_from_file(node, file, keys={})

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 786
    def restore_from_file(node, file, keys={})
      tk_call('::blt::tree', 'restorefile', tagid(node), file,
              __conv_keyonly_opts(keys))
      self
    end
restore_overwrite(node, str, keys={})

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 778
    def restore_overwrite(node, str, keys={})
      keys = __conv_keyonly_opts(keys)
      keys.delete('overwrite')
      keys.delete(:overwrite)
      tk_call('::blt::tree', 'restore', tagid(node), str, '-overwrite', keys)
      self
    end
restore_overwrite_from_file(node, file, keys={})

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 791
    def restore_overwrite_from_file(node, file, keys={})
      keys = __conv_keyonly_opts(keys)
      keys.delete('overwrite')
      keys.delete(:overwrite)
      tk_call('::blt::tree', 'restorefile', tagid(node), file,
              '-overwrite', keys)
      self
    end
root(node=None)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 800
    def root(node=None)
      Tk::BLT::Tree::Node.id2obj(self, tk_call('::blt::tree', 'root',
                                               tagid(node)))
    end
root?(node)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 672
    def root?(node)
      bool(tk_call('::blt::tree', 'is', 'root', tagid(node)))
    end
set(node, data)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 805
    def set(node, data)
      unless data.kind_of?(Hash)
        fail ArgumentError, 'Hash is expected for data'
      end
      args = []
      data.each{|k, v|  args << k << v}
      tk_call('::blt::tree', 'set', tagid(node), *args)
      self
    end
size(node)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 815
    def size(node)
      number(tk_call('::blt::tree', 'size', tagid(node)))
    end
sort(node, keys={})

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 819
    def sort(node, keys={})
      tk_call('::blt::tree', 'sort', tagid(node), __conv_keyonly_opts(keys))
      self
    end
tag_add(tag, *nodes)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 824
    def tag_add(tag, *nodes)
      tk_call(@path, 'tag', 'add', tagid(tag), *(nodes.collect{|n| tagid(n)}))
      self
    end
tag_delete(tag, *nodes)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 829
    def tag_delete(tag, *nodes)
      tk_call(@path, 'tag', 'delete', tagid(tag),
              *(nodes.collect{|n| tagid(n)}))
      self
    end
tag_forget(tag)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 835
    def tag_forget(tag)
      tag = tag.id if tag.kind_of?(Tk::BLT::Tree::Tag)
      tk_call(@path, 'tag', 'forget', tag)
      TreeTagID_TBL[@path].delete(tag)
      self
    end
tag_get(node, *patterns)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 842
    def tag_get(node, *patterns)
      simplelist(tk_call(@tpath, 'tag', 'get', tagid(node),
                         *(patterns.collect{|pat| tagid(pat)}))).collect{|str|
        Tk::BLT::Tree::Tag.id2obj(self, str)
      }
    end
tag_names(node = None)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 849
    def tag_names(node = None)
      simplelist(tk_call(@tpath, 'tag', 'names', tagid(node))).collect{|str|
        Tk::BLT::Tree::Tag.id2obj(self, str)
      }
    end
tag_nodes(tag)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 855
    def tag_nodes(tag)
      simplelist(tk_call(@tpath, 'tag', 'nodes', tagid(tag))).collect{|node|
        Tk::BLT::Tree::Node.id2obj(self, node)
      }
    end
tag_set(node, *tags)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 861
    def tag_set(node, *tags)
      tk_call(@path, 'tag', 'set', tagid(node), *(tags.collect{|t| tagid(t)}))
      self
    end
tag_unset(node, *tags)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 866
    def tag_unset(node, *tags)
      tk_call(@path, 'tag', 'unset', tagid(node),
              *(tags.collect{|t| tagid(t)}))
      self
    end
tagid(tag)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 539
    def tagid(tag)
      if tag.kind_of?(Tk::BLT::Tree::Node) ||
          tag.kind_of?(Tk::BLT::Tree::Tag) ||
          tag.kind_of?(Tk::BLT::Tree::Notify) ||
          tag.kind_of?(Tk::BLT::Tree::Trace)
        tag.id
      else
        tag  # maybe an Array of configure paramters
      end
    end
trace_create(*args, &b)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 872
    def trace_create(*args, &b)
      Tk::BLT::Tree::Trace.new(self, *args, &b)
    end
trace_delete(*args)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 889
    def trace_delete(*args)
      args = args.collect{|id| tagid(id)}
      tk_call(@path, 'trace', 'delete', *args)
      args.each{|id| Tk::BLT::Tree::Trace::TraceID_TBL[@path].delete(id.to_s)}
      self
    end
trace_info(id)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 896
    def trace_info(id)
      lst = simplelist(tk_call(@path, 'trace', 'info', tagid(id)))
      lst[0] = Tk::BLT::Tree::Trace.id2obj(self, lst[0])
      lst[2] = simplelist(lst[2])
      lst[3] = tk_tcl2ruby(lst[3])
      lst
    end
trace_names()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 904
    def trace_names()
      tk_call(@path, 'trace', 'names').collect{|id|
        Tk::BLT::Tree::Trace.id2obj(self, id)
      }
    end
type(node, key)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 910
    def type(node, key)
      tk_call('::blt::tree', 'type', tagid(node), key)
    end
unset(node, *keys)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 914
    def unset(node, *keys)
      tk_call('::blt::tree', 'unset', tagid(node), *keys)
      self
    end
values(node, key=None)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 919
    def values(node, key=None)
      simplelist(tk_call('::blt::tree', 'values', tagid(node), key))
    end


Class: Tk::BLT::Tree::Node

Class | Tk::BLT::Tree::Node
In: | tk/lib/tkextlib/blt/tree.rb
Parent: | TkObject

Methods

apply children copy copy_to degree delete depth dump dump_to_file exist? find find_child first_child fullpath get get_value id id2obj index keys label label= last_child leaf? link? move new new next next_sibling parent position prev_sibling previous restore restore_from_file restore_overwrite restore_overwrite_from_file root root? set size sort type unset values

Constants

TreeNodeID_TBL = TkCore::INTERP.create_table

Public Class methods

id2obj(tree, id)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 19
      def self.id2obj(tree, id)
        tpath = tree.path
        return id unless TreeNodeID_TBL[tpath]
        if TreeNodeID_TBL[tpath][id]
          TreeNodeID_TBL[tpath][id]
        else
          begin
            self.new(tree, nil, 'node'=>Integer(id))
          rescue
            id
          end
        end
      end
new(tree, parent, keys={})

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 46
      def initialize(tree, parent, keys={})
        @parent = @tree = tree
        @tpath = @parent.path

        parent = tk_call(@tpath, 'root') unless parent

        if (id = keys['node']) && bool(tk_call(@tpath, 'exists', id))
          @path = @id = id
          keys.delete('node')
          tk_call(@tpath, 'move', @id, parent, keys) if parent
        else
          @path = @id = tk_call(@tpath, 'insert', parent, keys)
        end

        TreeNodeID_TBL[@tpath] = {} unless TreeNodeID_TBL[@tpath]
        TreeNodeID_TBL[@tpath][@id] = self
      end
new(tree, parent, keys={})

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 33
      def self.new(tree, parent, keys={})
        keys = _symbolkey2str(keys)
        tpath = tree.path

        if (id = keys['node']) && (obj = TreeNodeID_TBL[tpath][id])
          keys.delete('node')
          tk_call(tree.path, 'move', id, parent, keys) if parent
          return obj
        end

        super(tree, parent, keys)
      end

Public Instance methods

apply(keys={})

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 68
      def apply(keys={})
        @tree.apply(@id, keys)
        self
      end
children()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 73
      def children()
        @tree.children(@id)
      end
copy(parent, keys={})

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 77
      def copy(parent, keys={})
        @tree.copy(@id, parent, keys)
      end
copy_to(dest_tree, parent, keys={})

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 80
      def copy_to(dest_tree, parent, keys={})
        @tree.copy_to(@id, dest_tree, parent, keys)
      end
degree()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 84
      def degree()
        @tree.degree(@id)
      end
delete()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 88
      def delete()
        @tree.delete(@id)
        self
      end
depth()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 93
      def depth()
        @tree.depth(@id)
      end
dump()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 97
      def dump()
        @tree.dump(@id)
      end
dump_to_file(file)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 101
      def dump_to_file(file)
        @tree.dump_to_file(@id, file)
        self
      end
exist?(keys={})

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 106
      def exist?(keys={})
        @tree.exist?(@id, keys)
      end
find(keys={})

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 110
      def find(keys={})
        @tree.find(@id, keys)
      end
find_child(label)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 114
      def find_child(label)
        @tree.find_child(@id, label)
      end
first_child()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 118
      def first_child()
        @tree.first_child(@id)
      end
fullpath()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 175
      def fullpath()
        @tree.fullpath(@id)
      end
get()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 122
      def get()
        @tree.get(@id)
      end
get_value(key, default_val=None)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 125
      def get_value(key, default_val=None)
        @tree.get_value(@id, key, default_val)
      end
id()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 64
      def id
        @id
      end
index()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 129
      def index()
        @tree.index(@id)
      end
keys()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 143
      def keys()
        @tree.keys(@id)
      end
label(text = nil)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 147
      def label(text = nil)
        @tree.label(@id, nil)
      end
label=(text)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 150
      def label=(text)
        @tree.label(@id, text)
      end
last_child()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 154
      def last_child()
        @tree.last_child(@id)
      end
leaf?()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 133
      def leaf?()
        @tree.leaf?(@id)
      end
link?()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 136
      def link?()
        @tree.link?(@id)
      end
move(dest, keys={})

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 158
      def move(dest, keys={})
        @tree.keys(@id, dest, keys)
        self
      end
next()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 163
      def next()
        @tree.next(@id)
      end
next_sibling()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 167
      def next_sibling()
        @tree.next_sibling(@id)
      end
parent()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 171
      def parent()
        @tree.parent(@id)
      end
position()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 179
      def position()
        @tree.position(@id)
      end
prev_sibling()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 187
      def prev_sibling()
        @tree.prev_sibling(@id)
      end
previous()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 183
      def previous()
        @tree.previous(@id)
      end
restore(str, keys={})

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 191
      def restore(str, keys={})
        @tree.restore(@id, str, keys)
        self
      end
restore_from_file(file, keys={})

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 200
      def restore_from_file(file, keys={})
        @tree.restore_from_file(@id, file, keys)
        self
      end
restore_overwrite(str, keys={})

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 195
      def restore_overwrite(str, keys={})
        @tree.restore_overwrite(@id, str, keys)
        self
      end
restore_overwrite_from_file(file, keys={})

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 204
      def restore_overwrite_from_file(file, keys={})
        @tree.restore_overwrite_from_file(@id, file, keys)
        self
      end
root()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 209
      def root()
        @tree.root(@id)
        self
      end
root?()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 139
      def root?()
        @tree.root?(@id)
      end
set(data)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 214
      def set(data)
        @tree.set(@id, data)
        self
      end
size()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 219
      def size()
        @tree.size(@id)
      end
sort(keys={})

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 223
      def sort(keys={})
        @tree.sort(@id, keys)
        self
      end
type(key)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 228
      def type(key)
        @tree.type(@id, key)
      end
unset(*keys)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 232
      def unset(*keys)
        @tree.unset(@id, *keys)
        self
      end
values(key=None)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 237
      def values(key=None)
        @tree.values(@id, key)
      end


Class: Tk::BLT::Tree::Notify

Class | Tk::BLT::Tree::Notify
In: | tk/lib/tkextlib/blt/tree.rb
Parent: | TkObject

Methods

delete id id2obj info new new

Constants

NotifyID_TBL = TkCore::INTERP.create_table

Public Class methods

id2obj(tree, id)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 317
      def self.id2obj(tree, id)
        tpath = tree.path
        return id unless NotifyID_TBL[tpath]
        if NotifyID_TBL[tpath][id]
          NotifyID_TBL[tpath][id]
        else
          begin
            self.new([tree, id])
          rescue
            id
          end
        end
      end
new(tree, *args, &b)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 331
      def self.new(tree, *args, &b)
        if tree.kind_of?(Array)
          # not create
          if obj = NotifyID_TBL[tree[0].path][tree[1]]
            return obj
          else
            return super(false, tree[0], tree[1])
          end
        end

        super(true, tree, *args, &b)
      end
new(create, tree, *args, &b)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 344
      def initialize(create, tree, *args, &b)
        @parent = @tree = tree
        @tpath = @parent.path

        unless create
          @path = @id = args[0]
          return
        end

        # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
        if TkComm._callback_entry?(args[0])
          cmd = args.shift
        # elsif args[-1].kind_of?(Proc) || args[-1].kind_of?(Method)
        elsif TkComm._callback_entry?(args[-1])
          cmd = args.pop
        elsif b
          cmd = Proc.new(&b)
        else
          fail ArgumentError, "lack of 'command' argument"
        end

        args = args.collect{|arg| '-' << arg.to_s}

        args << proc{|id, type|
          cmd.call(Tk::BLT::Tree::Node.id2obj(@tree, id),
                   ((type[0] == ?-)? type[1..-1]: type))
        }

        @path = @id = tk_call(@tpath, 'notify', 'create', *args)
      end

Public Instance methods

delete()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 379
      def delete()
        tk_call(@tpath, 'notify', 'delete', @id)
        NotifyID_TBL[tpath].delete(@id)
        self
      end
id()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 375
      def id
        @id
      end
info()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 385
      def info()
        lst = simplelist(tk_call(@tpath, 'notify', 'info', id))
        lst[0] = Tk::BLT::Tree::Notify.id2obj(@tree, lst[0])
        lst[1] = simplelist(lst[1]).collect{|flag| flag[1..-1]}
        lst[2] = tk_tcl2ruby(lst[2])
        lst
      end


Class: Tk::BLT::Tree::Tag

Class | Tk::BLT::Tree::Tag
In: | tk/lib/tkextlib/blt/tree.rb
Parent: | TkObject

Methods

add delete forget id id2obj new nodes set unset

Constants

TreeTagID_TBL | = | TkCore::INTERP.create_table
TreeTag_ID | = | ['blt_tree_tag'.freeze, '00000'.taint].freeze

Public Class methods

id2obj(tree, id)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 249
      def self.id2obj(tree, id)
        tpath = tree.path
        return id unless TreeTagID_TBL[tpath]
        if TreeTagID_TBL[tpath][id]
          TreeTagID_TBL[tpath][id]
        else
          self.new(tree, id)
        end
      end
new(tree, tag_str = nil)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 259
      def initialize(tree, tag_str = nil)
        @parent = @tree = tree
        @tpath = @parent.path

        if tag_str
          @path = @id = tag_str.dup.freeze
        else
          @path = @id = TreeTag_ID.join(TkCore::INTERP._ip_id_)
          TreeTagID_TBL[@id] = self
          TreeTag_ID[1].succ!
        end
        TreeTagID_TBL[@tpath] = {} unless TreeTagID_TBL[@tpath]
        TreeTagID_TBL[@tpath][@id] = self
      end

Public Instance methods

add(*nodes)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 278
      def add(*nodes)
        tk_call(@tpath, 'tag', 'add', @id, *nodes)
        self
      end
delete(*nodes)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 283
      def delete(*nodes)
        tk_call(@tpath, 'tag', 'delete', @id, *nodes)
        self
      end
forget()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 288
      def forget()
        tk_call(@tpath, 'tag', 'forget', @id)
        TreeTagID_TBL[@tpath].delete(@id)
        self
      end
id()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 274
      def id
        @id
      end
nodes()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 294
      def nodes()
        simplelist(tk_call(@tpath, 'tag', 'nodes', @id)).collect{|node|
          Tk::BLT::Tree::Node.id2obj(@path, node)
        }
      end
set(node)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 300
      def set(node)
        tk_call(@tpath, 'tag', 'set', node, @id)
        self
      end
unset(node)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 305
      def unset(node)
        tk_call(@tpath, 'tag', 'unset', node, @id)
        self
      end


Class: Tk::BLT::Tree::Trace

Class | Tk::BLT::Tree::Trace
In: | tk/lib/tkextlib/blt/tree.rb
Parent: | TkObject

Methods

delete id id2obj info new new

Constants

TraceID_TBL = TkCore::INTERP.create_table

Public Class methods

id2obj(tree, id)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 400
      def self.id2obj(tree, id)
        tpath = tree.path
        return id unless TraceID_TBL[tpath]
        if TraceID_TBL[tpath][id]
          TraceID_TBL[tpath][id]
        else
          begin
            self.new([tree, id])
          rescue
            id
          end
        end
      end
new(tree, *args, &b)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 414
      def self.new(tree, *args, &b)
        if tree.kind_of?(Array)
          # not create
          if obj = TraceID_TBL[tree[0].path][tree[1]]
            return obj
          else
            return super(false, tree[0], tree[1])
          end
        end

        super(true, tree, *args, &b)
      end
new(create, tree, node, key, opts, cmd=nil, &b)

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 427
      def initialize(create, tree, node, key, opts, cmd=nil, &b)
        @parent = @tree = tree
        @tpath = @parent.path

        unless create
          @path = @id = node  # == traceID
          return
        end

        if !cmd
          if b
            cmd = Proc.new(&b)
          else
            fail ArgumentError, "lack of 'command' argument"
          end
        end

        @path = @id = tk_call(@tpath, 'trace', 'create', node, key, opts,
                              proc{|t, id, k, ops|
                                tobj = Tk::BLT::Tree.id2obj(t)
                                if tobj.kind_of?(Tk::BLT::Tree)
                                  nobj = Tk::BLT::Tree::Node.id2obj(tobj, id)
                                else
                                  nobj = id
                                end
                                cmd.call(tobj, nobj, k, ops)
                              })
      end

Public Instance methods

delete()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 460
      def delete()
        tk_call(@tpath, 'trace', 'delete', @id)
        TraceID_TBL[tpath].delete(@id)
        self
      end
id()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 456
      def id
        @id
      end
info()

[Source]

# File tk/lib/tkextlib/blt/tree.rb, line 466
      def info()
        lst = simplelist(tk_call(@tpath, 'trace', 'info', id))
        lst[0] = Tk::BLT::Tree::Trace.id2obj(@tree, lst[0])
        lst[2] = simplelist(lst[2])
        lst[3] = tk_tcl2ruby(lst[3])
        lst
      end


Class: Tk::BLT::Treeview

Class | Tk::BLT::Treeview
In: | tk/lib/tkextlib/blt/treeview.rb
Parent: | TkWindow

Methods

__destroy_hook__ __item_validation_class_list __validation_class_list _find_exec_flag_value bbox button_activate button_bind button_bind_append button_bind_remove button_bindinfo close close_recurse column_activate column_delete column_insert column_invoke column_move column_names column_nearest curselection delete entry_activate entry_before? entry_children entry_delete entry_hidden? entry_open? entry_size entry_size_recurse find get get_full hide index index_at index_at_path insert insert_at move_after move_before move_into nearest open open_recurse range range_open scan_dragto scan_mark screen_bbox see see_anchor selection_anchor selection_cancel selection_clear selection_clear_all selection_include? selection_mark selection_present? selection_set selection_toggle show sort_auto sort_auto= sort_auto? sort_once sort_once_recurse tag_add tag_bind tag_bind_append tag_bind_remove tag_bindinfo tag_delete tag_focus tag_forget tag_names tag_nodes tagid2obj text_apply text_cancel text_delete text_get text_get_root text_icursor text_index text_insert text_selection_adjust text_selection_clear text_selection_from text_selection_present text_selection_range text_selection_to toggle

Included Modules

Scrollable ValidateConfigure ItemValidateConfigure Tk::BLT::Treeview::ConfigMethod

Classes and Modules

Module Tk::BLT::Treeview::ConfigMethod
Module Tk::BLT::Treeview::TagOrID_Methods
Class Tk::BLT::Treeview::FindExecFlagValue
Class Tk::BLT::Treeview::Node
Class Tk::BLT::Treeview::OpenCloseCommand
Class Tk::BLT::Treeview::Tag

Constants

TkCommandNames | = | ['::blt::treeview'.freeze].freeze
WidgetClassName | = | 'TreeView'.freeze

Public Instance methods

__destroy_hook__()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 275
  def __destroy_hook__
    Tk::BLT::Treeview::Node::TreeNodeID_TBL.delete(@path)
    Tk::BLT::Treeview::Tag::TreeTagID_TBL.delete(@path)
  end
__item_validation_class_list(id)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 262
  def __item_validation_class_list(id)
    case id
    when 'entry'
      super(id) << OpenCloseCommand
    else
      super(id)
    end
  end
__validation_class_list()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 254
  def __validation_class_list
    super() << OpenCloseCommand
  end
_find_exec_flag_value(val)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 487
  def _find_exec_flag_value(val)
    if val.kind_of?(Array)
      cmd, *args = val
      FindExecFlagValue.new(cmd, args.join(' '))
    elsif TkComm._callback_entry?(val)
      FindExecFlagValue.new(val)
    else
      val
    end
  end
bbox(*tags)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 304
  def bbox(*tags)
    list(tk_send('bbox', *(tags.collect{|tag| tagid(tag)})))
  end
button_activate(tag)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 338
  def button_activate(tag)
    tk_send('button', 'activate', tagid(tag))
    self
  end
button_bind(tag, seq, *args)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 343
  def button_bind(tag, seq, *args)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    _bind([@path, 'button', 'bind', tagid(tag)], seq, cmd, *args)
    self
  end
button_bind_append(tag, seq, *args)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 352
  def button_bind_append(tag, seq, *args)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    _bind_append([@path, 'button', 'bind', tagid(tag)], seq, cmd, *args)
    self
  end
button_bind_remove(tag, seq)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 361
  def button_bind_remove(tag, seq)
    _bind_remove([@path, 'button', 'bind', tagid(tag)], seq)
    self
  end
button_bindinfo(tag, seq=nil)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 365
  def button_bindinfo(tag, seq=nil)
    _bindinfo([@path, 'button', 'bind', tagid(tag)], seq)
  end
close(*tags)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 369
  def close(*tags)
    tk_send('close', *(tags.collect{|tag| tagid(tag)}))
    self
  end
close_recurse(*tags)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 373
  def close_recurse(*tags)
    tk_send('close', '-recurse', *(tags.collect{|tag| tagid(tag)}))
    self
  end
column_activate(column=None)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 378
  def column_activate(column=None)
    if column == None
      tk_send('column', 'activate')
    else
      tk_send('column', 'activate', column)
      self
    end
  end
column_delete(*fields)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 387
  def column_delete(*fields)
    tk_send('column', 'delete', *fields)
    self
  end
column_insert(pos, field, *opts)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 391
  def column_insert(pos, field, *opts)
    tk_send('column', 'insert', pos, field, *opts)
    self
  end
column_invoke(field)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 395
  def column_invoke(field)
    tk_send('column', 'invoke', field)
    self
  end
column_move(name, dest)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 399
  def column_move(name, dest)
    tk_send('column', 'move', name, dest)
    self
  end
column_names()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 403
  def column_names()
    simplelist(tk_send('column', 'names'))
  end
column_nearest(x, y=None)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 406
  def column_nearest(x, y=None)
    tk_send('column', 'nearest', x, y)
  end
curselection()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 410
  def curselection
    simplelist(tk_send('curselection')).collect{|id| tagid2obj(id)}
  end
delete(*tags)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 414
  def delete(*tags)
    tk_send('delete', *(tags.collect{|tag| tagid(tag)}))
    self
  end
entry_activate(tag)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 419
  def entry_activate(tag)
    tk_send('entry', 'activate', tagid(tag))
    self
  end
entry_before?(tag1, tag2)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 430
  def entry_before?(tag1, tag2)
    bool(tk_send('entry', 'isbefore', tagid(tag1), tagid(tag2)))
  end
entry_children(tag, first=None, last=None)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 423
  def entry_children(tag, first=None, last=None)
    simplelist(tk_send('entry', 'children', tagid(tag),
                       first, last)).collect{|id| tagid2obj(id)}
  end
entry_delete(tag, first=None, last=None)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 427
  def entry_delete(tag, first=None, last=None)
    tk_send('entry', 'delete', tagid(tag), first, last)
  end
entry_hidden?(tag)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 433
  def entry_hidden?(tag)
    bool(tk_send('entry', 'ishidden', tagid(tag)))
  end
entry_open?(tag)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 436
  def entry_open?(tag)
    bool(tk_send('entry', 'isopen', tagid(tag)))
  end
entry_size(tag)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 440
  def entry_size(tag)
    number(tk_send('entry', 'size', tagid(tag)))
  end
entry_size_recurse(tag)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 443
  def entry_size_recurse(tag)
    number(tk_send('entry', 'size', '-recurse', tagid(tag)))
  end
find(first, last, keys={})

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 500
  def find(first, last, keys={})
    keys = _search_flags(keys)
    keys['exec'] = _find_exec_flag_value(keys['exec']) if keys.key?('exec')
    args = hash_kv(keys) << '--' << tagid(first) << tagid(last)
    simplelist(tk_send('find', *args)).collect{|id| tagid2obj(id)}
  end
get(*tags)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 511
  def get(*tags)
    simplelist(tk_send('get', *(tags.collect{|tag| tagid(tag)})))
  end
get_full(*tags)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 514
  def get_full(*tags)
    simplelist(tk_send('get', '-full', *(tags.collect{|tag| tagid(tag)})))
  end
hide(*tags)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 518
  def hide(*tags)
    if tags[-1].kind_of?(Hash)
      keys = tags.pop
    else
      keys = {}
    end
    keys = _search_flags(keys)
    args = hash_kv(keys) << '--'
    args.concat(tags.collect{|t| tagid(t)})
    tk_send('hide', *args)
    self
  end
index(str)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 531
  def index(str)
    tagid2obj(tk_send('index', str))
  end
index_at(tag, str)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 534
  def index_at(tag, str)
    tagid2obj(tk_send('index', '-at', tagid(tag), str))
  end
index_at_path(tag, str)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 537
  def index_at_path(tag, str)
    tagid2obj(tk_send('index', '-at', tagid(tag), '-path', str))
  end
insert(pos, parent=nil, keys={})

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 541
  def insert(pos, parent=nil, keys={})
    Tk::BLT::Treeview::Node.new(pos, parent, keys)
  end
insert_at(tag, pos, parent=nil, keys={})

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 544
  def insert_at(tag, pos, parent=nil, keys={})
    if parent.kind_of?(Hash)
      keys = parent
      parent = nil
    end

    keys = _symbolkey2str(keys)
    keys['at'] = tagid(tag)

    Tk::BLT::Treeview::Node.new(pos, parent, keys)
  end
move_after(tag, dest)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 560
  def move_after(tag, dest)
    tk_send('move', tagid(tag), 'after', tagid(dest))
    self
  end
move_before(tag, dest)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 556
  def move_before(tag, dest)
    tk_send('move', tagid(tag), 'before', tagid(dest))
    self
  end
move_into(tag, dest)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 564
  def move_into(tag, dest)
    tk_send('move', tagid(tag), 'into', tagid(dest))
    self
  end
nearest(x, y, var=None)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 569
  def nearest(x, y, var=None)
    tagid2obj(tk_send('nearest', x, y, var))
  end
open(*tags)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 573
  def open(*tags)
    tk_send('open', *(tags.collect{|tag| tagid(tag)}))
    self
  end
open_recurse(*tags)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 577
  def open_recurse(*tags)
    tk_send('open', '-recurse', *(tags.collect{|tag| tagid(tag)}))
    self
  end
range(first, last)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 582
  def range(first, last)
    simplelist(tk_send('range', tagid(first), tagid(last))).collect{|id|
      tagid2obj(id)
    }
  end
range_open(first, last)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 587
  def range_open(first, last)
    simplelist(tk_send('range', '-open',
                       tagid(first), tagid(last))).collect{|id|
      tagid2obj(id)
    }
  end
scan_dragto(x, y)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 598
  def scan_dragto(x, y)
    tk_send_without_enc('scan', 'dragto', x, y)
    self
  end
scan_mark(x, y)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 594
  def scan_mark(x, y)
    tk_send_without_enc('scan', 'mark', x, y)
    self
  end
screen_bbox(*tags)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 308
  def screen_bbox(*tags)
    list(tk_send('bbox', '-screen', *(tags.collect{|tag| tagid(tag)})))
  end
see(tag)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 603
  def see(tag)
    tk_send_without_enc('see', tagid(tag))
    self
  end
see_anchor(anchor, tag)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 607
  def see_anchor(anchor, tag)
    tk_send_without_enc('see', '-anchor', anchor, tagid(tag))
    self
  end
selection_anchor(tag)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 612
  def selection_anchor(tag)
    tk_send_without_enc('selection', 'anchor', tagid(tag))
    self
  end
selection_cancel()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 616
  def selection_cancel()
    tk_send_without_enc('selection', 'cancel')
    self
  end
selection_clear(first, last=None)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 620
  def selection_clear(first, last=None)
    tk_send_without_enc('selection', 'clear', tagid(first), tagid(last))
    self
  end
selection_clear_all()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 624
  def selection_clear_all()
    tk_send_without_enc('selection', 'clearall')
    self
  end
selection_include?(tag)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 632
  def selection_include?(tag)
    bool(tk_send('selection', 'include', tagid(tag)))
  end
selection_mark(tag)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 628
  def selection_mark(tag)
    tk_send_without_enc('selection', 'mark', tagid(tag))
    self
  end
selection_present?()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 635
  def selection_present?()
    bool(tk_send('selection', 'present'))
  end
selection_set(first, last=None)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 638
  def selection_set(first, last=None)
    tk_send_without_enc('selection', 'set', tagid(first), tagid(last))
    self
  end
selection_toggle(first, last=None)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 642
  def selection_toggle(first, last=None)
    tk_send_without_enc('selection', 'toggle', tagid(first), tagid(last))
    self
  end
show(*tags)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 647
  def show(*tags)
    if tags[-1].kind_of?(Hash)
      keys = tags.pop
    else
      keys = {}
    end
    keys = _search_flags(keys)
    args = hash_kv(keys) << '--'
    args.concat(tags.collect{|t| tagid(t)})
    tk_send('show', *args)
    self
  end
sort_auto(mode)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 660
  def sort_auto(mode)
    tk_send('sort', 'auto', mode)
    self
  end
sort_auto=(mode)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 664
  def sort_auto=(mode)
    tk_send('sort', 'auto', mode)
    mode
  end
sort_auto?()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 668
  def sort_auto?
    bool(tk_send('sort', 'auto'))
  end
sort_once(*tags)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 671
  def sort_once(*tags)
    tk_send('sort', 'once', *(tags.collect{|tag| tagid(tag)}))
    self
  end
sort_once_recurse(*tags)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 675
  def sort_once_recurse(*tags)
    tk_send('sort', 'once', '-recurse', *(tags.collect{|tag| tagid(tag)}))
    self
  end
tag_add(tag, *ids)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 680
  def tag_add(tag, *ids)
    tk_send('tag', 'add', tagid(tag), *ids)
    self
  end
tag_bind(tag, seq, *args)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 312
  def tag_bind(tag, seq, *args)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    _bind([@path, 'bind', tagid(tag)], seq, cmd, *args)
    self
  end
tag_bind_append(tag, seq, *args)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 321
  def tag_bind_append(tag, seq, *args)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    _bind_append([@path, 'bind', tagid(tag)], seq, cmd, *args)
    self
  end
tag_bind_remove(tag, seq)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 330
  def tag_bind_remove(tag, seq)
    _bind_remove([@path, 'bind', tagid(tag)], seq)
    self
  end
tag_bindinfo(tag, seq=nil)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 334
  def tag_bindinfo(tag, seq=nil)
    _bindinfo([@path, 'bind', tagid(tag)], seq)
  end
tag_delete(tag, *ids)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 684
  def tag_delete(tag, *ids)
    tk_send('tag', 'delete', tagid(tag), *ids)
    self
  end
tag_focus(tag)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 507
  def tag_focus(tag)
    tk_send('focus', tagid(tag))
    self
  end
tag_forget(tag)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 688
  def tag_forget(tag)
    tk_send('tag', 'forget', tagid(tag))
    self
  end
tag_names(id=nil)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 692
  def tag_names(id=nil)
    id = (id)? tagid(id): None

    simplelist(tk_send('tag', 'nodes', id)).collect{|tag|
      Tk::BLT::Treeview::Tag.id2obj(self, tag)
    }
  end
tag_nodes(tag)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 699
  def tag_nodes(tag)
    simplelist(tk_send('tag', 'nodes', tagid(tag))).collect{|id|
      Tk::BLT::Treeview::Node.id2obj(self, id)
    }
  end
tagid2obj(tagid)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 290
  def tagid2obj(tagid)
    if tagid.kind_of?(Integer)
      Tk::BLT::Treeview::Node.id2obj(self, tagid.to_s)
    elsif tagid.kind_of?(String)
      if tagid =~ /^\d+$/
        Tk::BLT::Treeview::Node.id2obj(self, tagid)
      else
        Tk::BLT::Treeview::Tag.id2obj(self, tagid)
      end
    else
      tagid
    end
  end
text_apply()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 705
  def text_apply
    tk_send('text', 'apply')
    self
  end
text_cancel()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 709
  def text_cancel
    tk_send('text', 'cancel')
    self
  end
text_delete(first, last)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 714
  def text_delete(first, last)
    tk_send('text', 'delete', first, last)
    self
  end
text_get(x, y)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 718
  def text_get(x, y)
    tk_send('text', 'get', x, y)
  end
text_get_root(x, y)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 721
  def text_get_root(x, y)
    tk_send('text', 'get', '-root', x, y)
  end
text_icursor(idx)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 724
  def text_icursor(idx)
    tk_send('text', 'icursor', idx)
    self
  end
text_index(idx)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 728
  def text_index(idx)
    num_or_str(tk_send('text', 'index', idx))
  end
text_insert(idx, str)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 731
  def text_insert(idx, str)
    tk_send('text', 'insert', idx, str)
    self
  end
text_selection_adjust(idx)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 736
  def text_selection_adjust(idx)
    tk_send('text', 'selection', 'adjust', idx)
    self
  end
text_selection_clear()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 740
  def text_selection_clear
    tk_send('text', 'selection', 'clear')
    self
  end
text_selection_from(idx)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 744
  def text_selection_from(idx)
    tk_send('text', 'selection', 'from', idx)
    self
  end
text_selection_present()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 748
  def text_selection_present
    num_or_str(tk_send('text', 'selection', 'present'))
  end
text_selection_range(start, last)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 751
  def text_selection_range(start, last)
    tk_send('text', 'selection', 'range', start, last)
    self
  end
text_selection_to(idx)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 755
  def text_selection_to(idx)
    tk_send('text', 'selection', 'to', idx)
    self
  end
toggle(tag)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 760
  def toggle(tag)
    tk_send('toggle', tagid(tag))
    self
  end


Module: Tk::BLT::Treeview::ConfigMethod

Module | Tk::BLT::Treeview::ConfigMethod
In: | tk/lib/tkextlib/blt/treeview.rb

Methods

button_cget button_configinfo button_configure column_cget column_configinfo column_configure current_button_configinfo current_column_configinfo current_entry_configinfo current_sort_configinfo current_text_configinfo entry_cget entry_configinfo entry_configure sort_cget sort_configinfo sort_configure text_cget text_configinfo text_configure

Included Modules

TkItemConfigMethod

Public Instance methods

button_cget(option)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 111
  def button_cget(option)
    itemcget('button', option)
  end
button_configinfo(slot=nil)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 117
  def button_configinfo(slot=nil)
    itemconfiginfo('button', slot)
  end
button_configure(slot, value=None)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 114
  def button_configure(slot, value=None)
    itemconfigure('button', slot, value)
  end
column_cget(name, option)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 98
  def column_cget(name, option)
    itemcget(['column', name], option)
  end
column_configinfo(name, slot=nil)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 104
  def column_configinfo(name, slot=nil)
    itemconfiginfo(['column', name], slot)
  end
column_configure(name, slot, value=None)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 101
  def column_configure(name, slot, value=None)
    itemconfigure(['column', name], slot, value)
  end
current_button_configinfo(slot=nil)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 120
  def current_button_configinfo(slot=nil)
    current_itemconfiginfo('button', slot)
  end
current_column_configinfo(name, slot=nil)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 107
  def current_column_configinfo(name, slot=nil)
    current_itemconfiginfo(['column', name], slot)
  end
current_entry_configinfo(slot=nil)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 160
  def current_entry_configinfo(slot=nil)
    ret = current_itemconfiginfo('entry', slot)

    if (val = ret['bindtags'])
      ret['bindtags'] = val.collect{|tag| TkBindTag.id2obj(tag)}
    end

    ret
  end
current_sort_configinfo(slot=nil)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 179
  def current_sort_configinfo(slot=nil)
    current_itemconfiginfo('sort', slot)
  end
current_text_configinfo(slot=nil)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 192
  def current_text_configinfo(slot=nil)
    current_itemconfiginfo('text', slot)
  end
entry_cget(option)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 124
  def entry_cget(option)
    ret = itemcget('entry', option)
    if option == 'bindtags' || option == :bindtags
      ret.collect{|tag| TkBindTag.id2obj(tag)}
    else
      ret
    end
  end
entry_configinfo(slot=nil)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 135
  def entry_configinfo(slot=nil)
    ret = itemconfiginfo('entry', slot)

    if TkComm::GET_CONFIGINFO_AS_ARRAY
      if slot
        if slot == 'bindtags' || slot == :bindtags
          ret[-2] = ret[-2].collect{|tag| TkBindTag.id2obj(tag)}
          ret[-1] = ret[-1].collect{|tag| TkBindTag.id2obj(tag)}
        end
      else
        inf = ret.assoc('bindtags')
        inf[-2] = inf[-2].collect{|tag| TkBindTag.id2obj(tag)}
        inf[-1] = inf[-1].collect{|tag| TkBindTag.id2obj(tag)}
      end

    else # ! TkComm::GET_CONFIGINFO_AS_ARRAY
      if (inf = ret['bindtags'])
        inf[-2] = inf[-2].collect{|tag| TkBindTag.id2obj(tag)}
        inf[-1] = inf[-1].collect{|tag| TkBindTag.id2obj(tag)}
        ret['bindtags'] = inf
      end
    end

    ret
  end
entry_configure(slot, value=None)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 132
  def entry_configure(slot, value=None)
    itemconfigure('entry', slot, value)
  end
sort_cget(option)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 170
  def sort_cget(option)
    itemcget('sort', option)
  end
sort_configinfo(slot=nil)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 176
  def sort_configinfo(slot=nil)
    itemconfiginfo('sort', slot)
  end
sort_configure(slot, value=None)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 173
  def sort_configure(slot, value=None)
    itemconfigure('sort', slot, value)
  end
text_cget(option)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 183
  def text_cget(option)
    itemcget('text', option)
  end
text_configinfo(slot=nil)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 189
  def text_configinfo(slot=nil)
    itemconfiginfo('text', slot)
  end
text_configure(slot, value=None)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 186
  def text_configure(slot, value=None)
    itemconfigure('text', slot, value)
  end


Class: Tk::BLT::Treeview::FindExecFlagValue

Class | Tk::BLT::Treeview::FindExecFlagValue
In: | tk/lib/tkextlib/blt/treeview.rb
Parent: | TkValidateCommand

Methods

_config_keys

Classes and Modules

Class Tk::BLT::Treeview::FindExecFlagValue::ValidateArgs

Public Class methods

_config_keys()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 482
    def self._config_keys
      []
    end


Class: Tk::BLT::Treeview::FindExecFlagValue::ValidateArgs

Class | Tk::BLT::Treeview::FindExecFlagValue::ValidateArgs
In: | tk/lib/tkextlib/blt/treeview.rb
Parent: | TkUtil::CallbackSubst

Methods

ret_val

Constants

KEY_TBL | = | [ [ ?W, ?w, :widget ], [ ?p, ?s, :name ], [ ?P, ?s, :fullpath ], [ ?#, ?x, :node_id ], nil
PROC_TBL | = | [ [ ?x, TkComm.method(:num_or_str) ], [ ?s, TkComm.method(:string) ], [ ?w, TkComm.method(:window) ], nil

Public Class methods

ret_val(val)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 477
      def self.ret_val(val)
        val
      end


Class: Tk::BLT::Treeview::Node

Class | Tk::BLT::Treeview::Node
In: | tk/lib/tkextlib/blt/treeview.rb
Parent: | TkObject

Methods

id id2obj new new

Included Modules

Tk::BLT::Treeview::TagOrID_Methods

Constants

TreeNodeID_TBL | = | TkCore::INTERP.create_table
TreeNode_ID | = | ['blt_treeview_node'.freeze, '00000'.taint].freeze

Public Class methods

id2obj(tree, id)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 974
  def self.id2obj(tree, id)
    tpath = tree.path
    return id unless TreeNodeID_TBL[tpath]
    if TreeNodeID_TBL[tpath][id]
      TreeNodeID_TBL[tpath][id]
    else
      begin
        self.new(tree, nil, nil, 'node'=>Integer(id))
      rescue
        id
      end
    end
  end
new(tree, pos, parent=nil, keys={})

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 988
  def self.new(tree, pos, parent=nil, keys={})
    if parent.kind_of?(Hash)
      keys = parent
      parent = nil
    end

    keys = _symbolkey2str(keys)
    tpath = tree.path

    if (id = keys['node']) && (obj = TreeNodeID_TBL[tpath][id])
      keys.delete('node')
      tk_call(tree.path, 'move', id, pos, parent) if parent
      return obj
    end

    super(tree, pos, parent, keys)
  end
new(tree, pos, parent, keys)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 1006
  def initialize(tree, pos, parent, keys)
    @parent = @tree = tree
    @tpath = @parent.path

    if (id = keys['node'])
      @path = @id = id
      tk_call(@tpath, 'move', @id, pos, tagid(parent)) if parent
    else
      name = TreeNode_ID.join(TkCore::INTERP._ip_id_).freeze
      TreeNode_ID[1].succ!

      at = keys.delete['at']

      if parent
        if parent.kind_of?(Tk::BLT::Treeview::Node) ||
            parent.kind_of?(Tk::BLT::Treeview::Tag)
          path = [get_full(parent.id)[0], name]
          at = nil # ignore 'at' option
        else
          path = [parent.to_s, name]
        end
      else
        path = name
      end

      if at
        @id = tk_call(@tpath, 'insert', '-at', tagid(at), pos, path, keys)
      else
        @id = tk_call(@tpath, 'insert', pos, path, keys)
      end
      @path = @id
    end

    TreeNodeID_TBL[@tpath] = {} unless TreeNodeID_TBL[@tpath]
    TreeNodeID_TBL[@tpath][@id] = self
  end

Public Instance methods

id()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 1043
  def id
    @id
  end


Class: Tk::BLT::Treeview::OpenCloseCommand

Class | Tk::BLT::Treeview::OpenCloseCommand
In: | tk/lib/tkextlib/blt/treeview.rb
Parent: | TkValidateCommand

Methods

_config_keys

Classes and Modules

Class Tk::BLT::Treeview::OpenCloseCommand::ValidateArgs

Public Class methods

_config_keys()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 249
    def self._config_keys
      ['opencommand', 'closecomand']
    end


Class: Tk::BLT::Treeview::OpenCloseCommand::ValidateArgs

Class | Tk::BLT::Treeview::OpenCloseCommand::ValidateArgs
In: | tk/lib/tkextlib/blt/treeview.rb
Parent: | TkUtil::CallbackSubst

Methods

ret_val

Constants

KEY_TBL | = | [ [ ?W, ?w, :widget ], [ ?p, ?s, :name ], [ ?P, ?s, :fullpath ], [ ?#, ?x, :node_id ], nil
PROC_TBL | = | [ [ ?x, TkComm.method(:num_or_str) ], [ ?s, TkComm.method(:string) ], [ ?w, TkComm.method(:window) ], nil

Public Class methods

ret_val(val)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 244
      def self.ret_val(val)
        val
      end


Class: Tk::BLT::Treeview::Tag

Class | Tk::BLT::Treeview::Tag
In: | tk/lib/tkextlib/blt/treeview.rb
Parent: | TkObject

Methods

add forget id id2obj new new new_by_name nodes remove

Included Modules

Tk::BLT::Treeview::TagOrID_Methods

Constants

TreeTagID_TBL | = | TkCore::INTERP.create_table
TreeTag_ID | = | ['blt_treeview_tag'.freeze, '00000'.taint].freeze

Public Class methods

id2obj(tree, id)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 1058
  def self.id2obj(tree, id)
    tpath = tree.path
    return id unless TreeTagID_TBL[tpath]
    if TreeTagID_TBL[tpath][id]
      TreeTagID_TBL[tpath][id]
    else
      begin
        self.new(tree, nil, nil, 'name'=>Integer(id))
      rescue
        id
      end
    end
  end
new(tree, name, ids)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 1087
  def initialize(tree, name, ids)
    @parent = @tree = tree
    @tpath = @parent.path

    if name
      @path = @id = name
    else
      @path = @id = TreeTag_ID.join(TkCore::INTERP._ip_id_).freeze
      TreeTag_ID[1].succ!
    end

    TreeTagID_TBL[@tpath] = {} unless TreeTagID_TBL[@tpath]
    TreeTagID_TBL[@tpath][@id] = self

    unless ids.empty?
      tk_call(@tpath, 'tag', 'add', @id, *(ids.collect{|id| tagid(id)}))
    end
  end
new(tree, *ids)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 1079
  def self.new(tree, *ids)
    if tree.kind_of?(Array)
      super(tree[0], tree[1], ids)
    else
      super(tree, nil, ids)
    end
  end
new_by_name(tree, name, *ids)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 1072
  def self.new_by_name(tree, name, *ids)
    if (obj = TreeTagID_TBL[tree.path][name])
      return obj
    end
    new([tree, name], ids)
  end

Public Instance methods

add(*ids)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 1120
  def add(*ids)
    tk_call(@tpath, 'tag', 'add', @id, *(ids{|id| tagid(id)}))
    self
  end
forget()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 1130
  def forget
    tk_call(@tpath, 'tag', 'forget', @id)
    self
  end
id()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 1116
  def id
    @id
  end
nodes()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 1135
  def nodes
    simplelist(tk_call(@tpath, 'tag', 'nodes', @id)).collect{|id|
      Tk::BLT::Treeview::Node.id2obj(@tree, id)
    }
  end
remove(*ids)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 1125
  def remove(*ids)
    tk_call(@tpath, 'tag', 'delete', @id, *(ids{|id| tagid(id)}))
    self
  end


Module: Tk::BLT::Treeview::TagOrID_Methods

Module | Tk::BLT::Treeview::TagOrID_Methods
In: | tk/lib/tkextlib/blt/treeview.rb

Methods

bbox bind bind_append bind_remove bindinfo button_activate button_bind button_bind_append button_bind_remove button_bindinfo close close_recurse delete entry_activate entry_before? entry_children entry_delete entry_hidden? entry_open? entry_size entry_size_recurse focus get get_full hide index index_path insert move_after move_before move_into open open_recurse range_open_to range_to screen_bbox see see_anchor selection_anchor selection_clear selection_include? selection_mark selection_set selection_toggle show sort_once sort_once_recurse toggle

Public Instance methods

bbox()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 769
  def bbox
    @tree.bbox(self)
  end
bind(seq, *args)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 776
  def bind(seq, *args)
    @tree.tag_bind(self, seq, *args)
    self
  end
bind_append(seq, *args)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 780
  def bind_append(seq, *args)
    @tree.tag_bind_append(self, seq, *args)
    self
  end
bind_remove(seq)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 784
  def bind_remove(seq)
    @tree.tag_bind_remove(self, seq)
    self
  end
bindinfo(seq=nil)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 788
  def bindinfo(seq=nil)
    @tree.tag_bindinfo(self, seq)
  end
button_activate()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 792
  def button_activate
    @tree.button_activate(self)
    self
  end
button_bind(seq, *args)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 797
  def button_bind(seq, *args)
    @tree.button_bind(self, seq, *args)
    self
  end
button_bind_append(seq, *args)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 801
  def button_bind_append(seq, *args)
    @tree.button_bind_append(self, seq, *args)
    self
  end
button_bind_remove(seq)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 805
  def button_bind_remove(seq)
    @tree.button_bind_remove(self, seq)
    self
  end
button_bindinfo(seq=nil)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 809
  def button_bindinfo(seq=nil)
    @tree.button_bindinfo(self, seq)
  end
close()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 813
  def close
    @tree.close(self)
    self
  end
close_recurse()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 817
  def close_recurse
    @tree.close_recurse(self)
    self
  end
delete()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 822
  def delete
    @tree.delete(self)
    self
  end
entry_activate()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 827
  def entry_activate
    @tree.entry_activate(self)
    self
  end
entry_before?(tag)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 837
  def entry_before?(tag)
    @tree.entry_before?(self, tag)
  end
entry_children(first=None, last=None)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 831
  def entry_children(first=None, last=None)
    @tree.entry_children(self, first, last)
  end
entry_delete(first=None, last=None)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 834
  def entry_delete(first=None, last=None)
    @tree.entry_delete(self, first, last)
  end
entry_hidden?()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 840
  def entry_hidden?
    @tree.entry_before?(self)
  end
entry_open?()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 843
  def entry_open?
    @tree.entry_open?(self)
  end
entry_size()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 847
  def entry_size
    @tree.entry_size(self)
  end
entry_size_recurse()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 850
  def entry_size_recurse
    @tree.entry_size_recurse(self)
  end
focus()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 854
  def focus
    @tree.tag_focus(self)
    self
  end
get()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 859
  def get
    @tree.get(self)
  end
get_full()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 862
  def get_full
    @tree.get_full(self)
  end
hide()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 866
  def hide
    @tree.hide(self)
    self
  end
index(str)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 871
  def index(str)
    @tree.index_at(self, str)
  end
index_path(str)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 874
  def index_path(str)
    @tree.index_at_path(self, str)
  end
insert(pos, parent=nil, keys={})

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 878
  def insert(pos, parent=nil, keys={})
    @tree.insert_at(self, pos, parent, keys)
  end
move_after(dest)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 886
  def move_after(dest)
    @tree.move_after(self, dest)
    self
  end
move_before(dest)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 882
  def move_before(dest)
    @tree.move_before(self, dest)
    self
  end
move_into(dest)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 890
  def move_into(dest)
    @tree.move_into(self, dest)
    self
  end
open()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 895
  def open
    @tree.open(self)
    self
  end
open_recurse()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 899
  def open_recurse
    @tree.open_recurse(self)
    self
  end
range_open_to(tag)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 907
  def range_open_to(tag)
    @tree.range(self, tag)
  end
range_to(tag)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 904
  def range_to(tag)
    @tree.range(self, tag)
  end
screen_bbox()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 772
  def screen_bbox
    @tree.screen_bbox(self)
  end
see()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 911
  def see
    @tree.see(self)
    self
  end
see_anchor(anchor)

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 915
  def see_anchor(anchor)
    @tree.see_anchor(anchor, self)
    self
  end
selection_anchor()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 920
  def selection_anchor
    @tree.selection_anchor(self)
    self
  end
selection_clear()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 924
  def selection_clear
    @tree.selection_clear(self)
    self
  end
selection_include?()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 932
  def selection_include?
    @tree.selection_include?(self)
  end
selection_mark()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 928
  def selection_mark
    @tree.selection_mark(self)
    self
  end
selection_set()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 935
  def selection_set
    @tree.selection_set(self)
    self
  end
selection_toggle()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 939
  def selection_toggle
    @tree.selection_toggle(self)
    self
  end
show()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 944
  def show
    @tree.show(self)
    self
  end
sort_once()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 949
  def sort_once
    @tree.sort_once(self)
    self
  end
sort_once_recurse()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 953
  def sort_once_recurse
    @tree.sort_once_recurse(self)
    self
  end
toggle()

[Source]

# File tk/lib/tkextlib/blt/treeview.rb, line 958
  def toggle
    @tree.toggle(self)
    self
  end


Class: Tk::BLT::Vector

Class | Tk::BLT::Vector
In: | tk/lib/tkextlib/blt/vector.rb
Parent: | TkVariable

Methods

* + - / [] []= append binread clear create delete destroy destroy dup_vector expr expr index inspect length length= merge names new normalize notify offset offset= populate random range search seq set sort sort_reverse split to_s variable

Constants

TkCommandNames = ['::blt::vector'.freeze].freeze

Public Class methods

create(*args)

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 13
    def self.create(*args)
      tk_call('::blt::vector', 'create', *args)
    end
destroy(*args)

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 17
    def self.destroy(*args)
      tk_call('::blt::vector', 'destroy', *args)
    end
expr(expression)

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 21
    def self.expr(expression)
      tk_call('::blt::vector', 'expr', expression)
    end
names(pat=None)

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 25
    def self.names(pat=None)
      simplelist(tk_call('::blt::vector', 'names', pat)).collect{|name|
        if TkVar_ID_TBL[name]
          TkVar_ID_TBL[name]
        elsif name[0..1] == '::' && TkVar_ID_TBL[name[2..-1]]
          TkVar_ID_TBL[name[2..-1]]
        else
          name
        end
      }
    end
new(size=nil, keys={})

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 39
    def initialize(size=nil, keys={})
      if size.kind_of?(Hash)
        keys = size
        size = nil
      end
      if size.kind_of?(Array)
        # [first, last]
        size = size.join(':')
      end
      if size
        @id = INTERP._invoke('::blt::vector', 'create',
                             "#auto(#{size})", *hash_kv(keys))
      else
        @id = INTERP._invoke('::blt::vector', 'create',
                             "#auto", *hash_kv(keys))
      end

      TkVar_ID_TBL[@id] = self

      @def_default = false
      @default_val = nil

      @trace_var  = nil
      @trace_elem = nil
      @trace_opts = nil

      # teach Tk-ip that @id is global var
      INTERP._invoke_without_enc('global', @id)
    end

Public Instance methods

*(item)

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 81
    def *(item)
      list(tk_call(@id, '*', item))
    end
+(item)

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 85
    def +(item)
      list(tk_call(@id, '+', item))
    end
-(item)

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 89
    def -(item)
      list(tk_call(@id, '-', item))
    end
/(item)

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 93
    def /(item)
      list(tk_call(@id, '/', item))
    end
[](idx)

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 135
    def [](idx)
      index(idx)
    end
[]=(idx, val)

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 139
    def []=(idx, val)
      index(idx, val)
    end
append(*vectors)

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 97
    def append(*vectors)
      tk_call(@id, 'append', *vectors)
    end
binread(channel, len=None, keys={})

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 101
    def binread(channel, len=None, keys={})
      if len.kind_of?(Hash)
        keys = len
        len = None
      end
      keys = _symbolkey2str(keys)
      keys['swap'] = None if keys.delete('swap')
      tk_call(@id, 'binread', channel, len, keys)
    end
clear()

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 111
    def clear()
      tk_call(@id, 'clear')
      self
    end
delete(*indices)

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 116
    def delete(*indices)
      tk_call(@id, 'delete', *indices)
      self
    end
destroy()

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 69
    def destroy
      tk_call('::blt::vector', 'destroy', @id)
    end
dup_vector(vec)

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 121
    def dup_vector(vec)
      tk_call(@id, 'dup', vec)
      self
    end
expr(expression)

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 126
    def expr(expression)
      tk_call(@id, 'expr', expression)
      self
    end
index(idx, val=None)

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 131
    def index(idx, val=None)
      number(tk_call(@id, 'index', idx, val))
    end
inspect()

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 73
    def inspect
      '#<Tk::BLT::Vector: ' + @id + '>'
    end
length()

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 143
    def length()
      number(tk_call(@id, 'length'))
    end
length=(size)

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 147
    def length=(size)
      number(tk_call(@id, 'length', size))
    end
merge(*vectors)

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 151
    def merge(*vectors)
      tk_call(@id, 'merge', *vectors)
      self
    end
normalize(vec=None)

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 156
    def normalize(vec=None)
      tk_call(@id, 'normalize', vec)
      self
    end
notify(keyword)

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 161
    def notify(keyword)
      tk_call(@id, 'notify', keyword)
      self
    end
offset()

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 166
    def offset()
      number(tk_call(@id, 'offset'))
    end
offset=(val)

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 170
    def offset=(val)
      number(tk_call(@id, 'offset', val))
    end
populate(vector, density=None)

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 178
    def populate(vector, density=None)
      tk_call(@id, 'populate', vector, density)
      self
    end
random()

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 174
    def random()
      tk_call(@id, 'random')
    end
range(first, last=None)

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 183
    def range(first, last=None)
      list(tk_call(@id, 'range', first, last))
    end
search(val1, val2=None)

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 187
    def search(val1, val2=None)
      list(tk_call(@id, 'search', val1, val2))
    end
seq(start, finish=None, step=None)

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 196
    def seq(start, finish=None, step=None)
      tk_call(@id, 'seq', start, finish, step)
      self
    end
set(item)

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 191
    def set(item)
      tk_call(@id, 'set', item)
      self
    end
sort(*vectors)

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 201
    def sort(*vectors)
      tk_call(@id, 'sort', *vectors)
      self
    end
sort_reverse(*vectors)

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 206
    def sort_reverse(*vectors)
      tk_call(@id, 'sort', '-reverse', *vectors)
      self
    end
split(*vectors)

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 211
    def split(*vectors)
      tk_call(@id, 'split', *vectors)
      self
    end
to_s()

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 77
    def to_s
      @id
    end
variable(var)

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 216
    def variable(var)
      tk_call(@id, 'variable', var)
      self
    end


Class: Tk::BLT::VectorAccess

Class | Tk::BLT::VectorAccess
In: | tk/lib/tkextlib/blt/vector.rb
Parent: | Vector

Methods

new new

Public Class methods

new(name)

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 223
    def self.new(name)
      return TkVar_ID_TBL[name] if TkVar_ID_TBL[name]
      super(name, size=nil, keys={})
    end
new(vec_name)

[Source]

# File tk/lib/tkextlib/blt/vector.rb, line 228
    def initialize(vec_name)
      @id = vec_name
      TkVar_ID_TBL[@id] = self

      @def_default = false
      @default_val = nil

      @trace_var  = nil
      @trace_elem = nil
      @trace_opts = nil

      # teach Tk-ip that @id is global var
      INTERP._invoke_without_enc('global', @id)
    end


Class: Tk::BLT::Watch

Class | Tk::BLT::Watch
In: | tk/lib/tkextlib/blt/watch.rb
Parent: | TkObject

Methods

activate cget configinfo deactivate delete info names new

Constants

TkCommandNames | = | ['::blt::watch'.freeze].freeze
WATCH_ID_TBL | = | TkCore::INTERP.create_table
BLT_WATCH_ID | = | ['blt_watch_id'.freeze, '00000'.taint].freeze

Public Class methods

names(state = None)

[Source]

# File tk/lib/tkextlib/blt/watch.rb, line 18
    def self.names(state = None)
      tk_split_list(tk_call('::blt::watch', 'names', state)).collect{|name|
        WATCH_ID_TBL[name] || name
      }
    end
new(name = nil, keys = {})

[Source]

# File tk/lib/tkextlib/blt/watch.rb, line 39
    def initialize(name = nil, keys = {})
      if name.kind_of?(Hash)
        keys = name
        name = nil
      end

      if name
        @id = name.to_s
      else
        @id = BLT_WATCH_ID.join(TkCore::INTERP._ip_id_)
        BLT_WATCH_ID[1].succ!
      end

      @path = @id

      WATCH_ID_TBL[@id] = self
      tk_call('::blt::watch', 'create', @id, *hash_kv(keys))
    end

Public Instance methods

activate()

[Source]

# File tk/lib/tkextlib/blt/watch.rb, line 58
    def activate
      tk_call('::blt::watch', 'activate', @id)
      self
    end
cget(key)

[Source]

# File tk/lib/tkextlib/blt/watch.rb, line 133
    def cget(key)
      key = key.to_s
      begin
        info.assoc(key)[1]
      rescue
        fail ArgumentError, "unknown option '#{key}'"
      end
    end
configinfo(slot = nil)

[Source]

# File tk/lib/tkextlib/blt/watch.rb, line 116
    def configinfo(slot = nil)
      if slot
        slot = slot.to_s
        v = cget(slot)
        if TkComm::GET_CONFIGINFO_AS_ARRAY
          [slot, v]
        else
          {slot=>v}
        end
      else
        if TkComm::GET_CONFIGINFO_AS_ARRAY
          info
        else
          Hash[*(info.flatten)]
        end
      end
    end
deactivate()

[Source]

# File tk/lib/tkextlib/blt/watch.rb, line 62
    def deactivate
      tk_call('::blt::watch', 'deactivate', @id)
      self
    end
delete()

[Source]

# File tk/lib/tkextlib/blt/watch.rb, line 66
    def delete
      tk_call('::blt::watch', 'delete', @id)
      self
    end
info()

[Source]

# File tk/lib/tkextlib/blt/watch.rb, line 70
    def info
      ret = []
      lst = tk_split_simplelist(tk_call('::blt::watch', 'info', @id))
      until lst.empty?
        k, v, *lst = lst
        k = k[1..-1]
        case k
        when /^(#{__strval_optkeys.join('|')})$/
          # do nothing

        when /^(#{__numval_optkeys.join('|')})$/
          begin
            v = number(v)
          rescue
            v = nil
          end

        when /^(#{__numstrval_optkeys.join('|')})$/
          v = num_or_str(v)

        when /^(#{__boolval_optkeys.join('|')})$/
          begin
            v = bool(v)
          rescue
            v = nil
          end

        when /^(#{__listval_optkeys.join('|')})$/
          v = simplelist(v)

        when /^(#{__numlistval_optkeys.join('|')})$/
          v = list(v)

        else
          if v.index('{')
            v = tk_split_list(v)
          else
            v = tk_tcl2ruby(v)
          end
        end

        ret << [k, v]
      end

      ret
    end


Module: Tk::BLT::Winop

Module | Tk::BLT::Winop
In: | tk/lib/tkextlib/blt/winop.rb

Constants

TkCommandNames = ['::blt::winop'.freeze].freeze


Module: Tk::BWidget
In: tk/lib/tkextlib/bwidget.rb
tk/lib/tkextlib/bwidget/widget.rb
tk/lib/tkextlib/bwidget/tree.rb
tk/lib/tkextlib/bwidget/titleframe.rb
tk/lib/tkextlib/bwidget/statusbar.rb
tk/lib/tkextlib/bwidget/spinbox.rb
tk/lib/tkextlib/bwidget/separator.rb
tk/lib/tkextlib/bwidget/selectfont.rb
tk/lib/tkextlib/bwidget/selectcolor.rb
tk/lib/tkextlib/bwidget/scrollview.rb
tk/lib/tkextlib/bwidget/scrolledwindow.rb
tk/lib/tkextlib/bwidget/scrollableframe.rb
tk/lib/tkextlib/bwidget/progressdlg.rb
tk/lib/tkextlib/bwidget/progressbar.rb
tk/lib/tkextlib/bwidget/passwddlg.rb
tk/lib/tkextlib/bwidget/panelframe.rb
tk/lib/tkextlib/bwidget/panedwindow.rb
tk/lib/tkextlib/bwidget/pagesmanager.rb
tk/lib/tkextlib/bwidget/notebook.rb
tk/lib/tkextlib/bwidget/messagedlg.rb
tk/lib/tkextlib/bwidget/mainframe.rb
tk/lib/tkextlib/bwidget/listbox.rb
tk/lib/tkextlib/bwidget/labelframe.rb
tk/lib/tkextlib/bwidget/labelentry.rb
tk/lib/tkextlib/bwidget/label.rb
tk/lib/tkextlib/bwidget/entry.rb
tk/lib/tkextlib/bwidget/dynamichelp.rb
tk/lib/tkextlib/bwidget/dropsite.rb
tk/lib/tkextlib/bwidget/dragsite.rb
tk/lib/tkextlib/bwidget/dialog.rb
tk/lib/tkextlib/bwidget/combobox.rb
tk/lib/tkextlib/bwidget/buttonbox.rb
tk/lib/tkextlib/bwidget/button.rb
tk/lib/tkextlib/bwidget/bitmap.rb
tk/lib/tkextlib/bwidget/arrowbutton.rb

Methods

XLFDfont assert badOptionString bindMouseWheel classes clonename focus get3dcolor getname grab inuse library lreorder package_name package_version parsetext place write wrongNumArgsString

Classes and Modules

Module Tk::BWidget::DragSite
Module Tk::BWidget::DropSite
Module Tk::BWidget::DynamicHelp
Module Tk::BWidget::Widget
Class Tk::BWidget::ArrowButton
Class Tk::BWidget::Bitmap
Class Tk::BWidget::Button
Class Tk::BWidget::ButtonBox
Class Tk::BWidget::ComboBox
Class Tk::BWidget::Dialog
Class Tk::BWidget::Entry
Class Tk::BWidget::Label
Class Tk::BWidget::LabelEntry
Class Tk::BWidget::LabelFrame
Class Tk::BWidget::ListBox
Class Tk::BWidget::MainFrame
Class Tk::BWidget::MessageDlg
Class Tk::BWidget::NoteBook
Class Tk::BWidget::PagesManager
Class Tk::BWidget::PanedWindow
Class Tk::BWidget::PanelFrame
Class Tk::BWidget::PasswdDlg
Class Tk::BWidget::ProgressBar
Class Tk::BWidget::ProgressDlg
Class Tk::BWidget::ScrollView
Class Tk::BWidget::ScrollableFrame
Class Tk::BWidget::ScrolledWindow
Class Tk::BWidget::SelectColor
Class Tk::BWidget::SelectFont
Class Tk::BWidget::Separator
Class Tk::BWidget::SpinBox
Class Tk::BWidget::StatusBar
Class Tk::BWidget::TitleFrame
Class Tk::BWidget::Tree

Constants

LIBRARY | = | tk_call('set', '::BWIDGET::LIBRARY')
PACKAGE_NAME | = | 'BWidget'.freeze

Public Class methods

XLFDfont(cmd, *args)

[Source]

# File tk/lib/tkextlib/bwidget.rb, line 39
    def self.XLFDfont(cmd, *args)
      if args[-1].kind_of?(Hash)
        keys = args.pop
        args.concat(hash_kv(keys))
      end
      tk_call('BWidget::XLFDfont', cmd, *args)
    end
assert(exp, msg=None)

[Source]

# File tk/lib/tkextlib/bwidget.rb, line 47
    def self.assert(exp, msg=None)
      tk_call('BWidget::assert', exp, msg)
    end
badOptionString(type, value, list)

[Source]

# File tk/lib/tkextlib/bwidget.rb, line 51
    def self.badOptionString(type, value, list)
      tk_call('BWidget::badOptionString', type, value, list)
    end
bindMouseWheel(widget)

[Source]

# File tk/lib/tkextlib/bwidget.rb, line 55
    def self.bindMouseWheel(widget)
      tk_call('BWidget::bindMouseWheel', widget)
    end
classes(klass)

[Source]

# File tk/lib/tkextlib/bwidget.rb, line 59
    def self.classes(klass)
      list(tk_call('BWidget::classes', klass))
    end
clonename(menu)

[Source]

# File tk/lib/tkextlib/bwidget.rb, line 63
    def self.clonename(menu)
      tk_call('BWidget::clonename', menu)
    end
focus(opt, path)

[Source]

# File tk/lib/tkextlib/bwidget.rb, line 67
    def self.focus(opt, path)
      tk_call('BWidget::focus', opt, path)
    end
get3dcolor(path, bgcolor)

[Source]

# File tk/lib/tkextlib/bwidget.rb, line 71
    def self.get3dcolor(path, bgcolor)
      tk_call('BWidget::get3dcolor', path, bgcolor)
    end
getname(name)

[Source]

# File tk/lib/tkextlib/bwidget.rb, line 75
    def self.getname(name)
      tk_call('BWidget::getname', name)
    end
grab(opt, path)

[Source]

# File tk/lib/tkextlib/bwidget.rb, line 79
    def self.grab(opt, path)
      tk_call('BWidget::grab', opt, path)
    end
inuse(klass)

[Source]

# File tk/lib/tkextlib/bwidget.rb, line 83
    def self.inuse(klass)
      bool(tk_call('BWidget::inuse', klass))
    end
library(klass, *klasses)

[Source]

# File tk/lib/tkextlib/bwidget.rb, line 87
    def self.library(klass, *klasses)
      tk_call('BWidget::library', klass, *klasses)
    end
lreorder(list, neworder)

[Source]

# File tk/lib/tkextlib/bwidget.rb, line 91
    def self.lreorder(list, neworder)
      tk_call('BWidget::lreorder', list, neworder)
    end
package_name()

[Source]

# File tk/lib/tkextlib/bwidget.rb, line 27
    def self.package_name
      PACKAGE_NAME
    end
package_version()

[Source]

# File tk/lib/tkextlib/bwidget.rb, line 31
    def self.package_version
      begin
        TkPackage.require('BWidget')
      rescue
        ''
      end
    end
parsetext(text)

[Source]

# File tk/lib/tkextlib/bwidget.rb, line 95
    def self.parsetext(text)
      tk_call('BWidget::parsetext', text)
    end
place(path, w, h, *args)

[Source]

# File tk/lib/tkextlib/bwidget.rb, line 99
    def self.place(path, w, h, *args)
      if args[-1].kind_of?(Hash)
        keys = args.pop
        args.concat(hash_kv(keys))
      end
      tk_call('BWidget::place', path, w, h, *(args.flatten))
    end
write(file, mode=None)

[Source]

# File tk/lib/tkextlib/bwidget.rb, line 107
    def self.write(file, mode=None)
      tk_call('BWidget::write', file, mode)
    end
wrongNumArgsString(str)

[Source]

# File tk/lib/tkextlib/bwidget.rb, line 111
    def self.wrongNumArgsString(str)
      tk_call('BWidget::wrongNumArgsString', str)
    end


Class: Tk::BWidget::ArrowButton

Class | Tk::BWidget::ArrowButton
In: | tk/lib/tkextlib/bwidget/arrowbutton.rb
Parent: | Tk::BWidget::Button

Constants

TkCommandNames | = | ['ArrowButton'.freeze].freeze
WidgetClassName | = | 'ArrowButton'.freeze


Class: Tk::BWidget::Bitmap

Class | Tk::BWidget::Bitmap
In: | tk/lib/tkextlib/bwidget/bitmap.rb
Parent: | TkPhotoImage

Methods

new

Public Class methods

new(name)

[Source]

# File tk/lib/tkextlib/bwidget/bitmap.rb, line 17
  def initialize(name)
    @path = tk_call_without_enc('Bitmap::get', name)
    Tk_IMGTBL[@path] = self
  end


Class: Tk::BWidget::Button

Class | Tk::BWidget::Button
In: | tk/lib/tkextlib/bwidget/button.rb
Parent: | TkButton

Constants

TkCommandNames | = | ['Button'.freeze].freeze
WidgetClassName | = | 'Button'.freeze


Class: Tk::BWidget::ButtonBox

Class | Tk::BWidget::ButtonBox
In: | tk/lib/tkextlib/bwidget/buttonbox.rb
Parent: | TkWindow

Methods

add delete index insert invoke set_focus tagid

Included Modules

TkItemConfigMethod

Constants

TkCommandNames | = | ['ButtonBox'.freeze].freeze
WidgetClassName | = | 'ButtonBox'.freeze

Public Instance methods

add(keys={}, &b)

[Source]

# File tk/lib/tkextlib/bwidget/buttonbox.rb, line 41
  def add(keys={}, &b)
    win = window(tk_send('add', *hash_kv(keys)))
    win.instance_eval(&b) if b
    win
  end
delete(idx)

[Source]

# File tk/lib/tkextlib/bwidget/buttonbox.rb, line 47
  def delete(idx)
    tk_send('delete', tagid(idx))
    self
  end
index(idx)

[Source]

# File tk/lib/tkextlib/bwidget/buttonbox.rb, line 52
  def index(idx)
    if idx.kind_of?(Tk::BWidget::Button)
      name = idx[:name]
      idx = name unless name.empty?
    end
    if idx.kind_of?(TkButton)
      idx = idx[:text]
    end
    number(tk_send('index', idx.to_s))
  end
insert(idx, keys={}, &b)

[Source]

# File tk/lib/tkextlib/bwidget/buttonbox.rb, line 63
  def insert(idx, keys={}, &b)
    win = window(tk_send('insert', tagid(idx), *hash_kv(keys)))
    win.instance_eval(&b) if b
    win
  end
invoke(idx)

[Source]

# File tk/lib/tkextlib/bwidget/buttonbox.rb, line 69
  def invoke(idx)
    tk_send('invoke', tagid(idx))
    self
  end
set_focus(idx)

[Source]

# File tk/lib/tkextlib/bwidget/buttonbox.rb, line 74
  def set_focus(idx)
    tk_send('setfocus', tagid(idx))
    self
  end
tagid(tagOrId)

[Source]

# File tk/lib/tkextlib/bwidget/buttonbox.rb, line 29
  def tagid(tagOrId)
    if tagOrId.kind_of?(Tk::BWidget::Button)
      name = tagOrId[:name]
      return index(name) unless name.empty?
    end
    if tagOrId.kind_of?(TkButton)
      return index(tagOrId[:text])
    end
    # index(tagOrId.to_s)
    index(_get_eval_string(tagOrId))
  end


Class: Tk::BWidget::ComboBox

Class | Tk::BWidget::ComboBox
In: | tk/lib/tkextlib/bwidget/combobox.rb
Parent: | Tk::BWidget::SpinBox

Methods

get_listbox icursor post unpost

Included Modules

Scrollable

Constants

TkCommandNames | = | ['ComboBox'.freeze].freeze
WidgetClassName | = | 'ComboBox'.freeze

Public Instance methods

get_listbox(&b)

[Source]

# File tk/lib/tkextlib/bwidget/combobox.rb, line 26
  def get_listbox(&b)
    win = window(tk_send_without_enc('getlistbox'))
    win.instance_eval(&b) if b
    win
  end
icursor(idx)

[Source]

# File tk/lib/tkextlib/bwidget/combobox.rb, line 32
  def icursor(idx)
    tk_send_without_enc('icursor', idx)
  end
post()

[Source]

# File tk/lib/tkextlib/bwidget/combobox.rb, line 36
  def post
    tk_send_without_enc('post')
    self
  end
unpost()

[Source]

# File tk/lib/tkextlib/bwidget/combobox.rb, line 41
  def unpost
    tk_send_without_enc('unpost')
    self
  end


Class: Tk::BWidget::Dialog

Class | Tk::BWidget::Dialog
In: | tk/lib/tkextlib/bwidget/dialog.rb
Parent: | TkWindow

Methods

add cget configinfo configure create_self draw enddialog get_buttonbox get_frame index invoke new set_focus tagid withdraw

Included Modules

TkItemConfigMethod

Constants

TkCommandNames | = | ['Dialog'.freeze].freeze
WidgetClassName | = | 'Dialog'.freeze

Public Class methods

new(parent=nil, keys=nil)

[Source]

# File tk/lib/tkextlib/bwidget/dialog.rb, line 35
  def initialize(parent=nil, keys=nil)
    @relative = ''
    if parent.kind_of?(Hash)
      keys = _symbolkey2str(parent)
      @relative = keys['parent'] if keys.key?('parent')
      @relative = keys.delete('relative') if keys.key?('relative')
      super(keys)
    elsif keys
      keys = _symbolkey2str(keys)
      @relative = keys.delete('parent') if keys.key?('parent')
      @relative = keys.delete('relative') if keys.key?('relative')
      super(parent, keys)
    else
      super(parent)
    end
  end

Public Instance methods

add(keys={}, &b)

[Source]

# File tk/lib/tkextlib/bwidget/dialog.rb, line 113
  def add(keys={}, &b)
    win = window(tk_send('add', *hash_kv(keys)))
    win.instance_eval(&b) if b
    win
  end
cget(slot)

[Source]

# File tk/lib/tkextlib/bwidget/dialog.rb, line 62
  def cget(slot)
    if slot.to_s == 'relative'
      super('parent')
    else
      super(slot)
    end
  end
configinfo(slot=nil)

[Source]

# File tk/lib/tkextlib/bwidget/dialog.rb, line 84
  def configinfo(slot=nil)
    if slot
      if slot.to_s == 'relative'
        super('parent')
      else
        super(slot)
      end
    else
      ret = super()
      if TkComm::GET_CONFIGINFO_AS_ARRAY
        ret << ['relative', 'parent']
      else
        ret['relative'] = 'parent'
      end
    end
  end
configure(slot, value=None)

[Source]

# File tk/lib/tkextlib/bwidget/dialog.rb, line 70
  def configure(slot, value=None)
    if slot.kind_of?(Hash)
      slot = _symbolkey2str(slot)
      slot['parent'] = slot.delete('relative') if slot.key?('relative')
      super(slot)
    else
      if slot.to_s == 'relative'
        super('parent', value)
      else
        super(slot, value)
      end
    end
  end
create_self(keys)

[Source]

# File tk/lib/tkextlib/bwidget/dialog.rb, line 52
  def create_self(keys)
    cmd = self.class::TkCommandNames[0]
    if keys and keys != None
      tk_call_without_enc(cmd, @path, '-parent', @relative,
                          *hash_kv(keys, true))
    else
      tk_call_without_enc(cmd, @path, '-parent', @relative)
    end
  end
draw(focus_win=None)

[Source]

# File tk/lib/tkextlib/bwidget/dialog.rb, line 131
  def draw(focus_win=None)
    tk_send('draw', focus_win)
  end
enddialog(ret)

[Source]

# File tk/lib/tkextlib/bwidget/dialog.rb, line 135
  def enddialog(ret)
    tk_send('enddialog', ret)
  end
get_buttonbox(&b)

[Source]

# File tk/lib/tkextlib/bwidget/dialog.rb, line 125
  def get_buttonbox(&b)
    win = window(@path + '.bbox')
    win.instance_eval(&b) if b
    win
  end
get_frame(&b)

[Source]

# File tk/lib/tkextlib/bwidget/dialog.rb, line 119
  def get_frame(&b)
    win = window(tk_send('getframe'))
    win.instance_eval(&b) if b
    win
  end
index(idx)

[Source]

# File tk/lib/tkextlib/bwidget/dialog.rb, line 139
  def index(idx)
    get_buttonbox.index(idx)
  end
invoke(idx)

[Source]

# File tk/lib/tkextlib/bwidget/dialog.rb, line 143
  def invoke(idx)
    tk_send('invoke', tagid(idx))
    self
  end
set_focus(idx)

[Source]

# File tk/lib/tkextlib/bwidget/dialog.rb, line 148
  def set_focus(idx)
    tk_send('setfocus', tagid(idx))
    self
  end
tagid(tagOrId)

[Source]

# File tk/lib/tkextlib/bwidget/dialog.rb, line 101
  def tagid(tagOrId)
    if tagOrId.kind_of?(Tk::BWidget::Button)
      name = tagOrId[:name]
      return index(name) unless name.empty?
    end
    if tagOrId.kind_of?(TkButton)
      return index(tagOrId[:text])
    end
    # index(tagOrId.to_s)
    index(_get_eval_string(tagOrId))
  end
withdraw()

[Source]

# File tk/lib/tkextlib/bwidget/dialog.rb, line 153
  def withdraw
    tk_send('withdraw')
    self
  end


Module: Tk::BWidget::DragSite

Module | Tk::BWidget::DragSite
In: | tk/lib/tkextlib/bwidget/dragsite.rb

Methods

include register set_drag

Included Modules

Tk

Public Class methods

include(klass, type, event)

[Source]

# File tk/lib/tkextlib/bwidget/dragsite.rb, line 20
  def self.include(klass, type, event)
    tk_call('DragSite::include', klass, type, event)
  end
register(path, keys={})

[Source]

# File tk/lib/tkextlib/bwidget/dragsite.rb, line 24
  def self.register(path, keys={})
    tk_call('DragSite::register', path, *hash_kv(keys))
  end
set_drag(path, subpath, initcmd, endcmd, force=None)

[Source]

# File tk/lib/tkextlib/bwidget/dragsite.rb, line 28
  def self.set_drag(path, subpath, initcmd, endcmd, force=None)
    tk_call('DragSite::setdrag', path, subpath, initcmd, endcmd, force)
  end


Module: Tk::BWidget::DropSite

Module | Tk::BWidget::DropSite
In: | tk/lib/tkextlib/bwidget/dropsite.rb

Methods

include register set_cursor set_drop set_operation

Included Modules

Tk

Public Class methods

include(klass, type)

[Source]

# File tk/lib/tkextlib/bwidget/dropsite.rb, line 20
  def self.include(klass, type)
    tk_call('DropSite::include', klass, type)
  end
register(path, keys={})

[Source]

# File tk/lib/tkextlib/bwidget/dropsite.rb, line 24
  def self.register(path, keys={})
    tk_call('DropSite::register', path, *hash_kv(keys))
  end
set_cursor(cursor)

[Source]

# File tk/lib/tkextlib/bwidget/dropsite.rb, line 28
  def self.set_cursor(cursor)
    tk_call('DropSite::setcursor', cursor)
  end
set_drop(path, subpath, dropover, drop, force=None)

[Source]

# File tk/lib/tkextlib/bwidget/dropsite.rb, line 32
  def self.set_drop(path, subpath, dropover, drop, force=None)
    tk_call('DropSite::setdrop', path, subpath, dropover, drop, force)
  end
set_operation(op)

[Source]

# File tk/lib/tkextlib/bwidget/dropsite.rb, line 36
  def self.set_operation(op)
    tk_call('DropSite::setoperation', op)
  end


Module: Tk::BWidget::DynamicHelp

Module | Tk::BWidget::DynamicHelp
In: | tk/lib/tkextlib/bwidget/dynamichelp.rb

Methods

__cget_cmd __config_cmd __pathname add cget delete include sethelp

Included Modules

Tk

Public Class methods

__cget_cmd()

[Source]

# File tk/lib/tkextlib/bwidget/dynamichelp.rb, line 29
  def self.__cget_cmd
    ['DynamicHelp::configure']
  end
__config_cmd()

[Source]

# File tk/lib/tkextlib/bwidget/dynamichelp.rb, line 33
  def self.__config_cmd
    ['DynamicHelp::configure']
  end
__pathname()

[Source]

# File tk/lib/tkextlib/bwidget/dynamichelp.rb, line 20
  def self.__pathname
    'DynamicHelp::configure'
  end
add(widget, keys={})

[Source]

# File tk/lib/tkextlib/bwidget/dynamichelp.rb, line 41
  def self.add(widget, keys={})
    tk_call('DynamicHelp::add', widget, *hash_kv(keys))
  end
cget(slot)

[Source]

# File tk/lib/tkextlib/bwidget/dynamichelp.rb, line 37
  def self.cget(slot)
    self.current_configinfo(slot).values[0]
  end
delete(widget)

[Source]

# File tk/lib/tkextlib/bwidget/dynamichelp.rb, line 45
  def self.delete(widget)
    tk_call('DynamicHelp::delete', widget)
  end
include(klass, type)

[Source]

# File tk/lib/tkextlib/bwidget/dynamichelp.rb, line 49
  def self.include(klass, type)
    tk_call('DynamicHelp::include', klass, type)
  end
sethelp(path, subpath, force=None)

[Source]

# File tk/lib/tkextlib/bwidget/dynamichelp.rb, line 53
  def self.sethelp(path, subpath, force=None)
    tk_call('DynamicHelp::sethelp', path, subpath, force)
  end


Class: Tk::BWidget::Entry

Class | Tk::BWidget::Entry
In: | tk/lib/tkextlib/bwidget/entry.rb
Parent: | TkEntry

Methods

invoke

Included Modules

Scrollable

Constants

TkCommandNames | = | ['Entry'.freeze].freeze
WidgetClassName | = | 'Entry'.freeze

Public Instance methods

invoke()

[Source]

# File tk/lib/tkextlib/bwidget/entry.rb, line 39
  def invoke
    tk_send_without_enc('invoke')
    self
  end


Class: Tk::BWidget::Label

Class | Tk::BWidget::Label
In: | tk/lib/tkextlib/bwidget/label.rb
Parent: | TkLabel

Methods

set_focus

Constants

TkCommandNames | = | ['Label'.freeze].freeze
WidgetClassName | = | 'Label'.freeze

Public Instance methods

set_focus()

[Source]

# File tk/lib/tkextlib/bwidget/label.rb, line 37
  def set_focus
    tk_send_without_enc('setfocus')
    self
  end


Class: Tk::BWidget::LabelEntry

Class | Tk::BWidget::LabelEntry
In: | tk/lib/tkextlib/bwidget/labelentry.rb
Parent: | TkEntry

Methods

entrybind entrybind_append entrybind_remove entrybindinfo

Included Modules

Scrollable

Constants

TkCommandNames | = | ['LabelEntry'.freeze].freeze
WidgetClassName | = | 'LabelEntry'.freeze

Public Instance methods

entrybind(context, *args)

def entrybind(*args)

  _bind([path, 'bind'], *args)
  self

end

[Source]

# File tk/lib/tkextlib/bwidget/labelentry.rb, line 45
  def entrybind(context, *args)
    # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    _bind([path, 'bind'], context, cmd, *args)
    self
  end
entrybind_append(context, *args)

def entrybind_append(*args)

  _bind_append([path, 'bind'], *args)
  self

end

[Source]

# File tk/lib/tkextlib/bwidget/labelentry.rb, line 60
  def entrybind_append(context, *args)
    #if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    _bind_append([path, 'bind'], context, cmd, *args)
    self
  end
entrybind_remove(*args)

[Source]

# File tk/lib/tkextlib/bwidget/labelentry.rb, line 71
  def entrybind_remove(*args)
    _bind_remove([path, 'bind'], *args)
    self
  end
entrybindinfo(*args)

[Source]

# File tk/lib/tkextlib/bwidget/labelentry.rb, line 76
  def entrybindinfo(*args)
    _bindinfo([path, 'bind'], *args)
    self
  end


Class: Tk::BWidget::LabelFrame

Class | Tk::BWidget::LabelFrame
In: | tk/lib/tkextlib/bwidget/labelframe.rb
Parent: | TkWindow

Methods

align get_frame

Constants

TkCommandNames | = | ['LabelFrame'.freeze].freeze
WidgetClassName | = | 'LabelFrame'.freeze

Public Class methods

align(*args)

[Source]

# File tk/lib/tkextlib/bwidget/labelframe.rb, line 38
  def self.align(*args)
    tk_call('LabelFrame::align', *args)
  end

Public Instance methods

get_frame(&b)

[Source]

# File tk/lib/tkextlib/bwidget/labelframe.rb, line 41
  def get_frame(&b)
    win = window(tk_send_without_enc('getframe'))
    win.instance_eval(&b) if b
    win
  end


Class: Tk::BWidget::ListBox

Class | Tk::BWidget::ListBox
In: | tk/lib/tkextlib/bwidget/listbox.rb
Parent: | TkWindow

Methods

delete edit exist? get_item imagebind imagebind_append imagebind_remove imagebindinfo index insert items move reorder see selection_add selection_clear selection_get selection_remove selection_set tagid textbind textbind_append textbind_remove textbindinfo

Included Modules

TkItemConfigMethod Scrollable

Classes and Modules

Class Tk::BWidget::ListBox::Event_for_Items
Class Tk::BWidget::ListBox::Item

Constants

TkCommandNames | = | ['ListBox'.freeze].freeze
WidgetClassName | = | 'ListBox'.freeze

Public Instance methods

delete(*args)

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 134
  def delete(*args)
    tk_send('delete', *args)
    self
  end
edit(item, text, *args)

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 139
  def edit(item, text, *args)
    tk_send('edit', tagid(item), text, *args)
    self
  end
exist?(item)

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 144
  def exist?(item)
    bool(tk_send('exists', tagid(item)))
  end
get_item(idx)

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 157
  def get_item(idx)
    tk_send('items', idx)
  end
imagebind(context, *args)

def imagebind(*args)

  _bind_for_event_class(Event_for_Items, [path, 'bindImage'], *args)
  self

end

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 56
  def imagebind(context, *args)
    #if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    _bind_for_event_class(Event_for_Items, [path, 'bindImage'],
                          context, cmd, *args)
    self
  end
imagebind_append(context, *args)

def imagebind_append(*args)

  _bind_append_for_event_class(Event_for_Items, [path, 'bindImage'], *args)
  self

end

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 72
  def imagebind_append(context, *args)
    #if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    _bind_append_for_event_class(Event_for_Items, [path, 'bindImage'],
                                 context, cmd, *args)
    self
  end
imagebind_remove(*args)

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 84
  def imagebind_remove(*args)
    _bind_remove_for_event_class(Event_for_Items, [path, 'bindImage'], *args)
    self
  end
imagebindinfo(*args)

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 89
  def imagebindinfo(*args)
    _bindinfo_for_event_class(Event_for_Items, [path, 'bindImage'], *args)
  end
index(item)

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 148
  def index(item)
    num_or_str(tk_send('index', tagid(item)))
  end
insert(idx, item, keys={})

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 152
  def insert(idx, item, keys={})
    tk_send('insert', idx, tagid(item), *hash_kv(keys))
    self
  end
items(first=None, last=None)

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 161
  def items(first=None, last=None)
    list(tk_send('items', first, last))
  end
move(item, idx)

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 165
  def move(item, idx)
    tk_send('move', tagid(item), idx)
    self
  end
reorder(neworder)

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 170
  def reorder(neworder)
    tk_send('reorder', neworder)
    self
  end
see(item)

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 175
  def see(item)
    tk_send('see', tagid(item))
    self
  end
selection_add(*args)

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 191
  def selection_add(*args)
    tk_send_without_enc('selection', 'add',
                        *(args.collect{|item| tagid(item)}))
    self
  end
selection_clear()

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 180
  def selection_clear
    tk_send_without_enc('selection', 'clear')
    self
  end
selection_get(*args)

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 203
  def selection_get(*args)
    simplelist(tk_send_without_enc('selection', 'get')).collect{|item|
      Tk::BWidget::ListBox::Item.id2obj(self, item)
    }
  end
selection_remove(*args)

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 197
  def selection_remove(*args)
    tk_send_without_enc('selection', 'remove',
                        *(args.collect{|item| tagid(item)}))
    self
  end
selection_set(*args)

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 185
  def selection_set(*args)
    tk_send_without_enc('selection', 'set',
                        *(args.collect{|item| tagid(item)}))
    self
  end
tagid(tag)

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 43
  def tagid(tag)
    if tag.kind_of?(Tk::BWidget::ListBox::Item)
      tag.id
    else
      # tag
      _get_eval_string(tag)
    end
  end
textbind(context, *args)

def textbind(*args)

  _bind_for_event_class(Event_for_Items, [path, 'bindText'], *args)
  self

end

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 97
  def textbind(context, *args)
    #if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    _bind_for_event_class(Event_for_Items, [path, 'bindText'],
                          context, cmd, *args)
    self
  end
textbind_append(context, *args)

def textbind_append(*args)

  _bind_append_for_event_class(Event_for_Items, [path, 'bindText'], *args)
  self

end

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 113
  def textbind_append(context, *args)
    #if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    _bind_append_for_event_class(Event_for_Items, [path, 'bindText'],
                                 context, cmd, *args)
    self
  end
textbind_remove(*args)

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 125
  def textbind_remove(*args)
    _bind_remove_for_event_class(Event_for_Items, [path, 'bindText'], *args)
    self
  end
textbindinfo(*args)

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 130
  def textbindinfo(*args)
    _bindinfo_for_event_class(Event_for_Items, [path, 'bindText'], *args)
  end


Class: Tk::BWidget::ListBox::Event_for_Items

Class | Tk::BWidget::ListBox::Event_for_Items
In: | tk/lib/tkextlib/bwidget/listbox.rb
Parent: | TkEvent::Event

Methods

_get_extra_args_tbl

Public Class methods

_get_extra_args_tbl()

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 31
    def self._get_extra_args_tbl
      [
        TkComm.method(:string)   # item idenfier
      ]
    end


Class: Tk::BWidget::ListBox::Item

Class | Tk::BWidget::ListBox::Item
In: | tk/lib/tkextlib/bwidget/listbox.rb
Parent: | TkObject

is NOT a subclass of a listbox widget class. because it constructed on a canvas widget.

Methods

[] []= cget configinfo configure current_configinfo delete edit exist? id id2obj index listbox move new see selection_add selection_remove selection_set selection_toggle

Included Modules

TkTreatTagFont

Constants

ListItem_TBL | = | TkCore::INTERP.create_table
ListItem_ID | = | ['bw:item'.freeze, '00000'.taint].freeze

Public Class methods

id2obj(lbox, id)

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 218
  def self.id2obj(lbox, id)
    lpath = lbox.path
    return id unless ListItem_TBL[lpath]
    ListItem_TBL[lpath][id]? ListItem_TBL[lpath][id]: id
  end
new(lbox, *args)

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 224
  def initialize(lbox, *args)
    if lbox.kind_of?(Tk::BWidget::ListBox)
      @listbox = lbox
    else
      fail RuntimeError,
        "expect Tk::BWidget::ListBox or Tk::BWidget::ListBox::Item for 1st argument"
    end

    if args[-1].kind_of?(Hash)
      keys = _symbolkey2str(args.pop)
    else
      keys = {}
    end

    index = keys.delete('index')
    unless args.empty?
      index = args.shift
    end
    index = 'end' unless index

    unless args.empty?
      fail RuntimeError, 'too much arguments'
    end

    @lpath = @listbox.path

    if keys.key?('itemname')
      @path = @id = keys.delete('itemname')
    else
      @path = @id = ListItem_ID.join(TkCore::INTERP._ip_id_)
      ListItem_ID[1].succ!
    end

    ListItem_TBL[@id] = self
    ListItem_TBL[@lpath] = {} unless ListItem_TBL[@lpath]
    ListItem_TBL[@lpath][@id] = self

    @listbox.insert(index, @id, keys)
  end

Public Instance methods

[](key)

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 272
  def [](key)
    cget(key)
  end
[]=(key, val)

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 276
  def []=(key, val)
    configure(key, val)
    val
  end
cget(key)

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 281
  def cget(key)
    @listbox.itemcget(@id, key)
  end
configinfo(key=nil)

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 289
  def configinfo(key=nil)
    @listbox.itemconfiginfo(@id, key)
  end
configure(key, val=None)

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 285
  def configure(key, val=None)
    @listbox.itemconfigure(@id, key, val)
  end
current_configinfo(key=nil)

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 293
  def current_configinfo(key=nil)
    @listbox.current_itemconfiginfo(@id, key)
  end
delete()

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 297
  def delete
    @listbox.delete(@id)
    self
  end
edit(*args)

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 302
  def edit(*args)
    @listbox.edit(@id, *args)
    self
  end
exist?()

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 307
  def exist?
    @listbox.exist?(@id)
  end
id()

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 268
  def id
    @id
  end
index()

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 311
  def index
    @listbox.index(@id)
  end
listbox()

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 264
  def listbox
    @listbox
  end
move(index)

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 315
  def move(index)
    @listbox.move(@id, index)
  end
see()

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 319
  def see
    @listbox.see(@id)
  end
selection_add()

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 323
  def selection_add
    @listbox.selection_add(@id)
  end
selection_remove()

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 327
  def selection_remove
    @listbox.selection_remove(@id)
  end
selection_set()

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 331
  def selection_set
    @listbox.selection_set(@id)
  end
selection_toggle()

[Source]

# File tk/lib/tkextlib/bwidget/listbox.rb, line 335
  def selection_toggle
    @listbox.selection_toggle(@id)
  end


Class: Tk::BWidget::MainFrame

Class | Tk::BWidget::MainFrame
In: | tk/lib/tkextlib/bwidget/mainframe.rb
Parent: | TkWindow

Methods

add_indicator add_toolbar get_frame get_indicator get_menu get_toolbar set_menustate show_statusbar show_toolbar

Constants

TkCommandNames | = | ['MainFrame'.freeze].freeze
WidgetClassName | = | 'MainFrame'.freeze

Public Instance methods

add_indicator(keys={}, &b)

[Source]

# File tk/lib/tkextlib/bwidget/mainframe.rb, line 42
  def add_indicator(keys={}, &b)
    win = window(tk_send('addindicator', *hash_kv(keys)))
    win.instance_eval(&b) if b
    win
  end
add_toolbar(&b)

[Source]

# File tk/lib/tkextlib/bwidget/mainframe.rb, line 48
  def add_toolbar(&b)
    win = window(tk_send('addtoolbar'))
    win.instance_eval(&b) if b
    win
  end
get_frame(&b)

[Source]

# File tk/lib/tkextlib/bwidget/mainframe.rb, line 54
  def get_frame(&b)
    win = window(tk_send('getframe'))
    win.instance_eval(&b) if b
    win
  end
get_indicator(idx, &b)

[Source]

# File tk/lib/tkextlib/bwidget/mainframe.rb, line 60
  def get_indicator(idx, &b)
    win = window(tk_send('getindicator', idx))
    win.instance_eval(&b) if b
    win
  end
get_menu(menu_id, &b)

[Source]

# File tk/lib/tkextlib/bwidget/mainframe.rb, line 66
  def get_menu(menu_id, &b)
    win = window(tk_send('getmenu', menu_id))
    win.instance_eval(&b) if b
    win
  end
get_toolbar(idx, &b)

[Source]

# File tk/lib/tkextlib/bwidget/mainframe.rb, line 72
  def get_toolbar(idx, &b)
    win = window(tk_send('gettoolbar', idx))
    win.instance_eval(&b) if b
    win
  end
set_menustate(tag, state)

[Source]

# File tk/lib/tkextlib/bwidget/mainframe.rb, line 78
  def set_menustate(tag, state)
    tk_send('setmenustate', tag, state)
    self
  end
show_statusbar(name)

[Source]

# File tk/lib/tkextlib/bwidget/mainframe.rb, line 83
  def show_statusbar(name)
    tk_send('showstatusbar', name)
    self
  end
show_toolbar(idx, mode)

[Source]

# File tk/lib/tkextlib/bwidget/mainframe.rb, line 88
  def show_toolbar(idx, mode)
    tk_send('showtoolbar', idx, mode)
    self
  end


Class: Tk::BWidget::MessageDlg

Class | Tk::BWidget::MessageDlg
In: | tk/lib/tkextlib/bwidget/messagedlg.rb
Parent: | TkWindow

Methods

cget configinfo configure create new

Constants

TkCommandNames | = | ['MessageDlg'.freeze].freeze
WidgetClassName | = | 'MessageDlg'.freeze

Public Class methods

new(parent=nil, keys=nil)

[Source]

# File tk/lib/tkextlib/bwidget/messagedlg.rb, line 22
  def initialize(parent=nil, keys=nil)
    @relative = ''
    if parent.kind_of?(Hash)
      keys = _symbolkey2str(parent)
      @relative = keys['parent'] if keys.key?('parent')
      @relative = keys.delete('relative') if keys.key?('relative')
      super(keys)
    elsif keys
      keys = _symbolkey2str(keys)
      @relative = keys.delete('parent') if keys.key?('parent')
      @relative = keys.delete('relative') if keys.key?('relative')
      super(parent, keys)
    else
      super(parent)
    end
  end

Public Instance methods

cget(slot)

[Source]

# File tk/lib/tkextlib/bwidget/messagedlg.rb, line 57
  def cget(slot)
    slot = slot.to_s
    if slot == 'relative'
      slot = 'parent'
    end
    if winfo_exist?
      val = super(slot)
      @keys[slot] = val
    end
    @keys[slot]
  end
configinfo(slot=nil)

[Source]

# File tk/lib/tkextlib/bwidget/messagedlg.rb, line 123
  def configinfo(slot=nil)
    if winfo_exist?
      @info = super()
      if TkComm::GET_CONFIGINFO_AS_ARRAY
        @info << ['relative', 'parent']
      else
        @info['relative'] = 'parent'
      end
    end

    if TkComm::GET_CONFIGINFO_AS_ARRAY
      if @info
        if winfo_exist?
          # update @keys
          @info.each{|inf| @keys[inf[0]] = inf[-1] if inf.size > 2 }
        end
      else
        @info = []
        @keys.each{|k, v|
          @info << [k, '', '', '', v]
        }
        @info << ['relative', 'parent']
      end

      if slot
        @info.asoc(slot.to_s).dup
      else
        @info.dup
      end

    else # ! TkComm::GET_CONFIGINFO_AS_ARRAY
      if @info
        if winfo_exist?
          # update @keys
          @info.each{|k, inf| @keys[k] = inf[-1] if inf.size > 2 }
        end
      else
        @info = {}
        @keys.each{|k, v|
          @info[k] = ['', '', '', v]
        }
        @info['relative'] = 'parent'
      end

      if slot
        @info[slot.to_s].dup
      else
        @info.dup
      end
    end
  end
configure(slot, value=None)

[Source]

# File tk/lib/tkextlib/bwidget/messagedlg.rb, line 69
  def configure(slot, value=None)
    if winfo_exist?
      super(slot, value)
    end
    if slot.kind_of?(Hash)
      slot = _symbolkey2str(slot)
      slot['parent'] = slot.delete('relative') if slot.key?('relative')
      @keys.update(slot)

      if @info
        # update @info
        slot.each{|k, v|
          if TkComm::GET_CONFIGINFO_AS_ARRAY
            if (inf = @info.assoc(k))
              inf[-1] = v
            else
              @info << [k, '', '', '', v]
            end
          else
            if (inf = @info[k])
              inf[-1] = v
            else
              @info[k] = ['', '', '', v]
            end
          end
        }
      end

    else # ! Hash
      slot = slot.to_s
      slot = 'parent' if slot == 'relative'
      @keys[slot] = value

      if @info
        # update @info
        if TkComm::GET_CONFIGINFO_AS_ARRAY
          if (inf = @info.assoc(slot))
            inf[-1] = value
          else
            @info << [slot, '', '', '', value]
          end
        else
          if (inf = @info[slot])
            inf[-1] = value
          else
            @info[slot] = ['', '', '', value]
          end
        end
      end
    end

    self
  end
create()

[Source]

# File tk/lib/tkextlib/bwidget/messagedlg.rb, line 175
  def create
    num_or_str(tk_call(self.class::TkCommandNames[0], @path, *hash_kv(@keys)))
  end


Class: Tk::BWidget::NoteBook

Class | Tk::BWidget::NoteBook
In: | tk/lib/tkextlib/bwidget/notebook.rb
Parent: | TkWindow

Methods

add compute_size delete get_frame get_page index insert move pages raise see tabbind tabbind_append tabbind_remove tabbindinfo tagid

Included Modules

TkItemConfigMethod

Classes and Modules

Class Tk::BWidget::NoteBook::Event_for_Tabs

Constants

TkCommandNames | = | ['NoteBook'.freeze].freeze
WidgetClassName | = | 'NoteBook'.freeze

Public Instance methods

add(page, &b)

[Source]

# File tk/lib/tkextlib/bwidget/notebook.rb, line 90
  def add(page, &b)
    win = window(tk_send('add', tagid(page)))
    win.instance_eval(&b) if b
    win
  end
compute_size()

[Source]

# File tk/lib/tkextlib/bwidget/notebook.rb, line 96
  def compute_size
    tk_send('compute_size')
    self
  end
delete(page, destroyframe=None)

[Source]

# File tk/lib/tkextlib/bwidget/notebook.rb, line 101
  def delete(page, destroyframe=None)
    tk_send('delete', tagid(page), destroyframe)
    self
  end
get_frame(page, &b)

[Source]

# File tk/lib/tkextlib/bwidget/notebook.rb, line 106
  def get_frame(page, &b)
    win = window(tk_send('getframe', tagid(page)))
    win.instance_eval(&b) if b
    win
  end
get_page(page)

[Source]

# File tk/lib/tkextlib/bwidget/notebook.rb, line 127
  def get_page(page)
    tk_send('pages', page)
  end
index(page)

[Source]

# File tk/lib/tkextlib/bwidget/notebook.rb, line 112
  def index(page)
    num_or_str(tk_send('index', tagid(page)))
  end
insert(index, page, keys={}, &b)

[Source]

# File tk/lib/tkextlib/bwidget/notebook.rb, line 116
  def insert(index, page, keys={}, &b)
    win = window(tk_send('insert', index, tagid(page), *hash_kv(keys)))
    win.instance_eval(&b) if b
    win
  end
move(page, index)

[Source]

# File tk/lib/tkextlib/bwidget/notebook.rb, line 122
  def move(page, index)
    tk_send('move', tagid(page), index)
    self
  end
pages(first=None, last=None)

[Source]

# File tk/lib/tkextlib/bwidget/notebook.rb, line 131
  def pages(first=None, last=None)
    list(tk_send('pages', first, last))
  end
raise(page=nil)

[Source]

# File tk/lib/tkextlib/bwidget/notebook.rb, line 135
  def raise(page=nil)
    if page
      tk_send('raise', page)
      self
    else
      tk_send('raise')
    end
  end
see(page)

[Source]

# File tk/lib/tkextlib/bwidget/notebook.rb, line 144
  def see(page)
    tk_send('see', page)
    self
  end
tabbind(context, *args)

def tabbind(*args)

  _bind_for_event_class(Event_for_Tabs, [path, 'bindtabs'], *args)
  self

end

[Source]

# File tk/lib/tkextlib/bwidget/notebook.rb, line 53
  def tabbind(context, *args)
    #if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    _bind_for_event_class(Event_for_Tabs, [path, 'bindtabs'],
                          context, cmd, *args)
    self
  end
tabbind_append(context, *args)

def tabbind_append(*args)

  _bind_append_for_event_class(Event_for_Tabs, [path, 'bindtabs'], *args)
  self

end

[Source]

# File tk/lib/tkextlib/bwidget/notebook.rb, line 69
  def tabbind_append(context, *args)
    #if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    _bind_append_for_event_class(Event_for_Tabs, [path, 'bindtabs'],
                                 context, cmd, *args)
    self
  end
tabbind_remove(*args)

[Source]

# File tk/lib/tkextlib/bwidget/notebook.rb, line 81
  def tabbind_remove(*args)
    _bind_remove_for_event_class(Event_for_Tabs, [path, 'bindtabs'], *args)
    self
  end
tabbindinfo(*args)

[Source]

# File tk/lib/tkextlib/bwidget/notebook.rb, line 86
  def tabbindinfo(*args)
    _bindinfo_for_event_class(Event_for_Tabs, [path, 'bindtabs'], *args)
  end
tagid(id)

[Source]

# File tk/lib/tkextlib/bwidget/notebook.rb, line 37
  def tagid(id)
    if id.kind_of?(TkWindow)
      #id.path
      id.epath
    elsif id.kind_of?(TkObject)
      id.to_eval
    else
      # id.to_s
      _get_eval_string(id)
    end
  end


Class: Tk::BWidget::NoteBook::Event_for_Tabs

Class | Tk::BWidget::NoteBook::Event_for_Tabs
In: | tk/lib/tkextlib/bwidget/notebook.rb
Parent: | TkEvent::Event

Methods

_get_extra_args_tbl

Public Class methods

_get_extra_args_tbl()

[Source]

# File tk/lib/tkextlib/bwidget/notebook.rb, line 25
    def self._get_extra_args_tbl
      [
        TkComm.method(:string)   # page idenfier
      ]
    end


Class: Tk::BWidget::PagesManager

Class | Tk::BWidget::PagesManager
In: | tk/lib/tkextlib/bwidget/pagesmanager.rb
Parent: | TkWindow

Methods

add compute_size delete get_frame get_page pages raise tagid

Constants

TkCommandNames | = | ['PagesManager'.freeze].freeze
WidgetClassName | = | 'PagesManager'.freeze

Public Instance methods

add(page, &b)

[Source]

# File tk/lib/tkextlib/bwidget/pagesmanager.rb, line 27
  def add(page, &b)
    win = window(tk_send('add', tagid(page)))
    win.instance_eval(&b) if b
    win
  end
compute_size()

[Source]

# File tk/lib/tkextlib/bwidget/pagesmanager.rb, line 33
  def compute_size
    tk_send('compute_size')
    self
  end
delete(page)

[Source]

# File tk/lib/tkextlib/bwidget/pagesmanager.rb, line 38
  def delete(page)
    tk_send('delete', tagid(page))
    self
  end
get_frame(page, &b)

[Source]

# File tk/lib/tkextlib/bwidget/pagesmanager.rb, line 43
  def get_frame(page, &b)
    win = window(tk_send('getframe', tagid(page)))
    win.instance_eval(&b) if b
    win
  end
get_page(page)

[Source]

# File tk/lib/tkextlib/bwidget/pagesmanager.rb, line 49
  def get_page(page)
    tk_send('pages', page)
  end
pages(first=None, last=None)

[Source]

# File tk/lib/tkextlib/bwidget/pagesmanager.rb, line 53
  def pages(first=None, last=None)
    list(tk_send('pages', first, last))
  end
raise(page=None)

[Source]

# File tk/lib/tkextlib/bwidget/pagesmanager.rb, line 57
  def raise(page=None)
    tk_send('raise', page)
    self
  end
tagid(id)

[Source]

# File tk/lib/tkextlib/bwidget/pagesmanager.rb, line 22
  def tagid(id)
    # id.to_s
    _get_eval_string(id)
  end


Class: Tk::BWidget::PanedWindow

Class | Tk::BWidget::PanedWindow
In: | tk/lib/tkextlib/bwidget/panedwindow.rb
Parent: | TkWindow

Methods

add get_frame

Constants

TkCommandNames | = | ['PanedWindow'.freeze].freeze
WidgetClassName | = | 'PanedWindow'.freeze

Public Instance methods

add(keys={})

[Source]

# File tk/lib/tkextlib/bwidget/panedwindow.rb, line 22
  def add(keys={})
    window(tk_send('add', *hash_kv(keys)))
  end
get_frame(idx, &b)

[Source]

# File tk/lib/tkextlib/bwidget/panedwindow.rb, line 26
  def get_frame(idx, &b)
    win = window(tk_send_without_enc('getframe', idx))
    win.instance_eval(&b) if b
    win
  end


Class: Tk::BWidget::PanelFrame

Class | Tk::BWidget::PanelFrame
In: | tk/lib/tkextlib/bwidget/panelframe.rb
Parent: | TkWindow

Methods

add delete get_frame items remove

Constants

TkCommandNames | = | ['PanelFrame'.freeze].freeze
WidgetClassName | = | 'PanelFrame'.freeze

Public Instance methods

add(win, keys={})

[Source]

# File tk/lib/tkextlib/bwidget/panelframe.rb, line 27
  def add(win, keys={})
    tk_send('add', win, keys)
    self
  end
delete(*wins)

[Source]

# File tk/lib/tkextlib/bwidget/panelframe.rb, line 32
  def delete(*wins)
    tk_send('delete', *wins)
    self
  end
get_frame(&b)

[Source]

# File tk/lib/tkextlib/bwidget/panelframe.rb, line 37
  def get_frame(&b)
    win = window(tk_send_without_enc('getframe'))
    win.instance_eval(&b) if b
    win
  end
items()

[Source]

# File tk/lib/tkextlib/bwidget/panelframe.rb, line 43
  def items
    list(tk_send('items'))
  end
remove(*wins)

[Source]

# File tk/lib/tkextlib/bwidget/panelframe.rb, line 47
  def remove(*wins)
    tk_send('remove', *wins)
    self
  end


Class: Tk::BWidget::PasswdDlg

Class | Tk::BWidget::PasswdDlg
In: | tk/lib/tkextlib/bwidget/passwddlg.rb
Parent: | Tk::BWidget::MessageDlg

Methods

create

Constants

TkCommandNames | = | ['PasswdDlg'.freeze].freeze
WidgetClassName | = | 'PasswdDlg'.freeze

Public Instance methods

create()

[Source]

# File tk/lib/tkextlib/bwidget/passwddlg.rb, line 39
  def create
    login, passwd = simplelist(tk_call(self.class::TkCommandNames[0],
                                       @path, *hash_kv(@keys)))
    [login, passwd]
  end


Class: Tk::BWidget::ProgressBar

Class | Tk::BWidget::ProgressBar
In: | tk/lib/tkextlib/bwidget/progressbar.rb
Parent: | TkWindow

Constants

TkCommandNames | = | ['ProgressBar'.freeze].freeze
WidgetClassName | = | 'ProgressBar'.freeze


Class: Tk::BWidget::ProgressDlg

Class | Tk::BWidget::ProgressDlg
In: | tk/lib/tkextlib/bwidget/progressdlg.rb
Parent: | Tk::BWidget::MessageDlg

Methods

create_self text text= textvariable value value= variable

Constants

TkCommandNames | = | ['ProgressDlg'.freeze].freeze
WidgetClassName | = | 'ProgressDlg'.freeze

Public Instance methods

create_self(keys)

[Source]

# File tk/lib/tkextlib/bwidget/progressdlg.rb, line 24
  def create_self(keys)
    # NOT create widget for reusing the object
    super(keys)
    @keys['textvariable'] = TkVariable.new unless @keys.key?('textvariable')
    @keys['variable']     = TkVariable.new unless @keys.key?('variable')
  end
text()

[Source]

# File tk/lib/tkextlib/bwidget/progressdlg.rb, line 35
  def text
    @keys['textvariable'].value
  end
text=(txt)

[Source]

# File tk/lib/tkextlib/bwidget/progressdlg.rb, line 39
  def text= (txt)
    @keys['textvariable'].value = txt
  end
textvariable()

[Source]

# File tk/lib/tkextlib/bwidget/progressdlg.rb, line 31
  def textvariable
    @keys['textvariable']
  end
value()

[Source]

# File tk/lib/tkextlib/bwidget/progressdlg.rb, line 47
  def value
    @keys['variable'].value
  end
value=(val)

[Source]

# File tk/lib/tkextlib/bwidget/progressdlg.rb, line 51
  def value= (val)
    @keys['variable'].value = val
  end
variable()

[Source]

# File tk/lib/tkextlib/bwidget/progressdlg.rb, line 43
  def variable
    @keys['variable']
  end


Class: Tk::BWidget::ScrollView

Class | Tk::BWidget::ScrollView
In: | tk/lib/tkextlib/bwidget/scrollview.rb
Parent: | TkWindow

Constants

TkCommandNames | = | ['ScrollView'.freeze].freeze
WidgetClassName | = | 'ScrollView'.freeze


Class: Tk::BWidget::ScrollableFrame

Class | Tk::BWidget::ScrollableFrame
In: | tk/lib/tkextlib/bwidget/scrollableframe.rb
Parent: | TkWindow

Methods

get_frame see

Included Modules

Scrollable

Constants

TkCommandNames | = | ['ScrollableFrame'.freeze].freeze
WidgetClassName | = | 'ScrollableFrame'.freeze

Public Instance methods

get_frame(&b)

[Source]

# File tk/lib/tkextlib/bwidget/scrollableframe.rb, line 24
  def get_frame(&b)
    win = window(tk_send_without_enc('getframe'))
    win.instance_eval(&b) if b
    win
  end
see(win, vert=None, horiz=None)

[Source]

# File tk/lib/tkextlib/bwidget/scrollableframe.rb, line 30
  def see(win, vert=None, horiz=None)
    tk_send_without_enc('see', win, vert, horiz)
    self
  end


Class: Tk::BWidget::ScrolledWindow

Class | Tk::BWidget::ScrolledWindow
In: | tk/lib/tkextlib/bwidget/scrolledwindow.rb
Parent: | TkWindow

Methods

get_frame set_widget

Constants

TkCommandNames | = | ['ScrolledWindow'.freeze].freeze
WidgetClassName | = | 'ScrolledWindow'.freeze

Public Instance methods

get_frame(&b)

[Source]

# File tk/lib/tkextlib/bwidget/scrolledwindow.rb, line 22
  def get_frame(&b)
    win = window(tk_send_without_enc('getframe'))
    win.instance_eval(&b) if b
    win
  end
set_widget(win)

[Source]

# File tk/lib/tkextlib/bwidget/scrolledwindow.rb, line 28
  def set_widget(win)
    tk_send_without_enc('setwidget', win)
    self
  end


Class: Tk::BWidget::SelectColor

Class | Tk::BWidget::SelectColor
In: | tk/lib/tkextlib/bwidget/selectcolor.rb
Parent: | Tk::BWidget::MessageDlg

Methods

dialog menu set_color

Constants

TkCommandNames | = | ['SelectColor'.freeze].freeze
WidgetClassName | = | 'SelectColor'.freeze

Public Class methods

set_color(idx, color)

[Source]

# File tk/lib/tkextlib/bwidget/selectcolor.rb, line 42
  def self.set_color(idx, color)
    tk_call('SelectColor::setcolor', idx, color)
  end

Public Instance methods

dialog(keys={})

[Source]

# File tk/lib/tkextlib/bwidget/selectcolor.rb, line 24
  def dialog(keys={})
    newkeys = @keys.dup
    newkeys.update(_symbolkey2str(keys))
    tk_call('SelectColor::dialog', @path, *hash_kv(newkeys))
  end
menu(*args)

[Source]

# File tk/lib/tkextlib/bwidget/selectcolor.rb, line 30
  def menu(*args)
    if args[-1].kind_of?(Hash)
      keys = args.pop
    else
      keys = {}
    end
    place = args.flatten
    newkeys = @keys.dup
    newkeys.update(_symbolkey2str(keys))
    tk_call('SelectColor::menu', @path, place, *hash_kv(newkeys))
  end


Class: Tk::BWidget::SelectFont

Class | Tk::BWidget::SelectFont
In: | tk/lib/tkextlib/bwidget/selectfont.rb
Parent: | Tk::BWidget::MessageDlg

Methods

create load_font

Classes and Modules

Class Tk::BWidget::SelectFont::Dialog
Class Tk::BWidget::SelectFont::Toolbar

Constants

TkCommandNames | = | ['SelectFont'.freeze].freeze
WidgetClassName | = | 'SelectFont'.freeze

Public Class methods

load_font()

[Source]

# File tk/lib/tkextlib/bwidget/selectfont.rb, line 42
  def self.load_font
    tk_call('SelectFont::loadfont')
  end

Public Instance methods

create()

[Source]

# File tk/lib/tkextlib/bwidget/selectfont.rb, line 38
  def create
    tk_call(self.class::TkCommandNames[0], @path, *hash_kv(@keys))
  end


Class: Tk::BWidget::SelectFont::Dialog

Class | Tk::BWidget::SelectFont::Dialog
In: | tk/lib/tkextlib/bwidget/selectfont.rb
Parent: | Tk::BWidget::SelectFont

Methods

__font_optkeys configure create create_self

Public Instance methods

__font_optkeys()

[Source]

# File tk/lib/tkextlib/bwidget/selectfont.rb, line 48
  def __font_optkeys
    [] # without fontobj operation
  end
configure(slot, value=None)

[Source]

# File tk/lib/tkextlib/bwidget/selectfont.rb, line 57
  def configure(slot, value=None)
    if slot.kind_of?(Hash)
      slot.delete['type']
      slot.delete[:type]
      return self if slot.empty?
    else
      return self if slot == 'type' || slot == :type
    end
    super(slot, value)
  end
create()

[Source]

# File tk/lib/tkextlib/bwidget/selectfont.rb, line 68
  def create
    @keys['type'] = 'dialog'
    tk_call(Tk::BWidget::SelectFont::TkCommandNames[0], @path, *hash_kv(@keys))
  end
create_self(keys)

[Source]

# File tk/lib/tkextlib/bwidget/selectfont.rb, line 52
  def create_self(keys)
    super(keys)
    @keys['type'] = 'dialog'
  end


Class: Tk::BWidget::SelectFont::Toolbar

Class | Tk::BWidget::SelectFont::Toolbar
In: | tk/lib/tkextlib/bwidget/selectfont.rb
Parent: | TkWindow

Methods

__font_optkeys create_self

Public Instance methods

__font_optkeys()

[Source]

# File tk/lib/tkextlib/bwidget/selectfont.rb, line 75
  def __font_optkeys
    [] # without fontobj operation
  end
create_self(keys)

[Source]

# File tk/lib/tkextlib/bwidget/selectfont.rb, line 79
  def create_self(keys)
    keys = {} unless keys
    keys = _symbolkey2str(keys)
    keys['type'] = 'toolbar'
    tk_call(Tk::BWidget::SelectFont::TkCommandNames[0], @path, *hash_kv(keys))
  end


Class: Tk::BWidget::Separator

Class | Tk::BWidget::Separator
In: | tk/lib/tkextlib/bwidget/separator.rb
Parent: | TkWindow

Constants

TkCommandNames | = | ['Separator'.freeze].freeze
WidgetClassName | = | 'Separator'.freeze


Class: Tk::BWidget::SpinBox

Class | Tk::BWidget::SpinBox
In: | tk/lib/tkextlib/bwidget/spinbox.rb
Parent: | TkEntry

Methods

entrybind entrybind_append entrybind_remove entrybindinfo get_index_of_value get_value get_value_index set_index_value set_value set_value_by_index

Included Modules

Scrollable

Constants

TkCommandNames | = | ['SpinBox'.freeze].freeze
WidgetClassName | = | 'SpinBox'.freeze

Public Instance methods

entrybind(context, *args)

def entrybind(*args)

  _bind([path, 'bind'], *args)
  self

end

[Source]

# File tk/lib/tkextlib/bwidget/spinbox.rb, line 49
  def entrybind(context, *args)
    #if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    _bind([path, 'bind'], context, cmd, *args)
    self
  end
entrybind_append(context, *args)

def entrybind_append(*args)

  _bind_append([path, 'bind'], *args)
  self

end

[Source]

# File tk/lib/tkextlib/bwidget/spinbox.rb, line 64
  def entrybind_append(context, *args)
    #if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    _bind_append([path, 'bind'], context, cmd, *args)
    self
  end
entrybind_remove(*args)

[Source]

# File tk/lib/tkextlib/bwidget/spinbox.rb, line 75
  def entrybind_remove(*args)
    _bind_remove([path, 'bind'], *args)
    self
  end
entrybindinfo(*args)

[Source]

# File tk/lib/tkextlib/bwidget/spinbox.rb, line 80
  def entrybindinfo(*args)
    _bindinfo([path, 'bind'], *args)
    self
  end
get_index_of_value()

[Source]

# File tk/lib/tkextlib/bwidget/spinbox.rb, line 85
  def get_index_of_value
    number(tk_send_without_enc('getvalue'))
  end
get_value()

Alias for get_index_of_value

get_value_index()

Alias for get_index_of_value

set_index_value(idx)

Alias for set_value_by_index

set_value(idx)

Alias for set_value_by_index

set_value_by_index(idx)

[Source]

# File tk/lib/tkextlib/bwidget/spinbox.rb, line 91
  def set_value_by_index(idx)
    idx = "@#{idx}" if idx.kind_of?(Integer)
    tk_send_without_enc('setvalue', idx)
    self
  end


Class: Tk::BWidget::StatusBar

Class | Tk::BWidget::StatusBar
In: | tk/lib/tkextlib/bwidget/statusbar.rb
Parent: | TkWindow

Methods

add delete get_frame items

Constants

TkCommandNames | = | ['StatusBar'.freeze].freeze
WidgetClassName | = | 'StatusBar'.freeze

Public Instance methods

add(win, keys={})

[Source]

# File tk/lib/tkextlib/bwidget/statusbar.rb, line 27
  def add(win, keys={})
    tk_send('add', win, keys)
    self
  end
delete(*wins)

[Source]

# File tk/lib/tkextlib/bwidget/statusbar.rb, line 32
  def delete(*wins)
    tk_send('delete', *wins)
    self
  end
get_frame(&b)

[Source]

# File tk/lib/tkextlib/bwidget/statusbar.rb, line 37
  def get_frame(&b)
    win = window(tk_send_without_enc('getframe'))
    win.instance_eval(&b) if b
    win
  end
items()

[Source]

# File tk/lib/tkextlib/bwidget/statusbar.rb, line 43
  def items
    list(tk_send('items'))
  end


Class: Tk::BWidget::TitleFrame

Class | Tk::BWidget::TitleFrame
In: | tk/lib/tkextlib/bwidget/titleframe.rb
Parent: | TkWindow

Methods

get_frame

Constants

TkCommandNames | = | ['TitleFrame'.freeze].freeze
WidgetClassName | = | 'TitleFrame'.freeze

Public Instance methods

get_frame(&b)

[Source]

# File tk/lib/tkextlib/bwidget/titleframe.rb, line 22
  def get_frame(&b)
    win = window(tk_send_without_enc('getframe'))
    win.instance_eval(&b) if b
    win
  end


Class: Tk::BWidget::Tree

Class | Tk::BWidget::Tree
In: | tk/lib/tkextlib/bwidget/tree.rb
Parent: | TkWindow

Methods

close_tree delete edit exist? get_node imagebind imagebind_append imagebind_remove imagebindinfo index insert move nodes open? open_tree parent reorder see selection_add selection_clear selection_get selection_include? selection_range selection_remove selection_set selection_toggle tagid textbind textbind_append textbind_remove textbindinfo toggle visible

Included Modules

TkItemConfigMethod Scrollable

Classes and Modules

Class Tk::BWidget::Tree::Event_for_Items
Class Tk::BWidget::Tree::Node

Constants

TkCommandNames | = | ['Tree'.freeze].freeze
WidgetClassName | = | 'Tree'.freeze

Public Instance methods

close_tree(node, recurse=None)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 142
  def close_tree(node, recurse=None)
    tk_send('closetree', tagid(node), recurse)
    self
  end
delete(*args)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 147
  def delete(*args)
    tk_send('delete', *(args.collect{|node| tagid(node)}))
    self
  end
edit(node, text, *args)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 152
  def edit(node, text, *args)
    tk_send('edit', tagid(node), text, *args)
    self
  end
exist?(node)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 157
  def exist?(node)
    bool(tk_send('exists', tagid(node)))
  end
get_node(node, idx)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 175
  def get_node(node, idx)
    Tk::BWidget::Tree::Node.id2obj(self, tk_send('nodes', tagid(node), idx))
  end
imagebind(context, *args)

def imagebind(*args)

  _bind_for_event_class(Event_for_Items, [path, 'bindImage'], *args)
  self

end

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 64
  def imagebind(context, *args)
    #if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    _bind_for_event_class(Event_for_Items, [path, 'bindImage'],
                          context, cmd, *args)
    self
  end
imagebind_append(context, *args)

def imagebind_append(*args)

  _bind_append_for_event_class(Event_for_Items, [path, 'bindImage'], *args)
  self

end

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 80
  def imagebind_append(context, *args)
    #if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    _bind_append_for_event_class(Event_for_Items, [path, 'bindImage'],
                                 context, cmd, *args)
    self
  end
imagebind_remove(*args)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 92
  def imagebind_remove(*args)
    _bind_remove_for_event_class(Event_for_Items, [path, 'bindImage'], *args)
    self
  end
imagebindinfo(*args)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 97
  def imagebindinfo(*args)
    _bindinfo_for_event_class(Event_for_Items, [path, 'bindImage'], *args)
  end
index(node)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 161
  def index(node)
    num_or_str(tk_send('index', tagid(node)))
  end
insert(idx, parent, node, keys={})

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 165
  def insert(idx, parent, node, keys={})
    tk_send('insert', idx, tagid(parent), tagid(node), *hash_kv(keys))
    self
  end
move(parent, node, idx)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 170
  def move(parent, node, idx)
    tk_send('move', tagid(parent), tagid(node), idx)
    self
  end
nodes(node, first=None, last=None)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 179
  def nodes(node, first=None, last=None)
    simplelist(tk_send('nodes', tagid(node), first, last)).collect{|node|
      Tk::BWidget::Tree::Node.id2obj(self, node)
    }
  end
open?(node)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 185
  def open?(node)
    bool(@tree.itemcget(tagid(node), 'open'))
  end
open_tree(node, recurse=None)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 189
  def open_tree(node, recurse=None)
    tk_send('opentree', tagid(node), recurse)
    self
  end
parent(node)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 194
  def parent(node)
    Tk::BWidget::Tree::Node.id2obj(self, tk_send('parent', tagid(node)))
  end
reorder(node, neworder)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 198
  def reorder(node, neworder)
    tk_send('reorder', tagid(node), neworder)
    self
  end
see(node)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 203
  def see(node)
    tk_send('see', tagid(node))
    self
  end
selection_add(*args)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 208
  def selection_add(*args)
    tk_send_without_enc('selection', 'add',
                        *(args.collect{|node| tagid(node)}))
    self
  end
selection_clear()

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 214
  def selection_clear
    tk_send_without_enc('selection', 'clear')
    self
  end
selection_get()

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 219
  def selection_get
    list(tk_send_without_enc('selection', 'get'))
  end
selection_include?(*args)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 223
  def selection_include?(*args)
    bool(tk_send_without_enc('selection', 'get',
                             *(args.collect{|node| tagid(node)})))
  end
selection_range(*args)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 228
  def selection_range(*args)
    tk_send_without_enc('selection', 'range',
                        *(args.collect{|node| tagid(node)}))
    self
  end
selection_remove(*args)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 234
  def selection_remove(*args)
    tk_send_without_enc('selection', 'remove',
                        *(args.collect{|node| tagid(node)}))
    self
  end
selection_set(*args)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 240
  def selection_set(*args)
    tk_send_without_enc('selection', 'set',
                        *(args.collect{|node| tagid(node)}))
    self
  end
selection_toggle(*args)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 246
  def selection_toggle(*args)
    tk_send_without_enc('selection', 'toggle',
                        *(args.collect{|node| tagid(node)}))
    self
  end
tagid(tag)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 51
  def tagid(tag)
    if tag.kind_of?(Tk::BWidget::Tree::Node)
      tag.id
    else
      # tag
      _get_eval_string(tag)
    end
  end
textbind(context, *args)

def textbind(*args)

  _bind_for_event_class(Event_for_Items, [path, 'bindText'], *args)
  self

end

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 105
  def textbind(context, *args)
    #if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    _bind_for_event_class(Event_for_Items, [path, 'bindText'],
                          context, cmd, *args)
    self
  end
textbind_append(context, *args)

def textbind_append(*args)

  _bind_append_for_event_class(Event_for_Items, [path, 'bindText'], *args)
  self

end

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 121
  def textbind_append(context, *args)
    #if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    _bind_append_for_event_class(Event_for_Items, [path, 'bindText'],
                                 context, cmd, *args)
    self
  end
textbind_remove(*args)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 133
  def textbind_remove(*args)
    _bind_remove_for_event_class(Event_for_Items, [path, 'bindText'], *args)
    self
  end
textbindinfo(*args)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 138
  def textbindinfo(*args)
    _bindinfo_for_event_class(Event_for_Items, [path, 'bindText'], *args)
  end
toggle(node)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 252
  def toggle(node)
    tk_send_without_enc('toggle', tagid(node))
    self
  end
visible(node)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 257
  def visible(node)
    bool(tk_send_without_enc('visible', tagid(node)))
  end


Class: Tk::BWidget::Tree::Event_for_Items

Class | Tk::BWidget::Tree::Event_for_Items
In: | tk/lib/tkextlib/bwidget/tree.rb
Parent: | TkEvent::Event

Methods

_get_extra_args_tbl

Public Class methods

_get_extra_args_tbl()

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 28
    def self._get_extra_args_tbl
      [
        TkComm.method(:string)   # item idenfier
      ]
    end


Class: Tk::BWidget::Tree::Node

Class | Tk::BWidget::Tree::Node
In: | tk/lib/tkextlib/bwidget/tree.rb
Parent: | TkObject

Methods

[] []= cget close_tree configinfo configure current_configinfo delete edit exist? id id2obj index move new open? open_tree parent reorder see selection_add selection_remove selection_set selection_toggle toggle tree visible

Included Modules

TkTreatTagFont

Constants

TreeNode_TBL | = | TkCore::INTERP.create_table
TreeNode_ID | = | ['bw:node'.freeze, '00000'.taint].freeze

Public Class methods

id2obj(tree, id)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 270
  def self.id2obj(tree, id)
    tpath = tree.path
    return id unless TreeNode_TBL[tpath]
    TreeNode_TBL[tpath][id]? TreeNode_TBL[tpath][id]: id
  end
new(tree, *args)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 276
  def initialize(tree, *args)
    if tree.kind_of?(Tk::BWidget::Tree)
      @tree = tree
      parent = args.shift
      if parent.kind_of?(Tk::BWidget::Tree::Node)
        if parent.tree.path != @tree.path
          fail RuntimeError, 'tree of parent node is not match'
        end
      end
    elsif tree.kind_of?(Tk::BWidget::Tree::Node)
      @tree = tree.tree
      parent = tree.parent
    else
      fail RuntimeError,
        "expect Tk::BWidget::Tree or Tk::BWidget::Tree::Node for 1st argument"
    end

    if args[-1].kind_of?(Hash)
      keys = _symbolkey2str(args.pop)
    else
      keys = {}
    end

    index = keys.delete('index')
    unless args.empty?
      index = args.shift
    end
    index = 'end' unless index

    unless args.empty?
      fail RuntimeError, 'too much arguments'
    end

    @tpath = @tree.path

    if keys.key?('nodename')
      @path = @id = keys.delete('nodename')
    else
      @path = @id = TreeNode_ID.join(TkCore::INTERP._ip_id_)
      TreeNode_ID[1].succ!
    end

    TreeNode_TBL[@id] = self
    TreeNode_TBL[@tpath] = {} unless TreeNode_TBL[@tpath]
    TreeNode_TBL[@tpath][@id] = self

    @tree.insert(index, parent, @id, keys)
  end

Public Instance methods

[](key)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 333
  def [](key)
    cget(key)
  end
[]=(key, val)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 337
  def []=(key, val)
    configure(key, val)
    val
  end
cget(key)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 342
  def cget(key)
    @tree.itemcget(@id, key)
  end
close_tree(recurse=None)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 358
  def close_tree(recurse=None)
    @tree.close_tree(@id, recurse)
    self
  end
configinfo(key=nil)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 350
  def configinfo(key=nil)
    @tree.itemconfiginfo(@id, key)
  end
configure(key, val=None)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 346
  def configure(key, val=None)
    @tree.itemconfigure(@id, key, val)
  end
current_configinfo(key=nil)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 354
  def current_configinfo(key=nil)
    @tree.current_itemconfiginfo(@id, key)
  end
delete()

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 363
  def delete
    @tree.delete(@id)
    self
  end
edit(*args)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 368
  def edit(*args)
    @tree.edit(@id, *args)
    self
  end
exist?()

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 373
  def exist?
    @tree.exist?(@id)
  end
id()

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 329
  def id
    @id
  end
index()

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 377
  def index
    @tree.index(@id)
  end
move(index, parent=nil)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 381
  def move(index, parent=nil)
    if parent
      @tree.move(parent, @id, index)
    else
      @tree.move(self.parent, @id, index)
    end
  end
open?()

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 394
  def open?
    bool(@tree.itemcget(@id, 'open'))
  end
open_tree(recurse=None)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 389
  def open_tree(recurse=None)
    @tree.open_tree(@id, recurse)
    self
  end
parent()

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 398
  def parent
    @tree.parent(@id)
  end
reorder(neworder)

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 402
  def reorder(neworder)
    @tree.reorder(@id, neworder)
  end
see()

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 406
  def see
    @tree.see(@id)
  end
selection_add()

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 410
  def selection_add
    @tree.selection_add(@id)
  end
selection_remove()

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 414
  def selection_remove
    @tree.selection_remove(@id)
  end
selection_set()

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 418
  def selection_set
    @tree.selection_set(@id)
  end
selection_toggle()

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 422
  def selection_toggle
    @tree.selection_toggle(@id)
  end
toggle()

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 426
  def toggle
    @tree.toggle(@id)
  end
tree()

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 325
  def tree
    @tree
  end
visible()

[Source]

# File tk/lib/tkextlib/bwidget/tree.rb, line 430
  def visible
    @tree.visible(@id)
  end


Module: Tk::BWidget::Widget

Module | Tk::BWidget::Widget
In: | tk/lib/tkextlib/bwidget/widget.rb

Methods

__cget_cmd __config_cmd __pathname add_map bwinclude cget create declare define destroy focus_next focus_ok focus_prev generate_doc generate_widget_doc get_option get_variable has_changed init set_option sub_cget sync_options tkinclude

Included Modules

Tk

Public Class methods

__cget_cmd()

[Source]

# File tk/lib/tkextlib/bwidget/widget.rb, line 24
  def self.__cget_cmd
    ['Widget::cget']
  end
__config_cmd()

[Source]

# File tk/lib/tkextlib/bwidget/widget.rb, line 28
  def self.__config_cmd
    ['Widget::configure']
  end
__pathname()

[Source]

# File tk/lib/tkextlib/bwidget/widget.rb, line 20
  def self.__pathname
    'Widget::configure'
  end
add_map(klass, subclass, subpath, opts)

[Source]

# File tk/lib/tkextlib/bwidget/widget.rb, line 36
  def self.add_map(klass, subclass, subpath, opts)
    tk_call('Widget::addmap', klass, subclass, subpath, opts)
  end
bwinclude(klass, subclass, subpath, *args)

[Source]

# File tk/lib/tkextlib/bwidget/widget.rb, line 40
  def self.bwinclude(klass, subclass, subpath, *args)
    tk_call('Widget::bwinclude', klass, subclass, subpath, *args)
  end
cget(slot)

[Source]

# File tk/lib/tkextlib/bwidget/widget.rb, line 32
  def self.cget(slot)
    self.current_configinfo(slot).values[0]
  end
create(klass, path, rename=None, &b)

[Source]

# File tk/lib/tkextlib/bwidget/widget.rb, line 44
  def self.create(klass, path, rename=None, &b)
    win = window(tk_call('Widget::create', klass, path, rename))
    win.instance_eval(&b) if b
    win
  end
declare(klass, optlist)

[Source]

# File tk/lib/tkextlib/bwidget/widget.rb, line 50
  def self.declare(klass, optlist)
    tk_call('Widget::declare', klass, optlist)
  end
define(klass, filename, *args)

[Source]

# File tk/lib/tkextlib/bwidget/widget.rb, line 54
  def self.define(klass, filename, *args)
    tk_call('Widget::define', klass, filename, *args)
  end
destroy(win)

[Source]

# File tk/lib/tkextlib/bwidget/widget.rb, line 58
  def self.destroy(win)
    tk_call('Widget::destroy', _epath(win))
  end
focus_next(win)

[Source]

# File tk/lib/tkextlib/bwidget/widget.rb, line 62
  def self.focus_next(win)
    tk_call('Widget::focusNext', win)
  end
focus_ok(win)

[Source]

# File tk/lib/tkextlib/bwidget/widget.rb, line 66
  def self.focus_ok(win)
    tk_call('Widget::focusOk', win)
  end
focus_prev(win)

[Source]

# File tk/lib/tkextlib/bwidget/widget.rb, line 70
  def self.focus_prev(win)
    tk_call('Widget::focusPrev', win)
  end
generate_doc(dir, widgetlist)

[Source]

# File tk/lib/tkextlib/bwidget/widget.rb, line 74
  def self.generate_doc(dir, widgetlist)
    tk_call('Widget::generate-doc', dir, widgetlist)
  end
generate_widget_doc(klass, iscmd, file)

[Source]

# File tk/lib/tkextlib/bwidget/widget.rb, line 78
  def self.generate_widget_doc(klass, iscmd, file)
    tk_call('Widget::generate-widget-doc', klass, iscmd, file)
  end
get_option(win, option)

[Source]

# File tk/lib/tkextlib/bwidget/widget.rb, line 82
  def self.get_option(win, option)
    tk_call('Widget::getoption', win, option)
  end
get_variable(win, varname, my_varname=None)

[Source]

# File tk/lib/tkextlib/bwidget/widget.rb, line 86
  def self.get_variable(win, varname, my_varname=None)
    tk_call('Widget::getVariable', win, varname, my_varname)
  end
has_changed(win, option, pvalue)

[Source]

# File tk/lib/tkextlib/bwidget/widget.rb, line 90
  def self.has_changed(win, option, pvalue)
    tk_call('Widget::hasChanged', win, option, pvalue)
  end
init(klass, win, options)

[Source]

# File tk/lib/tkextlib/bwidget/widget.rb, line 94
  def self.init(klass, win, options)
    tk_call('Widget::init', klass, win, options)
  end
set_option(win, option, value)

[Source]

# File tk/lib/tkextlib/bwidget/widget.rb, line 98
  def self.set_option(win, option, value)
    tk_call('Widget::setoption', win, option, value)
  end
sub_cget(win, subwidget)

[Source]

# File tk/lib/tkextlib/bwidget/widget.rb, line 102
  def self.sub_cget(win, subwidget)
    tk_call('Widget::subcget', win, subwidget)
  end
sync_options(klass, subclass, subpath, options)

[Source]

# File tk/lib/tkextlib/bwidget/widget.rb, line 106
  def self.sync_options(klass, subclass, subpath, options)
    tk_call('Widget::syncoptions', klass, subclass, subpath, options)
  end
tkinclude(klass, tkwidget, subpath, *args)

[Source]

# File tk/lib/tkextlib/bwidget/widget.rb, line 110
  def self.tkinclude(klass, tkwidget, subpath, *args)
    tk_call('Widget::tkinclude', klass, tkwidget, subpath, *args)
  end


Class: Tk::BinaryString

Class | Tk::BinaryString
In: | tk/lib/tk/encodedstr.rb
Parent: | EncodedString

Constants

Encoding = 'binary'.freeze


Module: Tk::Clock

Module | Tk::Clock
In: | tk/lib/tk/clock.rb

Methods

add clicks format formatGMT microseconds milliseconds scan scanGMT seconds

Included Modules

Tk

Public Class methods

add(clk, *args)

[Source]

# File tk/lib/tk/clock.rb, line 11
    def self.add(clk, *args)
      tk_call_without_enc('clock','add', clk, *args).to_i
    end
clicks(ms=nil)

[Source]

# File tk/lib/tk/clock.rb, line 15
    def self.clicks(ms=nil)
      ms = ms.to_s if ms.kind_of?(Symbol)
      case ms
      when nil, ''
        tk_call_without_enc('clock','clicks').to_i
      when /^mic/
        tk_call_without_enc('clock','clicks','-microseconds').to_i
      when /^mil/
        tk_call_without_enc('clock','clicks','-milliseconds').to_i
      else
        tk_call_without_enc('clock','clicks','-milliseconds').to_i
      end
    end
format(clk, form=nil)

[Source]

# File tk/lib/tk/clock.rb, line 29
    def self.format(clk, form=nil)
      if form
        tk_call('clock','format',clk,'-format',form)
      else
        tk_call('clock','format',clk)
      end
    end
formatGMT(clk, form=nil)

[Source]

# File tk/lib/tk/clock.rb, line 37
    def self.formatGMT(clk, form=nil)
      if form
        tk_call('clock','format',clk,'-format',form,'-gmt','1')
      else
        tk_call('clock','format',clk,'-gmt','1')
      end
    end
microseconds()

[Source]

# File tk/lib/tk/clock.rb, line 67
    def self.microseconds
      tk_call_without_enc('clock','microseconds').to_i
    end
milliseconds()

[Source]

# File tk/lib/tk/clock.rb, line 64
    def self.milliseconds
      tk_call_without_enc('clock','milliseconds').to_i
    end
scan(str, base=nil)

[Source]

# File tk/lib/tk/clock.rb, line 45
    def self.scan(str, base=nil)
      if base
        tk_call('clock','scan',str,'-base',base).to_i
      else
        tk_call('clock','scan',str).to_i
      end
    end
scanGMT(str, base=nil)

[Source]

# File tk/lib/tk/clock.rb, line 53
    def self.scanGMT(str, base=nil)
      if base
        tk_call('clock','scan',str,'-base',base,'-gmt','1').to_i
      else
        tk_call('clock','scan',str,'-gmt','1').to_i
      end
    end
seconds()

[Source]

# File tk/lib/tk/clock.rb, line 61
    def self.seconds
      tk_call_without_enc('clock','seconds').to_i
    end


Class: Tk::EncodedString

Class | Tk::EncodedString
In: | tk/lib/tk/encodedstr.rb
Parent: | String

Methods

new new_with_utf_backslash new_without_utf_backslash subst_tk_backslash subst_utf_backslash to_backslash_sequence utf_backslash utf_to_backslash utf_to_backslash_sequence

Constants

Encoding = nil

Attributes

encoding [R]

Public Class methods

new(str, enc = nil)

[Source]

# File tk/lib/tk/encodedstr.rb, line 68
    def initialize(str, enc = nil)
      super(str)
      # @encoding = ( enc ||
      #              ((self.class::Encoding)?
      #                  self.class::Encoding : Tk.encoding_system) )
      @encoding = ( enc ||
                   ((self.class::Encoding)?
                         self.class::Encoding :
                         ((Tk.encoding)? Tk.encoding : Tk.encoding_system) ) )
    end
new_with_utf_backslash(str, enc = nil)

[Source]

# File tk/lib/tk/encodedstr.rb, line 60
    def self.new_with_utf_backslash(str, enc = nil)
      self.new('', enc).replace(self.subst_utf_backslash(str))
    end
new_without_utf_backslash(str, enc = nil)

[Source]

# File tk/lib/tk/encodedstr.rb, line 64
    def self.new_without_utf_backslash(str, enc = nil)
      self.new('', enc).replace(str)
    end
subst_tk_backslash(str)

[Source]

# File tk/lib/tk/encodedstr.rb, line 21
    def self.subst_tk_backslash(str)
      TclTkLib._subst_Tcl_backslash(str)
    end
subst_utf_backslash(str)

[Source]

# File tk/lib/tk/encodedstr.rb, line 13
    def self.subst_utf_backslash(str)
      # str.gsub(/\\u([0-9A-Fa-f]{1,4})/){[$1.hex].pack('U')}
      TclTkLib._subst_UTF_backslash(str)
    end
to_backslash_sequence(str)

[Source]

# File tk/lib/tk/encodedstr.rb, line 38
    def self.to_backslash_sequence(str)
      str.unpack('U*').collect{|c|
        if c <= 0x1F  # control character
          case c
          when 0x07; '\a'
          when 0x08; '\b'
          when 0x09; '\t'
          when 0x0a; '\n'
          when 0x0b; '\v'
          when 0x0c; '\f'
          when 0x0d; '\r'
          else
            format('\x%02X', c)
          end
        elsif c <= 0xFF  # ascii character
          c.chr
        else
          format('\u%X', c)
        end
      }.join('')
    end
utf_backslash(str)

[Source]

# File tk/lib/tk/encodedstr.rb, line 17
    def self.utf_backslash(str)
      self.subst_utf_backslash(str)
    end
utf_to_backslash(str)

[Source]

# File tk/lib/tk/encodedstr.rb, line 34
    def self.utf_to_backslash(str)
      self.utf_to_backslash_sequence(str)
    end
utf_to_backslash_sequence(str)

[Source]

# File tk/lib/tk/encodedstr.rb, line 25
    def self.utf_to_backslash_sequence(str)
      str.unpack('U*').collect{|c|
        if c <= 0xFF  # ascii character
          c.chr
        else
          format('\u%X', c)
        end
      }.join('')
    end


Module: Tk::Encoding

Module | Tk::Encoding
In: | tk/lib/tk.rb

Methods

encoding encoding encoding= encoding= encoding_convert_from encoding_convert_from encoding_convert_to encoding_convert_to encoding_convertfrom encoding_convertfrom encoding_convertto encoding_convertto encoding_names encoding_names encoding_system encoding_system encoding_system= encoding_system=

Constants

TkCommandNames = ['encoding'.freeze].freeze

Public Instance methods

encoding()

[Source]

# File tk/lib/tk.rb, line 2313
      def encoding
        nil
      end
encoding()

[Source]

# File tk/lib/tk.rb, line 2220
      def encoding
        TkCore::INTERP.encoding
      end
encoding=(name)

[Source]

# File tk/lib/tk.rb, line 2216
      def encoding=(name)
        TkCore::INTERP.encoding = name
      end
encoding=(name)

[Source]

# File tk/lib/tk.rb, line 2310
      def encoding=(name)
        nil
      end
encoding_convert_from(str, enc=nil)

Alias for encoding_convertfrom

encoding_convert_from(str, enc=nil)

Alias for encoding_convertfrom

encoding_convert_to(str, enc=nil)

Alias for encoding_convertto

encoding_convert_to(str, enc=nil)

Alias for encoding_convertto

encoding_convertfrom(str, enc=nil)

[Source]

# File tk/lib/tk.rb, line 2236
      def encoding_convertfrom(str, enc=nil)
        # str is an usual enc string or a Tcl's internal string expression
        # in enc (which is returned from 'encoding_convertto' method).
        # the return value is a UTF-8 string.
        enc = encoding_system unless enc
        ret = TkCore::INTERP.__invoke('encoding', 'convertfrom', enc, str)
        ret.instance_variable_set('@encoding', 'utf-8')
        ret
      end
encoding_convertfrom(str, enc=None)

[Source]

# File tk/lib/tk.rb, line 2326
      def encoding_convertfrom(str, enc=None)
        str
      end
encoding_convertto(str, enc=None)

[Source]

# File tk/lib/tk.rb, line 2331
      def encoding_convertto(str, enc=None)
        str
      end
encoding_convertto(str, enc=nil)

[Source]

# File tk/lib/tk.rb, line 2247
      def encoding_convertto(str, enc=nil)
        # str must be a UTF-8 string.
        # The return value is a Tcl's internal string expression in enc.
        # To get an usual enc string, use Tk.fromUTF8(ret_val, enc).
        enc = encoding_system unless enc
        ret = TkCore::INTERP.__invoke('encoding', 'convertto', enc, str)
        ret.instance_variable_set('@encoding', 'binary')
        ret
      end
encoding_names()

[Source]

# File tk/lib/tk.rb, line 2224
      def encoding_names
        tk_split_simplelist(tk_call('encoding', 'names'))
      end
encoding_names()

[Source]

# File tk/lib/tk.rb, line 2316
      def encoding_names
        nil
      end
encoding_system()

[Source]

# File tk/lib/tk.rb, line 2228
      def encoding_system
        tk_call('encoding', 'system')
      end
encoding_system()

[Source]

# File tk/lib/tk.rb, line 2319
      def encoding_system
        nil
      end
encoding_system=(enc)

[Source]

# File tk/lib/tk.rb, line 2322
      def encoding_system=(enc)
        nil
      end
encoding_system=(enc)

[Source]

# File tk/lib/tk.rb, line 2232
      def encoding_system=(enc)
        tk_call('encoding', 'system', enc)
      end


Class: Tk::HTML_Widget

Class | Tk::HTML_Widget
In: | tk/lib/tkextlib/tkHTML/htmlwidget.rb
Parent: | TkWindow

Methods

ascii_text base64_decode base64_encode bgimage break_text clear clipping_window clipwin coords crc32 dom_attr dom_form_element dom_formel dom_id dom_ids dom_name_index dom_nameidx dom_radio_index dom_radioidx dom_tree dom_value form_info forminfo gunzip_data gunzip_file gzip_data gzip_file href html_text htmlclip image_add image_at image_set image_update images index insert_cursor layout lockcopy names on_screen over over_attr over_markup package_name package_version parse plain_text postscript reformat refresh resolver selection_clear selection_set sizewindow source stdchan text_ascii text_break text_delete text_find text_format text_html text_insert text_table token_DOM token_append token_attrs token_define token_delete token_dom token_dom_tokens token_domtokens token_find token_get token_get_attr token_get_end token_getend token_handler token_insert token_list token_markup token_offset token_on_events token_set_attr token_unique url_join url_split xor

Included Modules

Scrollable

Classes and Modules

Class Tk::HTML_Widget::ClippingWindow

Constants

PACKAGE_NAME | = | 'Tkhtml'.freeze
TkCommandNames | = | ['html'.freeze].freeze
WidgetClassName | = | 'Html'.freeze

Public Class methods

base64_decode(dat)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 151
  def self.base64_decode(dat)
    tk_call('html', 'base64', 'encode', dat)
  end
base64_encode(dat)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 147
  def self.base64_encode(dat)
    tk_call('html', 'base64', 'encode', dat)
  end
crc32(data)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 167
  def self.crc32(data)
    tk_call('html', 'crc32', data)
  end
gunzip_data(dat)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 143
  def self.gunzip_data(dat)
    tk_call('html', 'gunzip', 'data', filet)
  end
gunzip_file(file, dat)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 135
  def self.gunzip_file(file, dat)
    tk_call('html', 'gunzip', 'file', filet)
  end
gzip_data(dat)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 139
  def self.gzip_data(dat)
    tk_call('html', 'gzip', 'data', file, dat)
  end
gzip_file(file, dat)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 131
  def self.gzip_file(file, dat)
    tk_call('html', 'gzip', 'file', file, dat)
  end
lockcopy(src, dst)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 127
  def self.lockcopy(src, dst)
    tk_call('html', 'lockcopy', src, dst)
  end
package_name()

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 20
    def self.package_name
      PACKAGE_NAME
    end
package_version()

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 24
    def self.package_version
      begin
        TkPackage.require('Tkhtml')
      rescue
        ''
      end
    end
reformat(src, dst, txt)

class methods

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 115
  def self.reformat(src, dst, txt)
    tk_call('html', 'reformat', src, dst, txt)
  end
stdchan(cmd, channel)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 163
  def self.stdchan(cmd, channel)
    tk_call('html', 'stdchan', cmd, channel)
  end
text_format(dat, len)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 155
  def self.text_format(dat, len)
    tk_call('html', 'text', 'format', dat, len)
  end
url_join(*args)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 119
  def self.url_join(*args) # args := sheme authority path query fragment
    tk_call('html', 'urljoin', *args)
  end
url_split(uri)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 123
  def self.url_split(uri)
    tk_call('html', 'urlsplit', uri)
  end
xor(cmd, *args)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 159
  def self.xor(cmd, *args)
    tk_call('html', 'xor', cmd, *args)
  end

Public Instance methods

ascii_text(first, last)

Alias for plain_text

bgimage(image, tid=None)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 180
  def bgimage(image, tid=None)
    tk_send('bgimage', image, tid)
    self
  end
break_text(idx)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 314
  def break_text(idx)
    tk_send('text', 'break', idx)
  end
clear()

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 185
  def clear()
    tk_send('clear')
    self
  end
clipping_window()

instance methods

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 174
  def clipping_window
    ClippingWindow.new(self)
  end
clipwin()

Alias for clipping_window

coords(index=None, percent=None)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 190
  def coords(index=None, percent=None)
    tk_send('coords', index, percent)
  end
dom_attr(idx)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 432
  def dom_attr(idx)
    tk_send('dom', 'attr', idx)
  end
dom_form_element(name)

Alias for dom_formel

dom_formel(name)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 436
  def dom_formel(name)
    tk_send('dom', 'formel', name)
  end
dom_id(*spec)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 420
  def dom_id(*spec)
    tk_send('dom', 'id', *spec)
  end
dom_ids(*spec)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 424
  def dom_ids(*spec)
    list(tk_send('dom', 'ids', *spec))
  end
dom_name_index(tag, name)

Alias for dom_nameidx

dom_nameidx(tag, name)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 410
  def dom_nameidx(tag, name)
    number(tk_send('dom', 'nameidx', tag, name))
  end
dom_radio_index(tag, name)

Alias for dom_radioidx

dom_radioidx(tag, name)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 415
  def dom_radioidx(tag, name)
    number(tk_send('dom', 'radioidx', tag, name))
  end
dom_tree(idx, val)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 441
  def dom_tree(idx, val)
    list(tk_send('dom', 'tree', idx, val))
  end
dom_value(*spec)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 428
  def dom_value(*spec)
    list(tk_send('dom', 'value', *spec))
  end
form_info(*args)

Alias for forminfo

forminfo(*args)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 194
  def forminfo(*args)
    tk_send('forminfo', *args)
  end
href(x, y)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 199
  def href(x, y)
    simplelist(tk_send('href', x, y))
  end
html_text(first, last)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 304
  def html_text(first, last)
    tk_send('text', 'html', first, last)
  end
htmlclip()

Alias for clipping_window

image_add(id, img)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 203
  def image_add(id, img)
    tk_send('imageadd', id, img)
    self
  end
image_at(x, y)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 208
  def image_at(x, y)
    tk_send('imageat', x, y)
  end
image_set(id, num)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 216
  def image_set(id, num)
    tk_send('imageset', id, num)
    self
  end
image_update(id, imgs)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 221
  def image_update(id, imgs)
    tk_send('imageupdate', id, imgs)
    self
  end
images()

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 212
  def images()
    list(tk_send('images'))
  end
index(idx, count=None, unit=None)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 226
  def index(idx, count=None, unit=None)
    tk_send('index', idx, count, unit)
  end
insert_cursor(idx)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 230
  def insert_cursor(idx)
    tk_send('insert', idx)
  end
layout()

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 277
  def layout()
    tk_send('layout')
  end
names()

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 234
  def names()
    simple_list(tk_send('names'))
  end
on_screen(id, x, y)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 238
  def on_screen(id, x, y)
    bool(tk_send('onscreen', id, x, y))
  end
over(x, y)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 242
  def over(x, y)
    list(tk_send('over', x, y))
  end
over_attr(x, y, attrs)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 250
  def over_attr(x, y, attrs)
    list(tk_send('overattr', x, y, attrs))
  end
over_markup(x, y)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 246
  def over_markup(x, y)
    list(tk_send('over', x, y, '-muponly'))
  end
parse(txt)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 254
  def parse(txt)
    tk_send('parse', txt)
    self
  end
plain_text(first, last)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 293
  def plain_text(first, last)
    tk_send('text', 'ascii', first, last)
  end
postscript(*args)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 285
  def postscript(*args)
    tk_send('postscript', *args)
  end
refresh(*opts)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 273
  def refresh(*opts)
    tk_send('refresh', *opts)
  end
resolver(*uri_args)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 259
  def resolver(*uri_args)
    tk_send('resolver', *uri_args)
  end
selection_clear()

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 263
  def selection_clear()
    tk_send('selection', 'clear')
    self
  end
selection_set(first, last)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 268
  def selection_set(first, last)
    tk_send('selection', 'set', first, last)
    self
  end
sizewindow(*args)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 281
  def sizewindow(*args)
    tk_send('sizewindow', *args)
  end
source()

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 289
  def source()
    tk_send('source')
  end
text_ascii(first, last)

Alias for plain_text

text_break(idx)

Alias for break_text

text_delete(first, last)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 299
  def text_delete(first, last)
    tk_send('text', 'delete', first, last)
    self
  end
text_find(txt, *args)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 319
  def text_find(txt, *args)
    tk_send('text', 'find', txt, *args)
  end
text_html(first, last)

Alias for html_text

text_insert(idx, txt)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 309
  def text_insert(idx, txt)
    tk_send('text', 'insert', idx, txt)
    self
  end
text_table(idx, imgs=None, attrs=None)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 323
  def text_table(idx, imgs=None, attrs=None)
    tk_send('text', 'table', idx, imgs, attrs)
  end
token_DOM(first, last=None)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 358
  def token_DOM(first, last=None)
    list(tk_send('token', 'domtokens', first, last))
  end
token_append(tag, *args)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 327
  def token_append(tag, *args)
    tk_send('token', 'append', tag, *args)
    self
  end
token_attrs(*args)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 398
  def token_attrs(*args)
    list(tk_send('token', 'attrs', *args))
  end
token_define(*args)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 337
  def token_define(*args)
    tk_send('token', 'defile', *args)
    self
  end
token_delete(first, last=None)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 332
  def token_delete(first, last=None)
    tk_send('token', 'delete', first, last)
    self
  end
token_dom(first, last=None)

Alias for token_DOM

token_dom_tokens(first, last=None)

Alias for token_DOM

token_domtokens(first, last=None)

Alias for token_DOM

token_find(tag, *args)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 342
  def token_find(tag, *args)
    list(tk_send('token', 'find', tag, *args))
  end
token_get(first, last=None)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 346
  def token_get(first, last=None)
    list(tk_send('token', 'get', first, last))
  end
token_get_attr(idx, name=None)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 374
  def token_get_attr(idx, name=None)
    list(tk_send('token', 'attr', idx, name))
  end
token_get_end(idx)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 365
  def token_get_end(idx)
    tk_send('token', 'getend', idx)
  end
token_getend(idx)

Alias for token_get_end

token_handler(tag, cmd=nil, &b)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 383
  def token_handler(tag, cmd=nil, &b)
    cmd = Proc.new(&b) if !cmd && b
    if cmd
      tk_send('token', 'handler', tag, cmd)
      return self
    else
      return tk_send('token', 'handler', tag)
    end
  end
token_insert(idx, tag, *args)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 393
  def token_insert(idx, tag, *args)
    tk_send('token', 'insert', idx, tag, *args)
    self
  end
token_list(first, last=None)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 350
  def token_list(first, last=None)
    list(tk_send('token', 'list', first, last))
  end
token_markup(first, last=None)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 354
  def token_markup(first, last=None)
    list(tk_send('token', 'markup', first, last))
  end
token_offset(start, num1, num2)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 370
  def token_offset(start, num1, num2)
    list(tk_send('token', 'offset', start, num1, num2))
  end
token_on_events(*args)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 406
  def token_on_events(*args)
    list(tk_send('token', 'onEvents', *args))
  end
token_set_attr(idx, name=None, val=None)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 378
  def token_set_attr(idx, name=None, val=None)
    tk_send('token', 'attr', idx, name, val)
    self
  end
token_unique(*args)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 402
  def token_unique(*args)
    list(tk_send('token', 'unique', *args))
  end


Class: Tk::HTML_Widget::ClippingWindow

Class | Tk::HTML_Widget::ClippingWindow
In: | tk/lib/tkextlib/tkHTML/htmlwidget.rb
Parent: | TkWindow

Methods

method_missing new new

Constants

WidgetClassName | = | 'HtmlClip'.freeze
HtmlClip_TBL | = | TkCore::INTERP.create_table

Public Class methods

new(parent)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 78
  def initialize(parent)
    @parent = parent
    @ppath = parent.path
    @path = @id = @ppath + '.x'
    HtmlClip_TBL[@ppath] = self
  end
new(parent, keys={})

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 44
  def self.new(parent, keys={})
    if parent.kind_of?(Hash)
      keys = TkComm._symbolkey2str(parent)
      parent = keys.delete('parent')
    end

    if parent.kind_of?(String)
      ppath = parent.path
    elsif parent
      ppath = parent
    else
      ppath = ''
    end
    return HtmlClip_TBL[ppath] if HtmlClip_TBL[ppath]

    widgetname = keys.delete('widgetname')
    if widgetname =~ /^(.*)\.[^.]+$/
      ppath2 = $1
      if ppath2[0] != ?.
        ppath2 = ppath + '.' + ppath2
      end
      return HtmlClip_TBL[ppath2] if HtmlClip_TBL[ppath2]

      ppath = ppath2
    end

    parent = TkComm._genobj_for_tkwidget(ppath)
    unless parent.kind_of?(Tk::HTML_Widget)
      fail ArgumentError, "parent must be a Tk::HTML_Widget instance"
    end

    super(parent)
  end

Public Instance methods

method_missing(m, *args, &b)

[Source]

# File tk/lib/tkextlib/tkHTML/htmlwidget.rb, line 85
  def method_missing(m, *args, &b)
    @parent.__send__(m, *args, &b)
  end


Class: Tk::ICONS

Class | Tk::ICONS
In: | tk/lib/tkextlib/ICONS/icons.rb
Parent: | TkImage

Methods

create delete delete name new new package_name package_version query query

Constants

PACKAGE_NAME = 'icons'.freeze

Public Class methods

create(*args)

[Source]

# File tk/lib/tkextlib/ICONS/icons.rb, line 34
    def self.create(*args)  # icon, icon, ..., ?option=>value, ...?
      if args[-1].kind_of?(Hash)
        keys = args.pop
        icons = simplelist(tk_call('::icons::icons', 'create',
                                   *(hash_kv(keys) << (args.flatten))))
      else
        icons = simplelist(tk_call('::icons::icons', 'create',
                                   args.flatten))
      end

      icons.collect{|icon| self.new(icon, :without_creating=>true)}
    end
delete(*icons)

[Source]

# File tk/lib/tkextlib/ICONS/icons.rb, line 47
    def self.delete(*icons)  # icon, icon, ...
      icons = icons.flatten
      return if icons.empty?
      icons.map!{|icon|
        if icon.kind_of?(Tk::ICONS)
          Tk_IMGTBL.delete(icon.path)
          icon.name
        elsif icon.to_s =~ /^::icon::(.*)/
          name = $1
          Tk_IMGTBL.delete(icon)
          name
        else
          Tk_IMGTBL.delete("::icon::#{icon}")
          icon
        end
      }
      tk_call('::icons::icons', 'delete', icons)
    end
new(name, keys=nil)

[Source]

# File tk/lib/tkextlib/ICONS/icons.rb, line 78
    def self.new(name, keys=nil)
      unless obj = Tk_IMGTBL["::icon::#{name}"]
        obj = allocate()
        obj.instance_eval{initialize(name, keys)}
      end
      obj
    end
new(name, keys=nil)

[Source]

# File tk/lib/tkextlib/ICONS/icons.rb, line 86
    def initialize(name, keys=nil)
      if name.kind_of?(String) && name =~ /^::icon::(.+)$/
          @name = $1
          @path = name
      else
        @name = name.to_s
        @path = "::icon::#{@name}"
      end
      keys = _symbolkey2str(keys)
      unless keys.delete('without_creating')
        tk_call('::icons::icons', 'create', *(hash_kv(keys) << @name))
      end
      Tk_IMGTBL[@path] = self
    end
package_name()

[Source]

# File tk/lib/tkextlib/ICONS/icons.rb, line 22
    def self.package_name
      PACKAGE_NAME
    end
package_version()

[Source]

# File tk/lib/tkextlib/ICONS/icons.rb, line 26
    def self.package_version
      begin
        TkPackage.require('icons')
      rescue
        ''
      end
    end
query(*args)

[Source]

# File tk/lib/tkextlib/ICONS/icons.rb, line 66
    def self.query(*args)  # icon, icon, ..., ?option=>value, ...?
      if args[-1].kind_of?(Hash)
        keys = args.pop
        simplelist(tk_call('::icons::icons', 'query',
                           *(hash_kv(keys) << (args.flatten))))
      else
        simplelist(tk_call('::icons::icons', 'query', args.flatten))
      end . map{|inf| list(inf) }
    end

Public Instance methods

delete()

[Source]

# File tk/lib/tkextlib/ICONS/icons.rb, line 105
    def delete
      Tk_IMGTBL.delete(@path)
      tk_call('::icons::icons', 'delete', @name)
      self
    end
name()

[Source]

# File tk/lib/tkextlib/ICONS/icons.rb, line 101
    def name
      @name
    end
query(keys={})

[Source]

# File tk/lib/tkextlib/ICONS/icons.rb, line 111
    def query(keys={})
      list(simplelist(tk_call('::icons::icons', 'query',
                               *(hash_kv(keys) << @name))
                      )[0])
    end


Module: Tk::Img

Module | Tk::Img
In: | tk/lib/tkextlib/tkimg.rb tk/lib/tkextlib/tkimg/xpm.rb tk/lib/tkextlib/tkimg/xbm.rb tk/lib/tkextlib/tkimg/window.rb tk/lib/tkextlib/tkimg/tiff.rb tk/lib/tkextlib/tkimg/tga.rb tk/lib/tkextlib/tkimg/sun.rb tk/lib/tkextlib/tkimg/sgi.rb tk/lib/tkextlib/tkimg/ps.rb tk/lib/tkextlib/tkimg/ppm.rb tk/lib/tkextlib/tkimg/png.rb tk/lib/tkextlib/tkimg/pixmap.rb tk/lib/tkextlib/tkimg/pcx.rb tk/lib/tkextlib/tkimg/jpeg.rb tk/lib/tkextlib/tkimg/ico.rb tk/lib/tkextlib/tkimg/gif.rb tk/lib/tkextlib/tkimg/bmp.rb

Methods

package_name package_version

Classes and Modules

Module Tk::Img::BMP
Module Tk::Img::GIF
Module Tk::Img::ICO
Module Tk::Img::JPEG
Module Tk::Img::PCX
Module Tk::Img::PIXMAP
Module Tk::Img::PNG
Module Tk::Img::PPM
Module Tk::Img::PS
Module Tk::Img::SGI
Module Tk::Img::SUN
Module Tk::Img::TGA
Module Tk::Img::TIFF
Module Tk::Img::WINDOW
Module Tk::Img::XBM
Module Tk::Img::XPM

Constants

PACKAGE_NAME = 'Img'.freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/tkimg.rb, line 21
    def self.package_name
      PACKAGE_NAME
    end
package_version()

[Source]

# File tk/lib/tkextlib/tkimg.rb, line 25
    def self.package_version
      begin
        TkPackage.require('Img')
      rescue
        ''
      end
    end


Module: Tk::Img::BMP

Module | Tk::Img::BMP
In: | tk/lib/tkextlib/tkimg/bmp.rb

Methods

package_name package_version

Constants

PACKAGE_NAME = 'img::bmp'.freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/tkimg/bmp.rb, line 20
      def self.package_name
        PACKAGE_NAME
      end
package_version()

[Source]

# File tk/lib/tkextlib/tkimg/bmp.rb, line 24
      def self.package_version
        begin
          TkPackage.require('img::bmp')
        rescue
          ''
        end
      end


Module: Tk::Img::GIF

Module | Tk::Img::GIF
In: | tk/lib/tkextlib/tkimg/gif.rb

Methods

package_name package_version

Constants

PACKAGE_NAME = 'img::gif'.freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/tkimg/gif.rb, line 20
      def self.package_name
        PACKAGE_NAME
      end
package_version()

[Source]

# File tk/lib/tkextlib/tkimg/gif.rb, line 24
      def self.package_version
        begin
          TkPackage.require('img::gif')
        rescue
          ''
        end
      end


Module: Tk::Img::ICO

Module | Tk::Img::ICO
In: | tk/lib/tkextlib/tkimg/ico.rb

Methods

package_name package_version

Constants

PACKAGE_NAME = 'img::ico'.freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/tkimg/ico.rb, line 20
      def self.package_name
        PACKAGE_NAME
      end
package_version()

[Source]

# File tk/lib/tkextlib/tkimg/ico.rb, line 24
      def self.package_version
        begin
          TkPackage.require('img::ico')
        rescue
          ''
        end
      end


Module: Tk::Img::JPEG

Module | Tk::Img::JPEG
In: | tk/lib/tkextlib/tkimg/jpeg.rb

Methods

package_name package_version

Constants

PACKAGE_NAME = 'img::jpeg'.freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/tkimg/jpeg.rb, line 20
      def self.package_name
        PACKAGE_NAME
      end
package_version()

[Source]

# File tk/lib/tkextlib/tkimg/jpeg.rb, line 24
      def self.package_version
        begin
          TkPackage.require('img::jpeg')
        rescue
          ''
        end
      end


Module: Tk::Img::PCX

Module | Tk::Img::PCX
In: | tk/lib/tkextlib/tkimg/pcx.rb

Methods

package_name package_version

Constants

PACKAGE_NAME = 'img::pcx'.freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/tkimg/pcx.rb, line 20
      def self.package_name
        PACKAGE_NAME
      end
package_version()

[Source]

# File tk/lib/tkextlib/tkimg/pcx.rb, line 24
      def self.package_version
        begin
          TkPackage.require('img::pcx')
        rescue
          ''
        end
      end


Module: Tk::Img::PIXMAP

Module | Tk::Img::PIXMAP
In: | tk/lib/tkextlib/tkimg/pixmap.rb

Methods

package_name package_version

Constants

PACKAGE_NAME = 'img::pixmap'.freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/tkimg/pixmap.rb, line 20
      def self.package_name
        PACKAGE_NAME
      end
package_version()

[Source]

# File tk/lib/tkextlib/tkimg/pixmap.rb, line 24
      def self.package_version
        begin
          TkPackage.require('img::pixmap')
        rescue
          ''
        end
      end


Module: Tk::Img::PNG

Module | Tk::Img::PNG
In: | tk/lib/tkextlib/tkimg/png.rb

Methods

package_name package_version

Constants

PACKAGE_NAME = 'img::png'.freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/tkimg/png.rb, line 20
      def self.package_name
        PACKAGE_NAME
      end
package_version()

[Source]

# File tk/lib/tkextlib/tkimg/png.rb, line 24
      def self.package_version
        begin
          TkPackage.require('img::png')
        rescue
          ''
        end
      end


Module: Tk::Img::PPM

Module | Tk::Img::PPM
In: | tk/lib/tkextlib/tkimg/ppm.rb

Methods

package_name package_version

Constants

PACKAGE_NAME = 'img::ppm'.freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/tkimg/ppm.rb, line 20
      def self.package_name
        PACKAGE_NAME
      end
package_version()

[Source]

# File tk/lib/tkextlib/tkimg/ppm.rb, line 24
      def self.package_version
        begin
          TkPackage.require('img::ppm')
        rescue
          ''
        end
      end


Module: Tk::Img::PS

Module | Tk::Img::PS
In: | tk/lib/tkextlib/tkimg/ps.rb

Methods

package_name package_version

Constants

PACKAGE_NAME = 'img::ps'.freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/tkimg/ps.rb, line 20
      def self.package_name
        PACKAGE_NAME
      end
package_version()

[Source]

# File tk/lib/tkextlib/tkimg/ps.rb, line 24
      def self.package_version
        begin
          TkPackage.require('img::ps')
        rescue
          ''
        end
      end


Module: Tk::Img::SGI

Module | Tk::Img::SGI
In: | tk/lib/tkextlib/tkimg/sgi.rb

Methods

package_name package_version

Constants

PACKAGE_NAME = 'img::sgi'.freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/tkimg/sgi.rb, line 20
      def self.package_name
        PACKAGE_NAME
      end
package_version()

[Source]

# File tk/lib/tkextlib/tkimg/sgi.rb, line 24
      def self.package_version
        begin
          TkPackage.require('img::sgi')
        rescue
          ''
        end
      end


Module: Tk::Img::SUN

Module | Tk::Img::SUN
In: | tk/lib/tkextlib/tkimg/sun.rb

Methods

package_name package_version

Constants

PACKAGE_NAME = 'img::sun'.freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/tkimg/sun.rb, line 20
      def self.package_name
        PACKAGE_NAME
      end
package_version()

[Source]

# File tk/lib/tkextlib/tkimg/sun.rb, line 24
      def self.package_version
        begin
          TkPackage.require('img::sun')
        rescue
          ''
        end
      end


Module: Tk::Img::TGA

Module | Tk::Img::TGA
In: | tk/lib/tkextlib/tkimg/tga.rb

Methods

package_name package_version

Constants

PACKAGE_NAME = 'img::tga'.freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/tkimg/tga.rb, line 20
      def self.package_name
        PACKAGE_NAME
      end
package_version()

[Source]

# File tk/lib/tkextlib/tkimg/tga.rb, line 24
      def self.package_version
        begin
          TkPackage.require('img::tga')
        rescue
          ''
        end
      end


Module: Tk::Img::TIFF

Module | Tk::Img::TIFF
In: | tk/lib/tkextlib/tkimg/tiff.rb

Methods

package_name package_version

Constants

PACKAGE_NAME = 'img::tiff'.freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/tkimg/tiff.rb, line 20
      def self.package_name
        PACKAGE_NAME
      end
package_version()

[Source]

# File tk/lib/tkextlib/tkimg/tiff.rb, line 24
      def self.package_version
        begin
          TkPackage.require('img::tiff')
        rescue
          ''
        end
      end


Module: Tk::Img::WINDOW

Module | Tk::Img::WINDOW
In: | tk/lib/tkextlib/tkimg/window.rb

Methods

package_name package_version

Constants

PACKAGE_NAME = 'img::window'.freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/tkimg/window.rb, line 20
      def self.package_name
        PACKAGE_NAME
      end
package_version()

[Source]

# File tk/lib/tkextlib/tkimg/window.rb, line 24
      def self.package_version
        begin
          TkPackage.require('img::window')
        rescue
          ''
        end
      end


Module: Tk::Img::XBM

Module | Tk::Img::XBM
In: | tk/lib/tkextlib/tkimg/xbm.rb

Methods

package_name package_version

Constants

PACKAGE_NAME = 'img::xbm'.freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/tkimg/xbm.rb, line 20
      def self.package_name
        PACKAGE_NAME
      end
package_version()

[Source]

# File tk/lib/tkextlib/tkimg/xbm.rb, line 24
      def self.package_version
        begin
          TkPackage.require('img::xbm')
        rescue
          ''
        end
      end


Module: Tk::Img::XPM

Module | Tk::Img::XPM
In: | tk/lib/tkextlib/tkimg/xpm.rb

Methods

package_name package_version

Constants

PACKAGE_NAME = 'img::xpm'.freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/tkimg/xpm.rb, line 20
      def self.package_name
        PACKAGE_NAME
      end
package_version()

[Source]

# File tk/lib/tkextlib/tkimg/xpm.rb, line 24
      def self.package_version
        begin
          TkPackage.require('img::xpm')
        rescue
          ''
        end
      end


Module: Tk::Itcl

Module | Tk::Itcl
In: | tk/lib/tkextlib/itcl/incr_tcl.rb

Methods

body code code_in_namespace configbody create_itcl_class create_local_obj delete_itcl_class delete_itcl_object delete_namespace ensemble find_classes find_objects is_itcl_class is_itcl_instance is_itcl_object package_name package_version scope

Included Modules

Tk

Classes and Modules

Class Tk::Itcl::ItclObject

Constants

LIBRARY | = | TkVarAccess.new('::itcl::library')
PURIST | = | TkVarAccess.new('::itcl::purist')
VERSION | = | TkCore::INTERP._invoke("set", "::itcl::version").freeze
PATCHLEVEL | = | TkCore::INTERP._invoke("set", "::itcl::patchLevel").freeze
PACKAGE_NAME | = | 'Itcl'.freeze

Public Class methods

body(klass, func, args, body)

[Source]

# File tk/lib/tkextlib/itcl/incr_tcl.rb, line 105
    def self.body(klass, func, args, body)
      tk_call('::itcl::body', "#{klass}::#{func}", args, body)
    end
code(cmd, *args)

[Source]

# File tk/lib/tkextlib/itcl/incr_tcl.rb, line 109
    def self.code(cmd, *args)
      tk_call('::itcl::code', cmd, *args)
    end
code_in_namespace(namespace, cmd, *args)

[Source]

# File tk/lib/tkextlib/itcl/incr_tcl.rb, line 113
    def self.code_in_namespace(namespace, cmd, *args)
      tk_call('::itcl::code', '-namespace', namespace, cmd, *args)
    end
configbody(klass, var, body)

[Source]

# File tk/lib/tkextlib/itcl/incr_tcl.rb, line 117
    def self.configbody(klass, var, body)
      tk_call('::itcl::configbody', "#{klass}::#{var}", body)
    end
create_itcl_class(name, body)

[Source]

# File tk/lib/tkextlib/itcl/incr_tcl.rb, line 121
    def self.create_itcl_class(name, body)
      TkCore::INTERP._invoke('::itcl::class', name, body)
      klass = Class.new(Tk::Itcl::ItclObject)
      klass.const_set('ITCL_CLASSNAME', name.dup.freeze)
      klass
    end
create_local_obj(klass, name, *args)

[Source]

# File tk/lib/tkextlib/itcl/incr_tcl.rb, line 160
    def self.create_local_obj(klass, name, *args)
      tk_call('::itcl::local', klass, name, *args)
    end
delete_itcl_class(*names)

[Source]

# File tk/lib/tkextlib/itcl/incr_tcl.rb, line 128
    def self.delete_itcl_class(*names)
      tk_call('::itcl::delete', 'class',  *names)
    end
delete_itcl_object(*names)

[Source]

# File tk/lib/tkextlib/itcl/incr_tcl.rb, line 132
    def self.delete_itcl_object(*names)
      tk_call('::itcl::delete', 'object',  *names)
    end
delete_namespace(*names)

[Source]

# File tk/lib/tkextlib/itcl/incr_tcl.rb, line 136
    def self.delete_namespace(*names)
      tk_call('::itcl::delete', 'namespace',  *names)
    end
ensemble(name, *args)

[Source]

# File tk/lib/tkextlib/itcl/incr_tcl.rb, line 140
    def self.ensemble(name, *args)
      tk_call('::itcl::ensemble', name, *args)
    end
find_classes(pat=None)

[Source]

# File tk/lib/tkextlib/itcl/incr_tcl.rb, line 144
    def self.find_classes(pat=None)
      simplelist(tk_call('::itcl::find', 'classes', pat))
    end
find_objects(*args)

[Source]

# File tk/lib/tkextlib/itcl/incr_tcl.rb, line 148
    def self.find_objects(*args)
      simplelist(tk_call('::itcl::find', 'objects', *args))
    end
is_itcl_class(target)

[Source]

# File tk/lib/tkextlib/itcl/incr_tcl.rb, line 152
    def self.is_itcl_class(target)
      bool(tk_call('::itcl::is', 'class', target))
    end
is_itcl_instance(klass, target)

[Source]

# File tk/lib/tkextlib/itcl/incr_tcl.rb, line 164
    def self.is_itcl_instance(klass, target)
      bool(tk_call('::itcl::is', 'object', '-class', klass, target))
    end
is_itcl_object(target)

[Source]

# File tk/lib/tkextlib/itcl/incr_tcl.rb, line 156
    def self.is_itcl_object(target)
      bool(tk_call('::itcl::is', 'object', target))
    end
package_name()

[Source]

# File tk/lib/tkextlib/itcl/incr_tcl.rb, line 26
    def self.package_name
      PACKAGE_NAME
    end
package_version()

[Source]

# File tk/lib/tkextlib/itcl/incr_tcl.rb, line 30
    def self.package_version
      begin
        TkPackage.require('Itcl')
      rescue
        ''
      end
    end
scope(var)

[Source]

# File tk/lib/tkextlib/itcl/incr_tcl.rb, line 168
    def self.scope(var)
      tk_call('::itcl::scope', var)
    end


Class: Tk::Itcl::ItclObject

Class | Tk::Itcl::ItclObject
In: | tk/lib/tkextlib/itcl/incr_tcl.rb
Parent: | TkObject

Methods

call_method call_proc info_class info_function info_heritage info_inherit info_variable isa itcl_kind_of? new

Constants

ITCL_CLASSNAME | = | ''.freeze
ITCL_OBJ_ID | = | ['itclobj'.freeze, '00000'.taint].freeze
ITCL_OBJ_TBL | = | {}.taint

Public Class methods

call_proc(name, *args)

[Source]

# File tk/lib/tkextlib/itcl/incr_tcl.rb, line 55
      def self.call_proc(name, *args)
        tk_call("#{ITCL_CLASSNAME}::#{cmd}", *args)
      end
new(*args)

[Source]

# File tk/lib/tkextlib/itcl/incr_tcl.rb, line 46
      def initialize(*args)
        if (@klass = self.class::ITCL_CLASSNAME).empty?
          fail RuntimeError, 'unknown itcl class (abstract class?)'
        end
        @id = Tk::Itcl::ItclObject::TCL_OBJ_ID.join(TkCore::INTERP._ip_id_)
        @path = @id
        Tk::Itcl::ItclObject::ITCL_OBJ_ID[1].succ!
      end

Public Instance methods

call_method(name, *args)

[Source]

# File tk/lib/tkextlib/itcl/incr_tcl.rb, line 59
      def call_method(name, *args)
        tk_call(@path, name, *args)
      end
info_class()

[Source]

# File tk/lib/tkextlib/itcl/incr_tcl.rb, line 68
      def info_class
        tk_call(@path, 'info', 'class')
      end
info_function(*args)

[Source]

# File tk/lib/tkextlib/itcl/incr_tcl.rb, line 80
      def info_function(*args)
        if args[-1].kind_of?(Array)
          params = args.pop
          params.each{|param|
            param = param.to_s
            args << ( (param[0] == ?-)? param: "-#{param}" )
          }
        end
        list(tk_call(@path, 'info', 'function', *args))
      end
info_heritage()

[Source]

# File tk/lib/tkextlib/itcl/incr_tcl.rb, line 76
      def info_heritage
        list(tk_call(@path, 'info', 'heritage'))
      end
info_inherit()

[Source]

# File tk/lib/tkextlib/itcl/incr_tcl.rb, line 72
      def info_inherit
        simplelist(tk_call(@path, 'info', 'inherit'))
      end
info_variable(*args)

[Source]

# File tk/lib/tkextlib/itcl/incr_tcl.rb, line 91
      def info_variable(*args)
        if args[-1].kind_of?(Array)
          params = args.pop
          params.each{|param|
            param = param.to_s
            args << ( (param[0] == ?-)? param: "-#{param}" )
          }
        end
        list(tk_call(@path, 'info', 'variable', *args))
      end
isa(klass)

[Source]

# File tk/lib/tkextlib/itcl/incr_tcl.rb, line 63
      def isa(klass)
        bool(tk_call(@path, 'isa', klass))
      end
itcl_kind_of?(klass)

Alias for isa


Module: Tk::ItemValidateConfigure

Module | Tk::ItemValidateConfigure
In: | tk/lib/tk/validation.rb

Methods

__conv_item_vcmd_on_hash_kv __def_validcmd __get_item_validate_key2class __item_validation_class_list __item_validcmd_call itemconfigure

Public Class methods

__def_validcmd(scope, klass, keys=nil)

[Source]

# File tk/lib/tk/validation.rb, line 110
    def self.__def_validcmd(scope, klass, keys=nil)
      keys = klass._config_keys unless keys
      keys.each{|key|
        eval("def item_#{key}(id, *args, &b)
                 __item_validcmd_call(#{klass.name}, '#{key}', id, *args, &b)
              end", scope)
      }
    end

Public Instance methods

__conv_item_vcmd_on_hash_kv(keys)

[Source]

# File tk/lib/tk/validation.rb, line 147
    def __conv_item_vcmd_on_hash_kv(keys)
      key2class = __get_item_validate_key2class(tagid(tagOrId))

      keys = _symbolkey2str(keys)
      key2class.each{|key, klass|
        if keys[key].kind_of?(Array)
          cmd, *args = keys[key]
          keys[key] = klass.new(cmd, args.join(' '))
        # elsif keys[key].kind_of?(Proc) || keys[key].kind_of?(Method)
        elsif TkComm._callback_entry?(keys[key])
          keys[key] = klass.new(keys[key])
        end
      }
      keys
    end
__get_item_validate_key2class(id)

[Source]

# File tk/lib/tk/validation.rb, line 138
    def __get_item_validate_key2class(id)
      k2c = {}
      __item_validation_class_list(id).each{|klass|
        klass._config_keys.each{|key|
          k2c[key.to_s] = klass
        }
      }
    end
__item_validation_class_list(id)

[Source]

# File tk/lib/tk/validation.rb, line 133
    def __item_validation_class_list(id)
      # maybe need to override
      []
    end
__item_validcmd_call(tagOrId, klass, key, *args, &b)

[Source]

# File tk/lib/tk/validation.rb, line 119
    def __item_validcmd_call(tagOrId, klass, key, *args, &b)
      return itemcget(tagid(tagOrId), key) if args.empty? && !b

      cmd = (b)? proc(&b) : args.shift

      if cmd.kind_of?(klass)
        itemconfigure(tagid(tagOrId), key, cmd)
      elsif !args.empty?
        itemconfigure(tagid(tagOrId), key, [cmd, args])
      else
        itemconfigure(tagid(tagOrId), key, cmd)
      end
    end
itemconfigure(tagOrId, slot, value=TkComm::None)

[Source]

# File tk/lib/tk/validation.rb, line 163
    def itemconfigure(tagOrId, slot, value=TkComm::None)
      if slot.kind_of?(Hash)
        super(__conv_item_vcmd_on_hash_kv(slot))
      else
        super(__conv_item_vcmd_on_hash_kv(slot=>value))
      end
      self
    end


Module: Tk::Itk

Module | Tk::Itk
In: | tk/lib/tkextlib/itk/incr_tk.rb

Methods

package_name package_version usual usual_names

Included Modules

Tk

Classes and Modules

Class Tk::Itk::Archetype
Class Tk::Itk::Component
Class Tk::Itk::Toplevel
Class Tk::Itk::Widget

Constants

LIBRARY | = | TkVarAccess.new('::itk::library')
PACKAGE_NAME | = | 'Itk'.freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/itk/incr_tk.rb, line 24
    def self.package_name
      PACKAGE_NAME
    end
package_version()

[Source]

# File tk/lib/tkextlib/itk/incr_tk.rb, line 28
    def self.package_version
      begin
        TkPackage.require('Itk')
      rescue
        ''
      end
    end
usual(arg, *args)

[Source]

# File tk/lib/tkextlib/itk/incr_tk.rb, line 36
    def self.usual(arg, *args)
      tk_call('::itk::usual', arg, *args)
    end
usual_names()

[Source]

# File tk/lib/tkextlib/itk/incr_tk.rb, line 40
    def self.usual_names
      list(tk_call('::itk::usual'))
    end


Class: Tk::Itk::Archetype

Class | Tk::Itk::Archetype
In: | tk/lib/tkextlib/itk/incr_tk.rb
Parent: | TkWindow

Methods

__destroy_hook__ component component_invoke component_obj component_path component_widget to_eval

Constants

TkCommandNames = [].freeze

Public Class methods

to_eval()

WidgetClassName = ‘Archetype’.freeze WidgetClassNames[WidgetClassName] = self

[Source]

# File tk/lib/tkextlib/itk/incr_tk.rb, line 51
      def self.to_eval
        '::itk::' << self::WidgetClassName
      end

Public Instance methods

__destroy_hook__()

[Source]

# File tk/lib/tkextlib/itk/incr_tk.rb, line 55
      def __destroy_hook__
        Tk::Itk::Component::ComponentID_TBL.delete(self.path)
      end
component()
incr Tk
public methods

[Source]

# File tk/lib/tkextlib/itk/incr_tk.rb, line 60
      def component
        simplelist(tk_send('component'))
      end
component_invoke(name, cmd, *args)

[Source]

# File tk/lib/tkextlib/itk/incr_tk.rb, line 69
      def component_invoke(name, cmd, *args)
        window(tk_send('component', name, cmd, *args))
      end
component_obj(*names)

[Source]

# File tk/lib/tkextlib/itk/incr_tk.rb, line 73
      def component_obj(*names)
        names = component if names.empty?
        names.collect{|name| Tk::Itk::Component.new(self.path, name) }
      end
component_path(name)

[Source]

# File tk/lib/tkextlib/itk/incr_tk.rb, line 64
      def component_path(name)
        window(tk_send('component', name))
      end
component_widget(name)

Alias for component_path


Class: Tk::Itk::Component

Class | Tk::Itk::Component
In: | tk/lib/tkextlib/itk/incr_tk.rb
Parent: | TkObject

Methods

bind bind_append bind_remove bindinfo epath id2obj master method_missing name new new path tk_send tk_send_with_enc tk_send_without_enc to_eval widget widget_class

Constants

ComponentID_TBL | = | TkCore::INTERP.create_table
Itk_Component_ID | = | ['itk:component'.freeze, '00000'.taint].freeze

Public Class methods

id2obj(master, id)

[Source]

# File tk/lib/tkextlib/itk/incr_tk.rb, line 152
      def self.id2obj(master, id)
        if master.kind_of?(TkObject)
          master = master.path
        else
          master = master.to_s
        end
        return id unless ComponentID_TBL.key?(master)
        (ComponentID_TBL.key?(id))? ComponentID_TBL[master][id]: id
      end
new(master, component=nil)

[Source]

# File tk/lib/tkextlib/itk/incr_tk.rb, line 162
      def self.new(master, component=nil)
        if master.kind_of?(TkObject)
          master = master.path
        else
          master = master.to_s
        end

        if component.kind_of?(Tk::Itk::Component)
          component = component.name
        elsif component
          component = component.to_s
        else
          component = Itk_Component_ID.join(TkCore::INTERP._ip_id_)
          Itk_Component_ID[1].succ!
        end

        if ComponentID_TBL.key?(master)
          if ComponentID_TBL[master].key?(component)
            return ComponentID_TBL[master][component]
          end
        else
          ComponentID_TBL[master] = {}
        end

        super(master, component)
      end
new(master, component)

[Source]

# File tk/lib/tkextlib/itk/incr_tk.rb, line 189
      def initialize(master, component)
        @master = master
        @component = component

        ComponentID_TBL[@master][@component] = self

        begin
          @widget = window(tk_call(@master, 'component', @component))
          @path = @widget.path
        rescue
          @widget = nil
          @path = nil
        end
      end

Public Instance methods

bind(context, *args)

def bind(*args)

  unless @widget
    begin
      @widget = window(tk_call(@master, 'component', @component))
      @path = @widget.path
    rescue
      fail RuntimeError, 'component is not assigned to a widget'
    end
  end
  @widget.bind(*args)

end

[Source]

# File tk/lib/tkextlib/itk/incr_tk.rb, line 354
      def bind(context, *args)
        unless @widget
          begin
            @widget = window(tk_call(@master, 'component', @component))
            @path = @widget.path
          rescue
            fail RuntimeError, 'component is not assigned to a widget'
          end
        end
        # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
        if TkComm._callback_entry?(args[0]) || !block_given?
          cmd = args.shift
        else
          cmd = Proc.new
        end
        @widget.bind(context, cmd, *args)
      end
bind_append(context, *args)

def bind_append(*args)

  unless @widget
    begin
      @widget = window(tk_call(@master, 'component', @component))
      @path = @widget.path
    rescue
      fail RuntimeError, 'component is not assigned to a widget'
    end
  end
  @widget.bind_append(*args)

end

[Source]

# File tk/lib/tkextlib/itk/incr_tk.rb, line 383
      def bind_append(context, *args)
        unless @widget
          begin
            @widget = window(tk_call(@master, 'component', @component))
            @path = @widget.path
          rescue
            fail RuntimeError, 'component is not assigned to a widget'
          end
        end
        # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
        if TkComm._callback_entry?(args[0]) || !block_given?
          cmd = args.shift
        else
          cmd = Proc.new
        end
        @widget.bind_append(context, cmd, *args)
      end
bind_remove(*args)

[Source]

# File tk/lib/tkextlib/itk/incr_tk.rb, line 401
      def bind_remove(*args)
        unless @widget
          begin
            @widget = window(tk_call(@master, 'component', @component))
            @path = @widget.path
          rescue
            fail RuntimeError, 'component is not assigned to a widget'
          end
        end
        @widget.bind_remove(*args)
      end
bindinfo(*args)

[Source]

# File tk/lib/tkextlib/itk/incr_tk.rb, line 413
      def bindinfo(*args)
        unless @widget
          begin
            @widget = window(tk_call(@master, 'component', @component))
            @path = @widget.path
          rescue
            fail RuntimeError, 'component is not assigned to a widget'
          end
        end
        @widget.bindinfo(*args)
      end
epath()

[Source]

# File tk/lib/tkextlib/itk/incr_tk.rb, line 216
      def epath
        path()
      end
master()

[Source]

# File tk/lib/tkextlib/itk/incr_tk.rb, line 224
      def master
        @master
      end
method_missing(id, *args)

[Source]

# File tk/lib/tkextlib/itk/incr_tk.rb, line 256
      def method_missing(id, *args)
        name = id.id2name

        # try 1 : component command
        begin
          return tk_call(@master, 'component', @component, name, *args)
        rescue
        end

        # try 2 : component configure
        len = args.length
        begin
          case len
          when 1
            if name[-1] == ?=
              return configure(name[0..-2], args[0])
            else
              return configure(name, args[0])
            end
          when 0
            return cget(name)
          end
        rescue
        end

        # try 3 : widget method or widget configure
        begin
          unless @widget
            @widget = window(tk_call(@master, 'component', @component))
            @path = @widget.path
          end
          @widget.__send__(id, *args)
        rescue
        end

        # unknown method
        fail RuntimeError, "unknown method '#{name}' for #{self.inspect}"
      end
name()

[Source]

# File tk/lib/tkextlib/itk/incr_tk.rb, line 228
      def name
        @component
      end
path()

[Source]

# File tk/lib/tkextlib/itk/incr_tk.rb, line 204
      def path
        unless @path
          begin
            @widget = window(tk_call(@master, 'component', @component))
            @path = @widget.path
          rescue
            fail RuntimeError, 'component is not assigned to a widget'
          end
        end
        @path
      end
tk_send(cmd, *rest)

[Source]

# File tk/lib/tkextlib/itk/incr_tk.rb, line 295
      def tk_send(cmd, *rest)
        begin
          tk_call(@master, 'component', @component, cmd, *rest)
        rescue
          unless @path
            begin
              @widget = window(tk_call(@master, 'component', @component))
              @path = @widget.path
            rescue
              fail RuntimeError, 'component is not assigned to a widget'
            end
          end
          tk_call(@path, cmd, *rest)
        end
      end
tk_send_with_enc(cmd, *rest)

[Source]

# File tk/lib/tkextlib/itk/incr_tk.rb, line 327
      def tk_send_with_enc(cmd, *rest)
        begin
          tk_call_with_enc(@master, 'component', @component, cmd, *rest)
        rescue
          unless @path
            begin
              @widget = window(tk_call(@master, 'component', @component))
              @path = @widget.path
            rescue
              fail RuntimeError, 'component is not assigned to a widget'
            end
          end
          tk_call_with_enc(@path, cmd, *rest)
        end
      end
tk_send_without_enc(cmd, *rest)

[Source]

# File tk/lib/tkextlib/itk/incr_tk.rb, line 311
      def tk_send_without_enc(cmd, *rest)
        begin
          tk_call_without_enc(@master, 'component', @component, cmd, *rest)
        rescue
          unless @path
            begin
              @widget = window(tk_call(@master, 'component', @component))
              @path = @widget.path
            rescue
              fail RuntimeError, 'component is not assigned to a widget'
            end
          end
          tk_call_without_enc(@path, cmd, *rest)
        end
      end
to_eval()

[Source]

# File tk/lib/tkextlib/itk/incr_tk.rb, line 220
      def to_eval
        path()
      end
widget()

[Source]

# File tk/lib/tkextlib/itk/incr_tk.rb, line 232
      def widget
        unless @widget
          begin
            @widget = window(tk_call(@master, 'component', @component))
            @path = @widget.path
          rescue
            fail RuntimeError, 'component is not assigned to a widget'
          end
        end
        @widget
      end
widget_class()

[Source]

# File tk/lib/tkextlib/itk/incr_tk.rb, line 244
      def widget_class
        unless @widget
          begin
            @widget = window(tk_call(@master, 'component', @component))
            @path = @widget.path
            @widget.classname
          rescue
            nil
          end
        end
      end


Class: Tk::Itk::Toplevel

Class | Tk::Itk::Toplevel
In: | tk/lib/tkextlib/itk/incr_tk.rb
Parent: | Archetype

Included Modules

Wm TkMenuSpec

Constants

TkCommandNames | = | ['::itk::Toplevel'].freeze
WidgetClassName | = | 'Toplevel'.freeze


Class: Tk::Itk::Widget

Class | Tk::Itk::Widget
In: | tk/lib/tkextlib/itk/incr_tk.rb
Parent: | Archetype

Constants

TkCommandNames | = | ['::itk::Widget'].freeze
WidgetClassName | = | 'Widget'.freeze


Module: Tk::Iwidgets
In: tk/lib/tkextlib/iwidgets.rb
tk/lib/tkextlib/iwidgets/watch.rb
tk/lib/tkextlib/iwidgets/toolbar.rb
tk/lib/tkextlib/iwidgets/timefield.rb
tk/lib/tkextlib/iwidgets/timeentry.rb
tk/lib/tkextlib/iwidgets/tabset.rb
tk/lib/tkextlib/iwidgets/tabnotebook.rb
tk/lib/tkextlib/iwidgets/spintime.rb
tk/lib/tkextlib/iwidgets/spinner.rb
tk/lib/tkextlib/iwidgets/spinint.rb
tk/lib/tkextlib/iwidgets/spindate.rb
tk/lib/tkextlib/iwidgets/shell.rb
tk/lib/tkextlib/iwidgets/selectiondialog.rb
tk/lib/tkextlib/iwidgets/selectionbox.rb
tk/lib/tkextlib/iwidgets/scrolledwidget.rb
tk/lib/tkextlib/iwidgets/scrolledtext.rb
tk/lib/tkextlib/iwidgets/scrolledlistbox.rb
tk/lib/tkextlib/iwidgets/scrolledhtml.rb
tk/lib/tkextlib/iwidgets/scrolledframe.rb
tk/lib/tkextlib/iwidgets/scrolledcanvas.rb
tk/lib/tkextlib/iwidgets/scopedobject.rb
tk/lib/tkextlib/iwidgets/radiobox.rb
tk/lib/tkextlib/iwidgets/pushbutton.rb
tk/lib/tkextlib/iwidgets/promptdialog.rb
tk/lib/tkextlib/iwidgets/panedwindow.rb
tk/lib/tkextlib/iwidgets/optionmenu.rb
tk/lib/tkextlib/iwidgets/notebook.rb
tk/lib/tkextlib/iwidgets/messagedialog.rb
tk/lib/tkextlib/iwidgets/messagebox.rb
tk/lib/tkextlib/iwidgets/menubar.rb
tk/lib/tkextlib/iwidgets/mainwindow.rb
tk/lib/tkextlib/iwidgets/labeledwidget.rb
tk/lib/tkextlib/iwidgets/labeledframe.rb
tk/lib/tkextlib/iwidgets/hyperhelp.rb
tk/lib/tkextlib/iwidgets/hierarchy.rb
tk/lib/tkextlib/iwidgets/finddialog.rb
tk/lib/tkextlib/iwidgets/fileselectiondialog.rb
tk/lib/tkextlib/iwidgets/fileselectionbox.rb
tk/lib/tkextlib/iwidgets/feedback.rb
tk/lib/tkextlib/iwidgets/extfileselectiondialog.rb
tk/lib/tkextlib/iwidgets/extfileselectionbox.rb
tk/lib/tkextlib/iwidgets/extbutton.rb
tk/lib/tkextlib/iwidgets/entryfield.rb
tk/lib/tkextlib/iwidgets/disjointlistbox.rb
tk/lib/tkextlib/iwidgets/dialogshell.rb
tk/lib/tkextlib/iwidgets/dialog.rb
tk/lib/tkextlib/iwidgets/datefield.rb
tk/lib/tkextlib/iwidgets/dateentry.rb
tk/lib/tkextlib/iwidgets/combobox.rb
tk/lib/tkextlib/iwidgets/checkbox.rb
tk/lib/tkextlib/iwidgets/canvasprintdialog.rb
tk/lib/tkextlib/iwidgets/canvasprintbox.rb
tk/lib/tkextlib/iwidgets/calendar.rb
tk/lib/tkextlib/iwidgets/buttonbox.rb

Methods

package_name package_version

Classes and Modules

Class Tk::Iwidgets::Buttonbox
Class Tk::Iwidgets::Calendar
Class Tk::Iwidgets::Canvasprintbox
Class Tk::Iwidgets::Canvasprintdialog
Class Tk::Iwidgets::Checkbox
Class Tk::Iwidgets::Combobox
Class Tk::Iwidgets::Dateentry
Class Tk::Iwidgets::Datefield
Class Tk::Iwidgets::Dialog
Class Tk::Iwidgets::Dialogshell
Class Tk::Iwidgets::Disjointlistbox
Class Tk::Iwidgets::Entryfield
Class Tk::Iwidgets::Extbutton
Class Tk::Iwidgets::Extfileselectionbox
Class Tk::Iwidgets::Extfileselectiondialog
Class Tk::Iwidgets::Feedback
Class Tk::Iwidgets::Fileselectionbox
Class Tk::Iwidgets::Fileselectiondialog
Class Tk::Iwidgets::Finddialog
Class Tk::Iwidgets::Hierarchy
Class Tk::Iwidgets::Hyperhelp
Class Tk::Iwidgets::Labeledframe
Class Tk::Iwidgets::Labeledwidget
Class Tk::Iwidgets::Mainwindow
Class Tk::Iwidgets::Menubar
Class Tk::Iwidgets::Messagebox
Class Tk::Iwidgets::Messagedialog
Class Tk::Iwidgets::Notebook
Class Tk::Iwidgets::Optionmenu
Class Tk::Iwidgets::Panedwindow
Class Tk::Iwidgets::Promptdialog
Class Tk::Iwidgets::Pushbutton
Class Tk::Iwidgets::Radiobox
Class Tk::Iwidgets::Scopedobject
Class Tk::Iwidgets::Scrolledcanvas
Class Tk::Iwidgets::Scrolledframe
Class Tk::Iwidgets::Scrolledhtml
Class Tk::Iwidgets::Scrolledlistbox
Class Tk::Iwidgets::Scrolledtext
Class Tk::Iwidgets::Scrolledwidget
Class Tk::Iwidgets::Selectionbox
Class Tk::Iwidgets::Selectiondialog
Class Tk::Iwidgets::Shell
Class Tk::Iwidgets::Spindate
Class Tk::Iwidgets::Spinint
Class Tk::Iwidgets::Spinner
Class Tk::Iwidgets::Spintime
Class Tk::Iwidgets::Tabnotebook
Class Tk::Iwidgets::Tabset
Class Tk::Iwidgets::Timeentry
Class Tk::Iwidgets::Timefield
Class Tk::Iwidgets::Toolbar
Class Tk::Iwidgets::Watch

Constants

PACKAGE_NAME = 'Iwidgets'.freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/iwidgets.rb, line 27
    def self.package_name
      PACKAGE_NAME
    end
package_version()

[Source]

# File tk/lib/tkextlib/iwidgets.rb, line 31
    def self.package_version
      begin
        TkPackage.require('Iwidgets')
      rescue
        ''
      end
    end


Class: Tk::Iwidgets::Buttonbox

Class | Tk::Iwidgets::Buttonbox
In: | tk/lib/tkextlib/iwidgets/buttonbox.rb
Parent: | Tk::Itk::Widget

Methods

add default delete hide index insert invoke show tagid

Included Modules

TkItemConfigMethod

Constants

TkCommandNames | = | ['::iwidgets::buttonbox'.freeze].freeze
WidgetClassName | = | 'Buttonbox'.freeze

External Aliases

itemcget | -> | buttoncget
itemconfigure | -> | buttonconfigure
itemconfiginfo | -> | buttonconfiginfo
current_itemconfiginfo | -> | current_buttonconfiginfo

Public Instance methods

add(tag=nil, keys={})

[Source]

# File tk/lib/tkextlib/iwidgets/buttonbox.rb, line 59
  def add(tag=nil, keys={})
    if tag.kind_of?(Hash)
      keys = tag
      tag = nil
    end
    if tag
      tag = Tk::Itk::Component.new(self, tagid(tag))
    else
      tag = Tk::Itk::Component.new(self)
    end
    tk_call(@path, 'add', tagid(tag), *hash_kv(keys))
    tag
  end
default(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/buttonbox.rb, line 73
  def default(idx)
    tk_call(@path, 'default', index(idx))
    self
  end
delete(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/buttonbox.rb, line 78
  def delete(idx)
    tk_call(@path, 'delete', index(idx))
    self
  end
hide(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/buttonbox.rb, line 83
  def hide(idx)
    tk_call(@path, 'hide', index(idx))
    self
  end
index(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/buttonbox.rb, line 88
  def index(idx)
    number(tk_call(@path, 'index', tagid(idx)))
  end
insert(idx, tag=nil, keys={})

[Source]

# File tk/lib/tkextlib/iwidgets/buttonbox.rb, line 92
  def insert(idx, tag=nil, keys={})
    if tag.kind_of?(Hash)
      keys = tag
      tag = nil
    end
    if tag
      tag = Tk::Itk::Component.new(self, tagid(tag))
    else
      tag = Tk::Itk::Component.new(self)
    end
    tk_call(@path, 'insert', index(idx), tagid(tag), *hash_kv(keys))
    tag
  end
invoke(idx=nil)

[Source]

# File tk/lib/tkextlib/iwidgets/buttonbox.rb, line 106
  def invoke(idx=nil)
    if idx
      tk_call(@path, 'invoke', index(idx))
    else
      tk_call(@path, 'invoke')
    end
    self
  end
show(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/buttonbox.rb, line 115
  def show(idx)
    tk_call(@path, 'show', index(idx))
    self
  end
tagid(tagOrId)

[Source]

# File tk/lib/tkextlib/iwidgets/buttonbox.rb, line 40
  def tagid(tagOrId)
    if tagOrId.kind_of?(Tk::Itk::Component)
      tagOrId.name
    else
      #_get_eval_string(tagOrId)
      tagOrId
    end
  end


Class: Tk::Iwidgets::Calendar

Class | Tk::Iwidgets::Calendar
In: | tk/lib/tkextlib/iwidgets/calendar.rb
Parent: | Tk::Itk::Widget

Methods

__validation_class_list get get_clicks get_string select show show_now

Included Modules

Tk::ValidateConfigure

Classes and Modules

Class Tk::Iwidgets::Calendar::CalendarCommand

Constants

TkCommandNames | = | ['::iwidgets::calendar'.freeze].freeze
WidgetClassName | = | 'Calendar'.freeze

Public Instance methods

__validation_class_list()

[Source]

# File tk/lib/tkextlib/iwidgets/calendar.rb, line 65
  def __validation_class_list
    super() << CalendarCommand
  end
get()

Alias for get_string

get_clicks()

[Source]

# File tk/lib/tkextlib/iwidgets/calendar.rb, line 89
  def get_clicks
    number(tk_call(@path, 'get', '-clicks'))
  end
get_string()

[Source]

# File tk/lib/tkextlib/iwidgets/calendar.rb, line 84
  def get_string
    tk_call(@path, 'get', '-string')
  end
select(date)

[Source]

# File tk/lib/tkextlib/iwidgets/calendar.rb, line 93
  def select(date)
    tk_call(@path, 'select', date)
    self
  end
show(date)

[Source]

# File tk/lib/tkextlib/iwidgets/calendar.rb, line 98
  def show(date)
    tk_call(@path, 'show', date)
    self
  end
show_now()

[Source]

# File tk/lib/tkextlib/iwidgets/calendar.rb, line 102
  def show_now
    tk_call(@path, 'show', 'now')
    self
  end


Class: Tk::Iwidgets::Calendar::CalendarCommand

Class | Tk::Iwidgets::Calendar::CalendarCommand
In: | tk/lib/tkextlib/iwidgets/calendar.rb
Parent: | TkValidateCommand

Methods

_config_keys

Classes and Modules

Class Tk::Iwidgets::Calendar::CalendarCommand::ValidateArgs

Public Class methods

_config_keys()

[Source]

# File tk/lib/tkextlib/iwidgets/calendar.rb, line 55
    def self._config_keys
      # array of config-option key (string or symbol)
      ['command']
    end


Class: Tk::Iwidgets::Calendar::CalendarCommand::ValidateArgs

Class | Tk::Iwidgets::Calendar::CalendarCommand::ValidateArgs
In: | tk/lib/tkextlib/iwidgets/calendar.rb
Parent: | TkUtil::CallbackSubst

class CalCmdArgs < TkUtil::CallbackSubst

Methods

ret_val

Constants

KEY_TBL | = | [ [?d, ?s, :date], nil ]
PROC_TBL | = | [ [?s, TkComm.method(:string) ], nil ]

Public Class methods

ret_val(val)

[Source]

# File tk/lib/tkextlib/iwidgets/calendar.rb, line 50
      def self.ret_val(val)
        val
      end


Class: Tk::Iwidgets::Canvasprintbox

Class | Tk::Iwidgets::Canvasprintbox
In: | tk/lib/tkextlib/iwidgets/canvasprintbox.rb
Parent: | Tk::Itk::Widget

Methods

get_output print refresh set_canvas stop

Constants

TkCommandNames | = | ['::iwidgets::canvasprintbox'.freeze].freeze
WidgetClassName | = | 'Canvasprintbox'.freeze

Public Instance methods

get_output()

[Source]

# File tk/lib/tkextlib/iwidgets/canvasprintbox.rb, line 31
  def get_output
    tk_call(@path, 'getoutput')
  end
print()

[Source]

# File tk/lib/tkextlib/iwidgets/canvasprintbox.rb, line 35
  def print
    bool(tk_call(@path, 'print'))
  end
refresh()

[Source]

# File tk/lib/tkextlib/iwidgets/canvasprintbox.rb, line 39
  def refresh
    tk_call(@path, 'refresh')
    self
  end
set_canvas(win)

[Source]

# File tk/lib/tkextlib/iwidgets/canvasprintbox.rb, line 44
  def set_canvas(win)
    tk_call(@path, 'setcanvas', win)
    self
  end
stop()

[Source]

# File tk/lib/tkextlib/iwidgets/canvasprintbox.rb, line 49
  def stop
    tk_call(@path, 'stop')
    self
  end


Class: Tk::Iwidgets::Canvasprintdialog

Class | Tk::Iwidgets::Canvasprintdialog
In: | tk/lib/tkextlib/iwidgets/canvasprintdialog.rb
Parent: | Tk::Iwidgets::Dialog

Methods

get_output print refresh set_canvas

Constants

TkCommandNames | = | ['::iwidgets::canvasprintdialog'.freeze].freeze
WidgetClassName | = | 'Canvasprintdialog'.freeze

Public Instance methods

get_output()

[Source]

# File tk/lib/tkextlib/iwidgets/canvasprintdialog.rb, line 21
  def get_output
    tk_call(@path, 'getoutput')
  end
print()

[Source]

# File tk/lib/tkextlib/iwidgets/canvasprintdialog.rb, line 25
  def print
    bool(tk_call(@path, 'print'))
  end
refresh()

[Source]

# File tk/lib/tkextlib/iwidgets/canvasprintdialog.rb, line 29
  def refresh
    tk_call(@path, 'refresh')
    self
  end
set_canvas(win)

[Source]

# File tk/lib/tkextlib/iwidgets/canvasprintdialog.rb, line 34
  def set_canvas(win)
    tk_call(@path, 'setcanvas', win)
    self
  end


Class: Tk::Iwidgets::Checkbox

Class | Tk::Iwidgets::Checkbox
In: | tk/lib/tkextlib/iwidgets/checkbox.rb
Parent: | Tk::Iwidgets::Labeledframe

Methods

add delete deselect flash get index insert select tagid

Included Modules

TkItemConfigMethod

Constants

TkCommandNames | = | ['::iwidgets::checkbox'.freeze].freeze
WidgetClassName | = | 'Checkbox'.freeze

External Aliases

itemcget | -> | buttoncget
itemconfigure | -> | buttonconfigure
itemconfiginfo | -> | buttonconfiginfo
current_itemconfiginfo | -> | current_buttonconfiginfo

Public Instance methods

add(tag=nil, keys={})

[Source]

# File tk/lib/tkextlib/iwidgets/checkbox.rb, line 59
  def add(tag=nil, keys={})
    if tag.kind_of?(Hash)
      keys = tag
      tag = nil
    end
    if tag
      tag = Tk::Itk::Component.new(self, tagid(tag))
    else
      tag = Tk::Itk::Component.new(self)
    end
    tk_call(@path, 'add', tagid(tag), *hash_kv(keys))
    tag
  end
delete(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/checkbox.rb, line 73
  def delete(idx)
    tk_call(@path, 'delete', index(idx))
    self
  end
deselect(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/checkbox.rb, line 78
  def deselect(idx)
    tk_call(@path, 'deselect', index(idx))
    self
  end
flash(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/checkbox.rb, line 83
  def flash(idx)
    tk_call(@path, 'flash', index(idx))
    self
  end
get(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/checkbox.rb, line 88
  def get(idx)
    simplelist(tk_call(@path, 'get', index(idx))).collect{|id|
      Tk::Itk::Component.id2obj(id)
    }
  end
index(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/checkbox.rb, line 94
  def index(idx)
    number(tk_call(@path, 'index', tagid(idx)))
  end
insert(idx, tag=nil, keys={})

[Source]

# File tk/lib/tkextlib/iwidgets/checkbox.rb, line 98
  def insert(idx, tag=nil, keys={})
    if tag.kind_of?(Hash)
      keys = tag
      tag = nil
    end
    if tag
      tag = Tk::Itk::Component.new(self, tagid(tag))
    else
      tag = Tk::Itk::Component.new(self)
    end
    tk_call(@path, 'insert', index(idx), tagid(tag), *hash_kv(keys))
    tag
  end
select(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/checkbox.rb, line 112
  def select(idx)
    tk_call(@path, 'select', index(idx))
    self
  end
tagid(tagOrId)

[Source]

# File tk/lib/tkextlib/iwidgets/checkbox.rb, line 40
  def tagid(tagOrId)
    if tagOrId.kind_of?(Tk::Itk::Component)
      tagOrId.name
    else
      #_get_eval_string(tagOrId)
      tagOrId
    end
  end


Class: Tk::Iwidgets::Combobox

Class | Tk::Iwidgets::Combobox
In: | tk/lib/tkextlib/iwidgets/combobox.rb
Parent: | Tk::Iwidgets::Entryfield

Methods

clear delete_entry delete_list get_curselection get_list_contents insert_entry insert_list justify see selection_anchor selection_clear selection_includes selection_set size sort sort_ascending sort_descending

Constants

TkCommandNames | = | ['::iwidgets::combobox'.freeze].freeze
WidgetClassName | = | 'Combobox'.freeze

Public Instance methods

clear(component=None)

[Source]

# File tk/lib/tkextlib/iwidgets/combobox.rb, line 26
  def clear(component=None)
    tk_call(@path, 'clear', component)
    self
  end
delete_entry(first, last=None)

[Source]

# File tk/lib/tkextlib/iwidgets/combobox.rb, line 36
  def delete_entry(first, last=None)
    tk_call(@path, 'delete', 'entry', first, last)
    self
  end
delete_list(first, last=None)

[Source]

# File tk/lib/tkextlib/iwidgets/combobox.rb, line 31
  def delete_list(first, last=None)
    tk_call(@path, 'delete', 'list', first, last)
    self
  end
get_curselection()

scrolledlistbox methods

[Source]

# File tk/lib/tkextlib/iwidgets/combobox.rb, line 80
  def get_curselection
    tk_call(@path, 'getcurselection')
  end
get_list_contents(index)

[Source]

# File tk/lib/tkextlib/iwidgets/combobox.rb, line 41
  def get_list_contents(index)
    tk_call(@path, 'get', index)
  end
insert_entry(idx, *elems)

[Source]

# File tk/lib/tkextlib/iwidgets/combobox.rb, line 50
  def insert_entry(idx, *elems)
    tk_call(@path, 'insert', 'entry', idx, *elems)
    self
  end
insert_list(idx, *elems)

[Source]

# File tk/lib/tkextlib/iwidgets/combobox.rb, line 45
  def insert_list(idx, *elems)
    tk_call(@path, 'insert', 'list', idx, *elems)
    self
  end
justify(dir)

[Source]

# File tk/lib/tkextlib/iwidgets/combobox.rb, line 83
  def justify(dir)
    tk_call(@path, 'justify', dir)
    self
  end
see(index)

[Source]

# File tk/lib/tkextlib/iwidgets/combobox.rb, line 59
  def see(index)
    tk_send_without_enc('see', index)
    self
  end
selection_anchor(index)

[Source]

# File tk/lib/tkextlib/iwidgets/combobox.rb, line 63
  def selection_anchor(index)
    tk_send_without_enc('selection', 'anchor', index)
    self
  end
selection_clear(first, last=None)

[Source]

# File tk/lib/tkextlib/iwidgets/combobox.rb, line 67
  def selection_clear(first, last=None)
    tk_send_without_enc('selection', 'clear', first, last)
    self
  end
selection_includes(index)

[Source]

# File tk/lib/tkextlib/iwidgets/combobox.rb, line 71
  def selection_includes(index)
    bool(tk_send_without_enc('selection', 'includes', index))
  end
selection_set(first, last=None)

[Source]

# File tk/lib/tkextlib/iwidgets/combobox.rb, line 74
  def selection_set(first, last=None)
    tk_send_without_enc('selection', 'set', first, last)
    self
  end
size()

listbox methods

[Source]

# File tk/lib/tkextlib/iwidgets/combobox.rb, line 56
  def size
    tk_send_without_enc('size').to_i
  end
sort(*params, &b)

[Source]

# File tk/lib/tkextlib/iwidgets/combobox.rb, line 87
  def sort(*params, &b)
    # see 'lsort' man page about params
    if b
      tk_call(@path, 'sort', '-command', proc(&b), *params)
    else
      tk_call(@path, 'sort', *params)
    end
    self
  end
sort_ascending()

[Source]

# File tk/lib/tkextlib/iwidgets/combobox.rb, line 96
  def sort_ascending
    tk_call(@path, 'sort', 'ascending')
    self
  end
sort_descending()

[Source]

# File tk/lib/tkextlib/iwidgets/combobox.rb, line 100
  def sort_descending
    tk_call(@path, 'sort', 'descending')
    self
  end


Class: Tk::Iwidgets::Dateentry

Class | Tk::Iwidgets::Dateentry
In: | tk/lib/tkextlib/iwidgets/dateentry.rb
Parent: | Tk::Iwidgets::Datefield

Constants

TkCommandNames | = | ['::iwidgets::dateentry'.freeze].freeze
WidgetClassName | = | 'Dateentry'.freeze


Class: Tk::Iwidgets::Datefield

Class | Tk::Iwidgets::Datefield
In: | tk/lib/tkextlib/iwidgets/datefield.rb
Parent: | Tk::Iwidgets::Labeledwidget

Methods

get get_clicks get_string isvalid? show show_now valid?

Constants

TkCommandNames | = | ['::iwidgets::datefield'.freeze].freeze
WidgetClassName | = | 'Datefield'.freeze

Public Instance methods

get()

Alias for get_string

get_clicks()

[Source]

# File tk/lib/tkextlib/iwidgets/datefield.rb, line 41
  def get_clicks
    number(tk_call(@path, 'get', '-clicks'))
  end
get_string()

[Source]

# File tk/lib/tkextlib/iwidgets/datefield.rb, line 36
  def get_string
    tk_call(@path, 'get', '-string')
  end
isvalid?()

Alias for valid?

show(date=None)

[Source]

# File tk/lib/tkextlib/iwidgets/datefield.rb, line 50
  def show(date=None)
    tk_call(@path, 'show', date)
    self
  end
show_now()

[Source]

# File tk/lib/tkextlib/iwidgets/datefield.rb, line 54
  def show_now
    tk_call(@path, 'show', 'now')
    self
  end
valid?()

[Source]

# File tk/lib/tkextlib/iwidgets/datefield.rb, line 45
  def valid?
    bool(tk_call(@path, 'isvalid'))
  end


Class: Tk::Iwidgets::Dialog

Class | Tk::Iwidgets::Dialog
In: | tk/lib/tkextlib/iwidgets/dialog.rb
Parent: | Tk::Iwidgets::Dialogshell

Constants

TkCommandNames | = | ['::iwidgets::dialog'.freeze].freeze
WidgetClassName | = | 'Dialog'.freeze


Class: Tk::Iwidgets::Dialogshell

Class | Tk::Iwidgets::Dialogshell
In: | tk/lib/tkextlib/iwidgets/dialogshell.rb
Parent: | Tk::Iwidgets::Shell

Methods

add default delete hide index insert invoke show tagid

Included Modules

TkItemConfigMethod

Constants

TkCommandNames | = | ['::iwidgets::dialogshell'.freeze].freeze
WidgetClassName | = | 'Dialogshell'.freeze

External Aliases

itemcget | -> | buttoncget
itemconfigure | -> | buttonconfigure
itemconfiginfo | -> | buttonconfiginfo
current_itemconfiginfo | -> | current_buttonconfiginfo

Public Instance methods

add(tag=nil, keys={})

[Source]

# File tk/lib/tkextlib/iwidgets/dialogshell.rb, line 59
  def add(tag=nil, keys={})
    if tag.kind_of?(Hash)
      keys = tag
      tag = nil
    end
    if tag
      tag = Tk::Itk::Component.new(self, tagid(tag))
    else
      tag = Tk::Itk::Component.new(self)
    end
    tk_call(@path, 'add', tagid(tag), *hash_kv(keys))
    tag
  end
default(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/dialogshell.rb, line 73
  def default(idx)
    tk_call(@path, 'default', index(idx))
    self
  end
delete(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/dialogshell.rb, line 78
  def delete(idx)
    tk_call(@path, 'delete', index(idx))
    self
  end
hide(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/dialogshell.rb, line 83
  def hide(idx)
    tk_call(@path, 'hide', index(idx))
    self
  end
index(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/dialogshell.rb, line 88
  def index(idx)
    number(tk_call(@path, 'index', tagid(idx)))
  end
insert(idx, tag=nil, keys={})

[Source]

# File tk/lib/tkextlib/iwidgets/dialogshell.rb, line 92
  def insert(idx, tag=nil, keys={})
    if tag.kind_of?(Hash)
      keys = tag
      tag = nil
    end
    if tag
      tag = Tk::Itk::Component.new(self, tagid(tag))
    else
      tag = Tk::Itk::Component.new(self)
    end
    tk_call(@path, 'insert', index(idx), tagid(tag), *hash_kv(keys))
    tag
  end
invoke(idx=nil)

[Source]

# File tk/lib/tkextlib/iwidgets/dialogshell.rb, line 106
  def invoke(idx=nil)
    if idx
      tk_call(@path, 'invoke', index(idx))
    else
      tk_call(@path, 'invoke')
    end
    self
  end
show(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/dialogshell.rb, line 115
  def show(idx)
    tk_call(@path, 'show', index(idx))
    self
  end
tagid(tagOrId)

[Source]

# File tk/lib/tkextlib/iwidgets/dialogshell.rb, line 40
  def tagid(tagOrId)
    if tagOrId.kind_of?(Tk::Itk::Component)
      tagOrId.name
    else
      #_get_eval_string(tagOrId)
      tagOrId
    end
  end


Class: Tk::Iwidgets::Disjointlistbox

Class | Tk::Iwidgets::Disjointlistbox
In: | tk/lib/tkextlib/iwidgets/disjointlistbox.rb
Parent: | Tk::Itk::Widget

Methods

get_lhs get_rhs insert_lhs insert_rhs set_lhs set_rhs

Constants

TkCommandNames | = | ['::iwidgets::disjointlistbox'.freeze].freeze
WidgetClassName | = | 'Disjointlistbox'.freeze

Public Instance methods

get_lhs()

[Source]

# File tk/lib/tkextlib/iwidgets/disjointlistbox.rb, line 35
  def get_lhs
    simplelist(tk_call(@path, 'getlhs'))
  end
get_rhs()

[Source]

# File tk/lib/tkextlib/iwidgets/disjointlistbox.rb, line 38
  def get_rhs
    simplelist(tk_call(@path, 'getrhs'))
  end
insert_lhs(*items)

[Source]

# File tk/lib/tkextlib/iwidgets/disjointlistbox.rb, line 42
  def insert_lhs(*items)
    tk_call(@path, 'insertlhs', items)
    self
  end
insert_rhs(*items)

[Source]

# File tk/lib/tkextlib/iwidgets/disjointlistbox.rb, line 46
  def insert_rhs(*items)
    tk_call(@path, 'insertrhs', items)
    self
  end
set_lhs(*items)

[Source]

# File tk/lib/tkextlib/iwidgets/disjointlistbox.rb, line 26
  def set_lhs(*items)
    tk_call(@path, 'setlhs', items)
    self
  end
set_rhs(*items)

[Source]

# File tk/lib/tkextlib/iwidgets/disjointlistbox.rb, line 30
  def set_rhs(*items)
    tk_call(@path, 'setrhs', items)
    self
  end


Class: Tk::Iwidgets::Entryfield

Class | Tk::Iwidgets::Entryfield
In: | tk/lib/tkextlib/iwidgets/entryfield.rb
Parent: | Tk::Iwidgets::Labeledwidget

Methods

__validation_class_list clear cursor= delete dragto get icursor index insert mark selection_adjust selection_clear selection_from selection_present selection_range selection_to set value value= xview xview_moveto xview_scroll

Included Modules

Tk::ValidateConfigure

Classes and Modules

Class Tk::Iwidgets::Entryfield::EntryfieldValidate

Constants

TkCommandNames | = | ['::iwidgets::entryfield'.freeze].freeze
WidgetClassName | = | 'Entryfield'.freeze

Public Instance methods

__validation_class_list()

[Source]

# File tk/lib/tkextlib/iwidgets/entryfield.rb, line 53
  def __validation_class_list
    super() << EntryfieldValidate
  end
clear()

[Source]

# File tk/lib/tkextlib/iwidgets/entryfield.rb, line 82
  def clear
    tk_call(@path, 'clear')
    self
  end
cursor=(index)

[Source]

# File tk/lib/tkextlib/iwidgets/entryfield.rb, line 103
  def cursor=(index)
    tk_send_without_enc('icursor', index)
    #self
    index
  end
delete(first, last=None)

[Source]

# File tk/lib/tkextlib/iwidgets/entryfield.rb, line 87
  def delete(first, last=None)
    tk_send_without_enc('delete', first, last)
    self
  end
dragto(pos)

[Source]

# File tk/lib/tkextlib/iwidgets/entryfield.rb, line 123
  def dragto(pos)
    tk_send_without_enc('scan', 'dragto', pos)
    self
  end
get()

Alias for value

icursor(index)

Alias for cursor=

index(index)

[Source]

# File tk/lib/tkextlib/iwidgets/entryfield.rb, line 110
  def index(index)
    number(tk_send_without_enc('index', index))
  end
insert(pos,text)

[Source]

# File tk/lib/tkextlib/iwidgets/entryfield.rb, line 114
  def insert(pos,text)
    tk_send_without_enc('insert', pos, _get_eval_enc_str(text))
    self
  end
mark(pos)

[Source]

# File tk/lib/tkextlib/iwidgets/entryfield.rb, line 119
  def mark(pos)
    tk_send_without_enc('scan', 'mark', pos)
    self
  end
selection_adjust(index)

[Source]

# File tk/lib/tkextlib/iwidgets/entryfield.rb, line 127
  def selection_adjust(index)
    tk_send_without_enc('selection', 'adjust', index)
    self
  end
selection_clear()

[Source]

# File tk/lib/tkextlib/iwidgets/entryfield.rb, line 131
  def selection_clear
    tk_send_without_enc('selection', 'clear')
    self
  end
selection_from(index)

[Source]

# File tk/lib/tkextlib/iwidgets/entryfield.rb, line 135
  def selection_from(index)
    tk_send_without_enc('selection', 'from', index)
    self
  end
selection_present()

[Source]

# File tk/lib/tkextlib/iwidgets/entryfield.rb, line 139
  def selection_present()
    bool(tk_send_without_enc('selection', 'present'))
  end
selection_range(s, e)

[Source]

# File tk/lib/tkextlib/iwidgets/entryfield.rb, line 142
  def selection_range(s, e)
    tk_send_without_enc('selection', 'range', s, e)
    self
  end
selection_to(index)

[Source]

# File tk/lib/tkextlib/iwidgets/entryfield.rb, line 146
  def selection_to(index)
    tk_send_without_enc('selection', 'to', index)
    self
  end
set(val)

Alias for value=

value()

[Source]

# File tk/lib/tkextlib/iwidgets/entryfield.rb, line 92
  def value
    _fromUTF8(tk_send_without_enc('get'))
  end
value=(val)

[Source]

# File tk/lib/tkextlib/iwidgets/entryfield.rb, line 95
  def value= (val)
    tk_send_without_enc('delete', 0, 'end')
    tk_send_without_enc('insert', 0, _get_eval_enc_str(val))
    val
  end
xview(*index)

based on tk/scrollable.rb

[Source]

# File tk/lib/tkextlib/iwidgets/entryfield.rb, line 152
  def xview(*index)
    if index.size == 0
      list(tk_send_without_enc('xview'))
    else
      tk_send_without_enc('xview', *index)
      self
    end
  end
xview_moveto(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/entryfield.rb, line 160
  def xview_moveto(*index)
    xview('moveto', *index)
  end
xview_scroll(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/entryfield.rb, line 163
  def xview_scroll(*index)
    xview('scroll', *index)
  end


Class: Tk::Iwidgets::Entryfield::EntryfieldValidate

Class | Tk::Iwidgets::Entryfield::EntryfieldValidate
In: | tk/lib/tkextlib/iwidgets/entryfield.rb
Parent: | TkValidateCommand

Methods

_config_keys

Classes and Modules

Class Tk::Iwidgets::Entryfield::EntryfieldValidate::ValidateArgs

Public Class methods

_config_keys()

[Source]

# File tk/lib/tkextlib/iwidgets/entryfield.rb, line 48
    def self._config_keys
      ['validate', 'invalid']
    end


Class: Tk::Iwidgets::Entryfield::EntryfieldValidate::ValidateArgs

Class | Tk::Iwidgets::Entryfield::EntryfieldValidate::ValidateArgs
In: | tk/lib/tkextlib/iwidgets/entryfield.rb
Parent: | TkUtil::CallbackSubst

class CalCmdArgs < TkUtil::CallbackSubst

Constants

KEY_TBL | = | [ [ ?c, ?s, :char ], [ ?P, ?s, :post ], [ ?S, ?s, :current ], [ ?W, ?w, :widget ], nil
PROC_TBL | = | [ [ ?s, TkComm.method(:string) ], [ ?w, TkComm.method(:window) ], nil


Class: Tk::Iwidgets::Extbutton

Class | Tk::Iwidgets::Extbutton
In: | tk/lib/tkextlib/iwidgets/extbutton.rb
Parent: | Tk::Itk::Widget

Methods

flash invoke

Constants

TkCommandNames | = | ['::iwidgets::extbutton'.freeze].freeze
WidgetClassName | = | 'Extbutton'.freeze

Public Instance methods

flash()

[Source]

# File tk/lib/tkextlib/iwidgets/extbutton.rb, line 36
  def flash
    tk_call(@path, 'flash')
    self
  end
invoke()

[Source]

# File tk/lib/tkextlib/iwidgets/extbutton.rb, line 31
  def invoke
    tk_call(@path, 'invoke')
    self
  end


Class: Tk::Iwidgets::Extfileselectionbox

Class | Tk::Iwidgets::Extfileselectionbox
In: | tk/lib/tkextlib/iwidgets/extfileselectionbox.rb
Parent: | Tk::Itk::Widget

Methods

child_site filter get

Constants

TkCommandNames | = | ['::iwidgets::extfileselectionbox'.freeze].freeze
WidgetClassName | = | 'Extfileselectionbox'.freeze

Public Instance methods

child_site()

[Source]

# File tk/lib/tkextlib/iwidgets/extfileselectionbox.rb, line 34
  def child_site
    window(tk_call(@path, 'childsite'))
  end
filter()

[Source]

# File tk/lib/tkextlib/iwidgets/extfileselectionbox.rb, line 38
  def filter
    tk_call(@path, 'filter')
    self
  end
get()

[Source]

# File tk/lib/tkextlib/iwidgets/extfileselectionbox.rb, line 43
  def get
    tk_call(@path, 'get')
  end


Class: Tk::Iwidgets::Extfileselectiondialog

Class | Tk::Iwidgets::Extfileselectiondialog
In: | tk/lib/tkextlib/iwidgets/extfileselectiondialog.rb
Parent: | Tk::Iwidgets::Dialog

Methods

child_site filter get

Constants

TkCommandNames | = | ['::iwidgets::extfileselectiondialog'.freeze].freeze
WidgetClassName | = | 'Extfileselectiondialog'.freeze

Public Instance methods

child_site()

[Source]

# File tk/lib/tkextlib/iwidgets/extfileselectiondialog.rb, line 21
  def child_site
    window(tk_call(@path, 'childsite'))
  end
filter()

[Source]

# File tk/lib/tkextlib/iwidgets/extfileselectiondialog.rb, line 25
  def filter
    tk_call(@path, 'filter')
    self
  end
get()

[Source]

# File tk/lib/tkextlib/iwidgets/extfileselectiondialog.rb, line 30
  def get
    tk_call(@path, 'get')
  end


Class: Tk::Iwidgets::Feedback

Class | Tk::Iwidgets::Feedback
In: | tk/lib/tkextlib/iwidgets/feedback.rb
Parent: | Tk::Iwidgets::Labeledwidget

Methods

reset step

Constants

TkCommandNames | = | ['::iwidgets::feedback'.freeze].freeze
WidgetClassName | = | 'Feedback'.freeze

Public Instance methods

reset()

[Source]

# File tk/lib/tkextlib/iwidgets/feedback.rb, line 26
  def reset
    tk_call(@path, 'reset')
    self
  end
step(inc=1)

[Source]

# File tk/lib/tkextlib/iwidgets/feedback.rb, line 31
  def step(inc=1)
    tk_call(@path, 'step', inc)
    self
  end


Class: Tk::Iwidgets::Fileselectionbox

Class | Tk::Iwidgets::Fileselectionbox
In: | tk/lib/tkextlib/iwidgets/fileselectionbox.rb
Parent: | Tk::Itk::Widget

Methods

child_site filter get

Constants

TkCommandNames | = | ['::iwidgets::fileselectionbox'.freeze].freeze
WidgetClassName | = | 'Fileselectionbox'.freeze

Public Instance methods

child_site()

[Source]

# File tk/lib/tkextlib/iwidgets/fileselectionbox.rb, line 34
  def child_site
    window(tk_call(@path, 'childsite'))
  end
filter()

[Source]

# File tk/lib/tkextlib/iwidgets/fileselectionbox.rb, line 38
  def filter
    tk_call(@path, 'filter')
    self
  end
get()

[Source]

# File tk/lib/tkextlib/iwidgets/fileselectionbox.rb, line 43
  def get
    tk_call(@path, 'get')
  end


Class: Tk::Iwidgets::Fileselectiondialog

Class | Tk::Iwidgets::Fileselectiondialog
In: | tk/lib/tkextlib/iwidgets/fileselectiondialog.rb
Parent: | Tk::Iwidgets::Dialog

Methods

child_site filter get

Constants

TkCommandNames | = | ['::iwidgets::fileselectiondialog'.freeze].freeze
WidgetClassName | = | 'Fileselectiondialog'.freeze

Public Instance methods

child_site()

[Source]

# File tk/lib/tkextlib/iwidgets/fileselectiondialog.rb, line 21
  def child_site
    window(tk_call(@path, 'childsite'))
  end
filter()

[Source]

# File tk/lib/tkextlib/iwidgets/fileselectiondialog.rb, line 25
  def filter
    tk_call(@path, 'filter')
    self
  end
get()

[Source]

# File tk/lib/tkextlib/iwidgets/fileselectiondialog.rb, line 30
  def get
    tk_call(@path, 'get')
  end


Class: Tk::Iwidgets::Finddialog

Class | Tk::Iwidgets::Finddialog
In: | tk/lib/tkextlib/iwidgets/finddialog.rb
Parent: | Tk::Iwidgets::Dialogshell

Methods

clear find

Constants

TkCommandNames | = | ['::iwidgets::finddialog'.freeze].freeze
WidgetClassName | = | 'Finddialog'.freeze

Public Instance methods

clear()

[Source]

# File tk/lib/tkextlib/iwidgets/finddialog.rb, line 34
  def clear
    tk_call(@path, 'clear')
    self
  end
find()

[Source]

# File tk/lib/tkextlib/iwidgets/finddialog.rb, line 39
  def find
    tk_call(@path, 'find')
  end


Class: Tk::Iwidgets::Hierarchy

Class | Tk::Iwidgets::Hierarchy
In: | tk/lib/tkextlib/iwidgets/hierarchy.rb
Parent: | Tk::Iwidgets::Scrolledwidget

Methods

__validation_class_list bbox clear collapse compare current debug debug= delete dlineinfo draw exp_state expand expand_state expanded? expanded_list get index insert mark_add mark_clear mark_get mark_remove prune refresh scan_dragto scan_mark see selection_add selection_clear selection_get selection_remove toggle xview xview_moveto xview_scroll yview yview_moveto yview_scroll

Included Modules

TkTextTagConfig Tk::ValidateConfigure

Classes and Modules

Class Tk::Iwidgets::Hierarchy::IconCommand
Class Tk::Iwidgets::Hierarchy::IndicatorCommand
Class Tk::Iwidgets::Hierarchy::QueryCommand

Constants

ItemConfCMD | = | ['tag'.freeze, 'configure'.freeze].freeze
TkCommandNames | = | ['::iwidgets::hierarchy'.freeze].freeze
WidgetClassName | = | 'Hierarchy'.freeze

Public Instance methods

__validation_class_list()

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 94
  def __validation_class_list
    super() << QueryCommand << IndicatorCommand << IconCommand
  end
bbox(index)

based on TkText widget

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 212
  def bbox(index)
    list(tk_send_without_enc('bbox', _get_eval_enc_str(index)))
  end
clear()

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 119
  def clear
    tk_call(@path, 'clear')
    self
  end
collapse(node)

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 124
  def collapse(node)
    tk_call(@path, 'collapse')
    self
  end
compare(idx1, op, idx2)

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 216
  def compare(idx1, op, idx2)
    bool(tk_send_without_enc('compare', _get_eval_enc_str(idx1),
                             op, _get_eval_enc_str(idx2)))
  end
current()

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 129
  def current
    tk_call(@path, 'current')
  end
debug()

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 221
  def debug
    bool(tk_send_without_enc('debug'))
  end
debug=(boolean)

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 224
  def debug=(boolean)
    tk_send_without_enc('debug', boolean)
    #self
    boolean
  end
delete(first, last=None)

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 230
  def delete(first, last=None)
    tk_send_without_enc('delete', first, last)
    self
  end
dlineinfo(index)

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 235
  def dlineinfo(index)
    list(tk_send_without_enc('dlineinfo', _get_eval_enc_str(index)))
  end
draw(mode=None)

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 133
  def draw(mode=None)
    case mode
    when None
      # do nothing
    when 'now', :now
      mode = '-now'
    when 'eventually', :eventually
      mode = '-eventually'
    when String, Symbol
      mode = mode.to_s
      mode = '-' << mode if mode[0] != ?-
    end
    tk_call(@path, 'draw', mode)
  end
exp_state()

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 157
  def exp_state
    list(tk_call(@path, 'expState'))
  end
expand(node)

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 148
  def expand(node)
    tk_call(@path, 'expand', node)
    self
  end
expand_state()

Alias for exp_state

expanded?(node)

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 153
  def expanded?(node)
    bool(tk_call(@path, 'expanded', node))
  end
expanded_list()

Alias for exp_state

get(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 239
  def get(*index)
    _fromUTF8(tk_send_without_enc('get', *index))
  end
index(index)

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 243
  def index(index)
    tk_send_without_enc('index', _get_eval_enc_str(index))
  end
insert(index, chars, *tags)

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 247
  def insert(index, chars, *tags)
    if tags[0].kind_of? Array
      # multiple chars-taglist argument :: str, [tag,...], str, [tag,...], ...
      args = [chars]
      while tags.size > 0
        args << tags.shift.collect{|x|_get_eval_string(x)}.join(' ')  # taglist
        args << tags.shift if tags.size > 0                           # chars
      end
      super(index, *args)
    else
      # single chars-taglist argument :: str, tag, tag, ...
      if tags.size == 0
        super(index, chars)
      else
        super(index, chars, tags.collect{|x|_get_eval_string(x)}.join(' '))
      end
    end
  end
mark_add(*nodes)

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 167
  def mark_add(*nodes)
    tk_call(@path, 'mark', 'add', *nodes)
    self
  end
mark_clear()

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 163
  def mark_clear
    tk_call(@path, 'mark', 'clear')
    self
  end
mark_get()

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 175
  def mark_get
    list(tk_call(@path, 'mark', 'get'))
  end
mark_remove(*nodes)

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 171
  def mark_remove(*nodes)
    tk_call(@path, 'mark', 'remove', *nodes)
    self
  end
prune(node)

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 184
  def prune(node)
    tk_call(@path, 'prune', node)
    self
  end
refresh(node)

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 179
  def refresh(node)
    tk_call(@path, 'refresh', node)
    self
  end
scan_dragto(x, y)

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 270
  def scan_dragto(x, y)
    tk_send_without_enc('scan', 'dragto', x, y)
    self
  end
scan_mark(x, y)

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 266
  def scan_mark(x, y)
    tk_send_without_enc('scan', 'mark', x, y)
    self
  end
see(index)

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 274
  def see(index)
    tk_send_without_enc('see', index)
    self
  end
selection_add(*nodes)

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 193
  def selection_add(*nodes)
    tk_call(@path, 'selection', 'add', *nodes)
    self
  end
selection_clear()

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 189
  def selection_clear
    tk_call(@path, 'selection', 'clear')
    self
  end
selection_get()

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 201
  def selection_get
    list(tk_call(@path, 'selection', 'get'))
  end
selection_remove(*nodes)

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 197
  def selection_remove(*nodes)
    tk_call(@path, 'selection', 'remove', *nodes)
    self
  end
toggle(node)

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 205
  def toggle(node)
    tk_call(@path, 'toggle', node)
    self
  end
xview(*index)

based on tk/scrollable.rb

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 280
  def xview(*index)
    if index.size == 0
      list(tk_send_without_enc('xview'))
    else
      tk_send_without_enc('xview', *index)
      self
    end
  end
xview_moveto(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 288
  def xview_moveto(*index)
    xview('moveto', *index)
  end
xview_scroll(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 291
  def xview_scroll(*index)
    xview('scroll', *index)
  end
yview(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 295
  def yview(*index)
    if index.size == 0
      list(tk_send_without_enc('yview'))
    else
      tk_send_without_enc('yview', *index)
      self
    end
  end
yview_moveto(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 303
  def yview_moveto(*index)
    yview('moveto', *index)
  end
yview_scroll(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 306
  def yview_scroll(*index)
    yview('scroll', *index)
  end


Class: Tk::Iwidgets::Hierarchy::IconCommand

Class | Tk::Iwidgets::Hierarchy::IconCommand
In: | tk/lib/tkextlib/iwidgets/hierarchy.rb
Parent: | TkValidateCommand

Methods

_config_keys

Classes and Modules

Class Tk::Iwidgets::Hierarchy::IconCommand::ValidateArgs

Public Class methods

_config_keys()

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 88
    def self._config_keys
      # array of config-option key (string or symbol)
      ['dblclickcommand', 'imagecommand', 'selectcommand']
    end


Class: Tk::Iwidgets::Hierarchy::IconCommand::ValidateArgs

Class | Tk::Iwidgets::Hierarchy::IconCommand::ValidateArgs
In: | tk/lib/tkextlib/iwidgets/hierarchy.rb
Parent: | TkUtil::CallbackSubst

Methods

ret_val

Constants

KEY_TBL | = | [ [ ?n, ?s, :node ], [ ?i, ?s, :icon ], nil
PROC_TBL | = | [ [ ?s, TkComm.method(:string) ], nil ]

Public Class methods

ret_val(val)

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 83
      def self.ret_val(val)
        val
      end


Class: Tk::Iwidgets::Hierarchy::IndicatorCommand

Class | Tk::Iwidgets::Hierarchy::IndicatorCommand
In: | tk/lib/tkextlib/iwidgets/hierarchy.rb
Parent: | TkValidateCommand

Methods

_config_keys

Classes and Modules

Class Tk::Iwidgets::Hierarchy::IndicatorCommand::ValidateArgs

Public Class methods

_config_keys()

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 67
    def self._config_keys
      # array of config-option key (string or symbol)
      ['iconcommand', 'icondblcommand', 'imagedblcommand']
    end


Class: Tk::Iwidgets::Hierarchy::IndicatorCommand::ValidateArgs

Class | Tk::Iwidgets::Hierarchy::IndicatorCommand::ValidateArgs
In: | tk/lib/tkextlib/iwidgets/hierarchy.rb
Parent: | TkUtil::CallbackSubst

Methods

ret_val

Constants

KEY_TBL | = | [ [ ?n, ?s, :node ], [ ?s, ?b, :status ], nil
PROC_TBL | = | [ [ ?s, TkComm.method(:string) ], [ ?b, TkComm.method(:bool) ], nil

Public Class methods

ret_val(val)

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 62
      def self.ret_val(val)
        val
      end


Class: Tk::Iwidgets::Hierarchy::QueryCommand

Class | Tk::Iwidgets::Hierarchy::QueryCommand
In: | tk/lib/tkextlib/iwidgets/hierarchy.rb
Parent: | TkValidateCommand

Methods

_config_keys

Classes and Modules

Class Tk::Iwidgets::Hierarchy::QueryCommand::ValidateArgs

Public Class methods

_config_keys()

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 40
    def self._config_keys
      # array of config-option key (string or symbol)
      ['querycommand']
    end


Class: Tk::Iwidgets::Hierarchy::QueryCommand::ValidateArgs

Class | Tk::Iwidgets::Hierarchy::QueryCommand::ValidateArgs
In: | tk/lib/tkextlib/iwidgets/hierarchy.rb
Parent: | TkUtil::CallbackSubst

Methods

ret_val

Constants

KEY_TBL | = | [ [?n, ?s, :node], nil ]
PROC_TBL | = | [ [?s, TkComm.method(:string) ], nil ]

Public Class methods

ret_val(val)

[Source]

# File tk/lib/tkextlib/iwidgets/hierarchy.rb, line 35
      def self.ret_val(val)
        val
      end


Class: Tk::Iwidgets::Hyperhelp

Class | Tk::Iwidgets::Hyperhelp
In: | tk/lib/tkextlib/iwidgets/hyperhelp.rb
Parent: | Tk::Iwidgets::Shell

Methods

back follow_link forward show_topic

Constants

TkCommandNames | = | ['::iwidgets::hyperhelp'.freeze].freeze
WidgetClassName | = | 'Hyperhelp'.freeze

Public Instance methods

back()

[Source]

# File tk/lib/tkextlib/iwidgets/hyperhelp.rb, line 46
  def back
    tk_call(@path, 'back')
    self
  end
follow_link(href)

[Source]

# File tk/lib/tkextlib/iwidgets/hyperhelp.rb, line 36
  def follow_link(href)
    tk_call(@path, 'followlink', href)
    self
  end
forward()

[Source]

# File tk/lib/tkextlib/iwidgets/hyperhelp.rb, line 41
  def forward
    tk_call(@path, 'forward')
    self
  end
show_topic(topic)

[Source]

# File tk/lib/tkextlib/iwidgets/hyperhelp.rb, line 31
  def show_topic(topic)
    tk_call(@path, 'showtopic', topic)
    self
  end


Class: Tk::Iwidgets::Labeledframe

Class | Tk::Iwidgets::Labeledframe
In: | tk/lib/tkextlib/iwidgets/labeledframe.rb
Parent: | Tk::Itk::Archetype

Methods

child_site

Constants

TkCommandNames | = | ['::iwidgets::labeledframe'.freeze].freeze
WidgetClassName | = | 'Labeledframe'.freeze

Public Instance methods

child_site()

[Source]

# File tk/lib/tkextlib/iwidgets/labeledframe.rb, line 36
  def child_site
    window(tk_call(@path, 'childsite'))
  end


Class: Tk::Iwidgets::Labeledwidget

Class | Tk::Iwidgets::Labeledwidget
In: | tk/lib/tkextlib/iwidgets/labeledwidget.rb
Parent: | Tk::Itk::Widget

Methods

alignlabels child_site

Constants

TkCommandNames | = | ['::iwidgets::labeledwidget'.freeze].freeze
WidgetClassName | = | 'Labeledwidget'.freeze

Public Class methods

alignlabels(*wins)

[Source]

# File tk/lib/tkextlib/iwidgets/labeledwidget.rb, line 38
  def self.alignlabels(*wins)
    tk_call('::iwidgets::Labeledwidget::alignlabels', *wins)
  end

Public Instance methods

child_site()

[Source]

# File tk/lib/tkextlib/iwidgets/labeledwidget.rb, line 42
  def child_site
    window(tk_call(@path, 'childsite'))
  end


Class: Tk::Iwidgets::Mainwindow

Class | Tk::Iwidgets::Mainwindow
In: | tk/lib/tkextlib/iwidgets/mainwindow.rb
Parent: | Tk::Iwidgets::Shell

Methods

child_site menubar mousebar msgd toolbar

Constants

TkCommandNames | = | ['::iwidgets::mainwindow'.freeze].freeze
WidgetClassName | = | 'Mainwindow'.freeze

Public Instance methods

child_site()

[Source]

# File tk/lib/tkextlib/iwidgets/mainwindow.rb, line 36
  def child_site
    window(tk_call(@path, 'childsite'))
  end
menubar(*args)

[Source]

# File tk/lib/tkextlib/iwidgets/mainwindow.rb, line 40
  def menubar(*args)
    unless args.empty?
      tk_call(@path, 'menubar', *args)
    end
    window(tk_call(@path, 'menubar'))
  end
mousebar(*args)

[Source]

# File tk/lib/tkextlib/iwidgets/mainwindow.rb, line 47
  def mousebar(*args)
    unless args.empty?
      tk_call(@path, 'mousebar', *args)
    end
    window(tk_call(@path, 'mousebar'))
  end
msgd(*args)

[Source]

# File tk/lib/tkextlib/iwidgets/mainwindow.rb, line 54
  def msgd(*args)
    unless args.empty?
      tk_call(@path, 'msgd', *args)
    end
    window(tk_call(@path, 'msgd'))
  end
toolbar(*args)

[Source]

# File tk/lib/tkextlib/iwidgets/mainwindow.rb, line 61
  def toolbar(*args)
    unless args.empty?
      tk_call(@path, 'toolbar', *args)
    end
    window(tk_call(@path, 'toolbar'))
  end


Class: Tk::Iwidgets::Menubar

Class | Tk::Iwidgets::Menubar
In: | tk/lib/tkextlib/iwidgets/menubar.rb
Parent: | Tk::Itk::Widget

Methods

__methodcall_optkeys _parse_menu_spec add delete index insert invoke menubuttons menupath menupath_glob menupath_tclregexp tagid type yposition

Included Modules

TkItemConfigMethod

Constants

TkCommandNames | = | ['::iwidgets::menubar'.freeze].freeze
WidgetClassName | = | 'Menubar'.freeze

External Aliases

itemcget | -> | menucget
itemconfigure | -> | menuconfigure
itemconfiginfo | -> | menuconfiginfo
current_itemconfiginfo | -> | current_menuconfiginfo

Public Instance methods

__methodcall_optkeys()

[Source]

# File tk/lib/tkextlib/iwidgets/menubar.rb, line 74
  def __methodcall_optkeys
    {'menubuttons'=>'menubuttons'}
  end
_parse_menu_spec(menu_spec)

[Source]

# File tk/lib/tkextlib/iwidgets/menubar.rb, line 87
  def _parse_menu_spec(menu_spec)
    ret = ''
    menu_spec.each{|spec|
      next unless spec

      if spec.kind_of?(Hash)
        args = [spec]
        type = 'options'
      else
        type, *args = spec
      end

      type = type.to_s
      case type
      when 'options'
        keys = args[0]
        ary = [type]
        ary.concat(hash_kv(keys))
        ret << array2tk_list(ary) << "\n"

      when 'menubutton', 'cascade'
        name, keys = args
        if keys
          ary = [type, name]
          keys = _symbolkey2str(keys)
          keys['menu'] = _parse_menu_spec(keys['menu']) if keys.key?('menu')
          ary.concat(hash_kv(keys))
          ret << array2tk_list(ary) << "\n"
        else
          ret << array2tk_list([type, name]) << "\n"
        end

      else
        name, keys = args
        if keys
          ary = [type, name]
          ary.concat(hash_kv(keys))
          ret << array2tk_list(ary) << "\n"
        else
          ret << array2tk_list([type, name]) << "\n"
        end
      end
    }
    ret
  end
add(type, tag=nil, keys={})

[Source]

# File tk/lib/tkextlib/iwidgets/menubar.rb, line 135
  def add(type, tag=nil, keys={})
    if tag.kind_of?(Hash)
      keys = tag
      tag = nil
    end
    if tag
      tag = Tk::Itk::Component.new(self, tagid(tag))
    else
      tag = Tk::Itk::Component.new(self)
    end
    keys = _symbolkey2str(keys)
    keys['menu'] = _parse_menu_spec(keys['menu']) if keys.key?('menu')
    tk_call(@path, 'add', type, tagid(tag), *hash_kv(keys))
    tag
  end
delete(path1, path2=nil)

[Source]

# File tk/lib/tkextlib/iwidgets/menubar.rb, line 151
  def delete(path1, path2=nil)
    if path2
    else
      tk_call(@path, 'delete', index(idx))
    end
    self
  end
index(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/menubar.rb, line 159
  def index(idx)
    number(tk_call(@path, 'index', tagid(idx)))
  end
insert(idx, type, tag=nil, keys={})

[Source]

# File tk/lib/tkextlib/iwidgets/menubar.rb, line 163
  def insert(idx, type, tag=nil, keys={})
    if tag.kind_of?(Hash)
      keys = tag
      tag = nil
    end
    if tag
      tag = Tk::Itk::Component.new(self, tagid(tag))
    else
      tag = Tk::Itk::Component.new(self)
    end
    keys = _symbolkey2str(keys)
    keys['menu'] = _parse_menu_spec(keys['menu']) if keys.key?('menu')
    tk_call(@path, 'insert', index(idx), type, tagid(tag), *hash_kv(keys))
    tag
  end
invoke(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/menubar.rb, line 179
  def invoke(idx)
    tk_call(@path, 'invoke', index(idx))
    self
  end
menubuttons(val = nil)

[Source]

# File tk/lib/tkextlib/iwidgets/menubar.rb, line 78
  def menubuttons(val = nil)
    unless val
      return tk_call(@path, 'cget', '-menubuttons')
    end

    tk_call(@path, 'configure', '-menubuttons', _parse_menu_spec(val))
    self
  end
menupath(pat)

[Source]

# File tk/lib/tkextlib/iwidgets/menubar.rb, line 184
  def menupath(pat)
    if (win = tk_call(@path, 'path', pat)) == '-1'
      return nil
    end
    window(win)
  end
menupath_glob(pat)

[Source]

# File tk/lib/tkextlib/iwidgets/menubar.rb, line 190
  def menupath_glob(pat)
    if (win = tk_call(@path, 'path', '-glob', pat)) == '-1'
      return nil
    end
    window(win)
  end
menupath_tclregexp(pat)

[Source]

# File tk/lib/tkextlib/iwidgets/menubar.rb, line 196
  def menupath_tclregexp(pat)
    if (win = tk_call(@path, 'path', '-regexp', pat)) == '-1'
      return nil
    end
    window(win)
  end
tagid(tagOrId)

[Source]

# File tk/lib/tkextlib/iwidgets/menubar.rb, line 55
  def tagid(tagOrId)
    if tagOrId.kind_of?(Tk::Itk::Component)
      tagOrId.name
    else
      #_get_eval_string(tagOrId)
      tagOrId
    end
  end
type(path)

[Source]

# File tk/lib/tkextlib/iwidgets/menubar.rb, line 203
  def type(path)
    tk_call(@path, 'type', path)
  end
yposition(path)

[Source]

# File tk/lib/tkextlib/iwidgets/menubar.rb, line 207
  def yposition(path)
    number(tk_call(@path, 'yposition', path))
  end


Class: Tk::Iwidgets::Messagebox

Class | Tk::Iwidgets::Messagebox
In: | tk/lib/tkextlib/iwidgets/messagebox.rb
Parent: | Tk::Iwidgets::Scrolledwidget

Methods

clear export issue tagid type_add

Included Modules

TkItemConfigMethod

Constants

TkCommandNames | = | ['::iwidgets::messagebox'.freeze].freeze
WidgetClassName | = | 'Messagebox'.freeze

External Aliases

itemcget | -> | typecget
itemconfigure | -> | typeconfigure
itemconfiginfo | -> | typeconfiginfo
current_itemconfiginfo | -> | current_typeconfiginfo

Public Instance methods

clear()

[Source]

# File tk/lib/tkextlib/iwidgets/messagebox.rb, line 76
  def clear
    tk_call(@path, 'clear')
    self
  end
export(file)

[Source]

# File tk/lib/tkextlib/iwidgets/messagebox.rb, line 81
  def export(file)
    tk_call(@path, 'export', file)
    self
  end
issue(string, type=None, *args)

[Source]

# File tk/lib/tkextlib/iwidgets/messagebox.rb, line 86
  def issue(string, type=None, *args)
    tk_call(@path, 'issue', string, tagid(type), *args)
    self
  end
tagid(tagOrId)

[Source]

# File tk/lib/tkextlib/iwidgets/messagebox.rb, line 35
  def tagid(tagOrId)
    if tagOrId.kind_of?(Tk::Itk::Component)
      tagOrId.name
    else
      #_get_eval_string(tagOrId)
      tagOrId
    end
  end
type_add(tag=nil, keys={})

[Source]

# File tk/lib/tkextlib/iwidgets/messagebox.rb, line 64
  def type_add(tag=nil, keys={})
    if tag.kind_of?(Hash)
      keys = tag
      tag = nil
    end
    unless tag
      tag = Tk::Itk::Component.new(self)
    end
    tk_call(@path, 'type', 'add', tagid(tag), *hash_kv(keys))
    tag
  end


Class: Tk::Iwidgets::Messagedialog

Class | Tk::Iwidgets::Messagedialog
In: | tk/lib/tkextlib/iwidgets/messagedialog.rb
Parent: | Tk::Iwidgets::Dialog

Constants

TkCommandNames | = | ['::iwidgets::messagedialog'.freeze].freeze
WidgetClassName | = | 'Messagedialog'.freeze


Class: Tk::Iwidgets::Notebook

Class | Tk::Iwidgets::Notebook
In: | tk/lib/tkextlib/iwidgets/notebook.rb
Parent: | Tk::Itk::Widget

Methods

add child_site child_site_list delete index insert next prev scrollbar scrollcommand select tagid view view_moveto view_scroll xscrollbar xscrollcommand xview xview_moveto xview_scroll yscrollbar yscrollcommand yview yview_moveto yview_scroll

Included Modules

TkItemConfigMethod

Constants

TkCommandNames | = | ['::iwidgets::notebook'.freeze].freeze
WidgetClassName | = | 'Notebook'.freeze

External Aliases

itemcget | -> | pagecget
itemconfigure | -> | pageconfigure
itemconfiginfo | -> | pageconfiginfo
current_itemconfiginfo | -> | current_pageconfiginfo

Public Instance methods

add(keys={})

[Source]

# File tk/lib/tkextlib/iwidgets/notebook.rb, line 59
  def add(keys={})
    window(tk_call(@path, 'add', *hash_kv(keys)))
  end
child_site(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/notebook.rb, line 67
  def child_site(idx)
    if (new_idx = self.index(idx)) < 0
      new_idx = tagid(idx)
    end
    window(tk_call(@path, 'childsite', new_idx))
  end
child_site_list()

[Source]

# File tk/lib/tkextlib/iwidgets/notebook.rb, line 63
  def child_site_list
    list(tk_call(@path, 'childsite'))
  end
delete(idx1, idx2=nil)

[Source]

# File tk/lib/tkextlib/iwidgets/notebook.rb, line 74
  def delete(idx1, idx2=nil)
    if (new_idx1 = self.index(idx1)) < 0
      new_idx1 = tagid(idx1)
    end
    if idx2
      if (new_idx2 = self.index(idx2)) < 0
        new_idx2 = tagid(idx2)
      end
      tk_call(@path, 'delete', new_idx1, new_idx2)
    else
      tk_call(@path, 'delete', new_idx1)
    end
    self
  end
index(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/notebook.rb, line 89
  def index(idx)
    number(tk_call(@path, 'index', tagid(idx)))
  end
insert(idx, keys={})

[Source]

# File tk/lib/tkextlib/iwidgets/notebook.rb, line 93
  def insert(idx, keys={})
    if (new_idx = self.index(idx)) < 0
      new_idx = tagid(idx)
    end
    window(tk_call(@path, 'insert', new_idx, *hash_kv(keys)))
  end
next()

[Source]

# File tk/lib/tkextlib/iwidgets/notebook.rb, line 100
  def next
    tk_call(@path, 'next')
    self
  end
prev()

[Source]

# File tk/lib/tkextlib/iwidgets/notebook.rb, line 105
  def prev
    tk_call(@path, 'prev')
    self
  end
scrollbar(bar=nil)

Alias for yscrollbar

scrollcommand(cmd=Proc.new)

[Source]

# File tk/lib/tkextlib/iwidgets/notebook.rb, line 118
  def scrollcommand(cmd=Proc.new)
    configure_cmd 'scrollcommand', cmd
    self
  end
select(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/notebook.rb, line 110
  def select(idx)
    if (new_idx = self.index(idx)) < 0
      new_idx = tagid(idx)
    end
    tk_call(@path, 'select', new_idx)
    self
  end
tagid(tagOrId)

[Source]

# File tk/lib/tkextlib/iwidgets/notebook.rb, line 35
  def tagid(tagOrId)
    if tagOrId.kind_of?(Tk::Itk::Component)
      tagOrId.name
    else
      #_get_eval_string(tagOrId)
      tagOrId
    end
  end
view(*idxs)

[Source]

# File tk/lib/tkextlib/iwidgets/notebook.rb, line 147
  def view(*idxs)
    if idxs.size == 0
      window(tk_send_without_enc('view'))
    else
      tk_send_without_enc('view', *idxs)
      self
    end
  end
view_moveto(*idxs)

[Source]

# File tk/lib/tkextlib/iwidgets/notebook.rb, line 158
  def view_moveto(*idxs)
    view('moveto', *idxs)
  end
view_scroll(*idxs)

[Source]

# File tk/lib/tkextlib/iwidgets/notebook.rb, line 163
  def view_scroll(*idxs)
    view('scroll', *idxs)
  end
xscrollbar(bar=nil)

[Source]

# File tk/lib/tkextlib/iwidgets/notebook.rb, line 125
  def xscrollbar(bar=nil)
    if bar
      @scrollbar = bar
      @scrollbar.orient 'horizontal'
      self.scrollcommand {|*arg| @scrollbar.set(*arg)}
      @scrollbar.command {|*arg| self.xview(*arg)}
      Tk.update  # avoid scrollbar trouble
    end
    @scrollbar
  end
xscrollcommand(cmd=Proc.new)

Alias for scrollcommand

xview(*idxs)

Alias for view

xview_moveto(*idxs)

Alias for view_moveto

xview_scroll(*idxs)

Alias for view_scroll

yscrollbar(bar=nil)

[Source]

# File tk/lib/tkextlib/iwidgets/notebook.rb, line 135
  def yscrollbar(bar=nil)
    if bar
      @scrollbar = bar
      @scrollbar.orient 'vertical'
      self.scrollcommand {|*arg| @scrollbar.set(*arg)}
      @scrollbar.command {|*arg| self.yview(*arg)}
      Tk.update  # avoid scrollbar trouble
    end
    @scrollbar
  end
yscrollcommand(cmd=Proc.new)

Alias for scrollcommand

yview(*idxs)

Alias for view

yview_moveto(*idxs)

Alias for view_moveto

yview_scroll(*idxs)

Alias for view_scroll


Class: Tk::Iwidgets::Optionmenu

Class | Tk::Iwidgets::Optionmenu
In: | tk/lib/tkextlib/iwidgets/optionmenu.rb
Parent: | Tk::Iwidgets::Labeledwidget

Methods

delete disable enable get get_range get_selected index insert select sort sort_ascending sort_descending

Constants

TkCommandNames | = | ['::iwidgets::optionmenu'.freeze].freeze
WidgetClassName | = | 'Optionmenu'.freeze

Public Instance methods

delete(first, last=nil)

[Source]

# File tk/lib/tkextlib/iwidgets/optionmenu.rb, line 26
  def delete(first, last=nil)
    if last
      tk_call(@path, 'delete', first, last)
    else
      tk_call(@path, 'delete', first)
    end
    self
  end
disable(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/optionmenu.rb, line 35
  def disable(idx)
    tk_call(@path, 'disable', idx)
    self
  end
enable(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/optionmenu.rb, line 40
  def enable(idx)
    tk_call(@path, 'enable', idx)
    self
  end
get(first=nil, last=nil)

[Source]

# File tk/lib/tkextlib/iwidgets/optionmenu.rb, line 45
  def get(first=nil, last=nil)
    if last
      simplelist(tk_call(@path, 'get', first, last))
    elsif first
      tk_call(@path, 'get', first)
    else
      tk_call(@path, 'get')
    end
  end
get_range(first, last)

[Source]

# File tk/lib/tkextlib/iwidgets/optionmenu.rb, line 54
  def get_range(first, last)
    get(first, last)
  end
get_selected()

[Source]

# File tk/lib/tkextlib/iwidgets/optionmenu.rb, line 57
  def get_selected
    get()
  end
index(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/optionmenu.rb, line 61
  def index(idx)
    number(tk_call(@path, 'index', idx))
  end
insert(idx, *args)

[Source]

# File tk/lib/tkextlib/iwidgets/optionmenu.rb, line 65
  def insert(idx, *args)
    tk_call(@path, 'insert', idx, *args)
    self
  end
select(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/optionmenu.rb, line 70
  def select(idx)
    tk_call(@path, 'select', idx)
    self
  end
sort(*params, &b)

[Source]

# File tk/lib/tkextlib/iwidgets/optionmenu.rb, line 75
  def sort(*params, &b)
    # see 'lsort' man page about params
    if b
      tk_call(@path, 'sort', '-command', proc(&b), *params)
    else
      tk_call(@path, 'sort', *params)
    end
    self
  end
sort_ascending()

[Source]

# File tk/lib/tkextlib/iwidgets/optionmenu.rb, line 84
  def sort_ascending
    tk_call(@path, 'sort', 'ascending')
    self
  end
sort_descending()

[Source]

# File tk/lib/tkextlib/iwidgets/optionmenu.rb, line 88
  def sort_descending
    tk_call(@path, 'sort', 'descending')
    self
  end


Class: Tk::Iwidgets::Panedwindow

Class | Tk::Iwidgets::Panedwindow
In: | tk/lib/tkextlib/iwidgets/panedwindow.rb
Parent: | Tk::Itk::Widget

Methods

add child_site child_site_list delete fraction hide index insert invoke reset show tagid

Included Modules

TkItemConfigMethod

Constants

TkCommandNames | = | ['::iwidgets::panedwindow'.freeze].freeze
WidgetClassName | = | 'Panedwindow'.freeze

External Aliases

itemcget | -> | panecget
itemconfigure | -> | paneconfigure
itemconfiginfo | -> | paneconfiginfo
current_itemconfiginfo | -> | current_paneconfiginfo

Public Instance methods

add(tag=nil, keys={})

[Source]

# File tk/lib/tkextlib/iwidgets/panedwindow.rb, line 59
  def add(tag=nil, keys={})
    if tag.kind_of?(Hash)
      keys = tag
      tag = nil
    end
    if tag
      tag = Tk::Itk::Component.new(self, tagid(tag))
    else
      tag = Tk::Itk::Component.new(self)
    end
    window(tk_call(@path, 'add', tagid(tag), *hash_kv(keys)))
    tag
  end
child_site(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/panedwindow.rb, line 77
  def child_site(idx)
    window(tk_call(@path, 'childsite', index(idx)))
  end
child_site_list()

[Source]

# File tk/lib/tkextlib/iwidgets/panedwindow.rb, line 73
  def child_site_list
    list(tk_call(@path, 'childsite'))
  end
delete(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/panedwindow.rb, line 81
  def delete(idx)
    tk_call(@path, 'delete', index(idx))
    self
  end
fraction(*percentages)

[Source]

# File tk/lib/tkextlib/iwidgets/panedwindow.rb, line 86
  def fraction(*percentages)
    tk_call(@path, 'fraction', *percentages)
    self
  end
hide(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/panedwindow.rb, line 91
  def hide(idx)
    tk_call(@path, 'hide', index(idx))
    self
  end
index(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/panedwindow.rb, line 96
  def index(idx)
    number(tk_call(@path, 'index', tagid(idx)))
  end
insert(idx, tag=nil, keys={})

[Source]

# File tk/lib/tkextlib/iwidgets/panedwindow.rb, line 100
  def insert(idx, tag=nil, keys={})
    if tag.kind_of?(Hash)
      keys = tag
      tag = nil
    end
    if tag
      tag = Tk::Itk::Component.new(self, tagid(tag))
    else
      tag = Tk::Itk::Component.new(self)
    end
    window(tk_call(@path, 'insert', index(idx), tagid(tag), *hash_kv(keys)))
    tag
  end
invoke(idx=nil)

[Source]

# File tk/lib/tkextlib/iwidgets/panedwindow.rb, line 114
  def invoke(idx=nil)
    if idx
      tk_call(@path, 'invoke', index(idx))
    else
      tk_call(@path, 'invoke')
    end
    self
  end
reset()

[Source]

# File tk/lib/tkextlib/iwidgets/panedwindow.rb, line 123
  def reset
    tk_call(@path, 'reset')
    self
  end
show(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/panedwindow.rb, line 128
  def show(idx)
    tk_call(@path, 'show', index(idx))
    self
  end
tagid(tagOrId)

[Source]

# File tk/lib/tkextlib/iwidgets/panedwindow.rb, line 35
  def tagid(tagOrId)
    if tagOrId.kind_of?(Tk::Itk::Component)
      tagOrId.name
    else
      #_get_eval_string(tagOrId)
      tagOrId
    end
  end


Class: Tk::Iwidgets::Promptdialog

Class | Tk::Iwidgets::Promptdialog
In: | tk/lib/tkextlib/iwidgets/promptdialog.rb
Parent: | Tk::Iwidgets::Dialog

Methods

clear cursor= default delete dragto get hide icursor index insert invoke mark selection_adjust selection_clear selection_from selection_present selection_range selection_to set show value value= xview xview_moveto xview_scroll

Constants

TkCommandNames | = | ['::iwidgets::promptdialog'.freeze].freeze
WidgetClassName | = | 'Promptdialog'.freeze

Public Instance methods

clear()

based on Tk::Iwidgets::Entryfield

[Source]

# File tk/lib/tkextlib/iwidgets/promptdialog.rb, line 48
  def clear
    tk_call(@path, 'clear')
    self
  end
cursor=(index)

[Source]

# File tk/lib/tkextlib/iwidgets/promptdialog.rb, line 69
  def cursor=(index)
    tk_send_without_enc('icursor', index)
    #self
    index
  end
default(name)

index method is not available, because it shows index of the entry field

[Source]

# File tk/lib/tkextlib/iwidgets/promptdialog.rb, line 22
  def default(name)
    tk_call(@path, 'default', tagid(name))
    self
  end
delete(first, last=None)

[Source]

# File tk/lib/tkextlib/iwidgets/promptdialog.rb, line 53
  def delete(first, last=None)
    tk_send_without_enc('delete', first, last)
    self
  end
dragto(pos)

[Source]

# File tk/lib/tkextlib/iwidgets/promptdialog.rb, line 89
  def dragto(pos)
    tk_send_without_enc('scan', 'dragto', pos)
    self
  end
get()

Alias for value

hide(name)

[Source]

# File tk/lib/tkextlib/iwidgets/promptdialog.rb, line 27
  def hide(name)
    tk_call(@path, 'hide', tagid(name))
    self
  end
icursor(index)

Alias for cursor=

index(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/promptdialog.rb, line 76
  def index(idx)
    number(tk_send_without_enc('index', idx))
  end
insert(pos,text)

[Source]

# File tk/lib/tkextlib/iwidgets/promptdialog.rb, line 80
  def insert(pos,text)
    tk_send_without_enc('insert', pos, _get_eval_enc_str(text))
    self
  end
invoke(name=nil)

[Source]

# File tk/lib/tkextlib/iwidgets/promptdialog.rb, line 32
  def invoke(name=nil)
    if name
      tk_call(@path, 'invoke', tagid(name))
    else
      tk_call(@path, 'invoke')
    end
    self
  end
mark(pos)

[Source]

# File tk/lib/tkextlib/iwidgets/promptdialog.rb, line 85
  def mark(pos)
    tk_send_without_enc('scan', 'mark', pos)
    self
  end
selection_adjust(index)

[Source]

# File tk/lib/tkextlib/iwidgets/promptdialog.rb, line 93
  def selection_adjust(index)
    tk_send_without_enc('selection', 'adjust', index)
    self
  end
selection_clear()

[Source]

# File tk/lib/tkextlib/iwidgets/promptdialog.rb, line 97
  def selection_clear
    tk_send_without_enc('selection', 'clear')
    self
  end
selection_from(index)

[Source]

# File tk/lib/tkextlib/iwidgets/promptdialog.rb, line 101
  def selection_from(index)
    tk_send_without_enc('selection', 'from', index)
    self
  end
selection_present()

[Source]

# File tk/lib/tkextlib/iwidgets/promptdialog.rb, line 105
  def selection_present()
    bool(tk_send_without_enc('selection', 'present'))
  end
selection_range(s, e)

[Source]

# File tk/lib/tkextlib/iwidgets/promptdialog.rb, line 108
  def selection_range(s, e)
    tk_send_without_enc('selection', 'range', s, e)
    self
  end
selection_to(index)

[Source]

# File tk/lib/tkextlib/iwidgets/promptdialog.rb, line 112
  def selection_to(index)
    tk_send_without_enc('selection', 'to', index)
    self
  end
set(val)

Alias for value=

show(name)

[Source]

# File tk/lib/tkextlib/iwidgets/promptdialog.rb, line 41
  def show(name)
    tk_call(@path, 'show', tagid(name))
    self
  end
value()

[Source]

# File tk/lib/tkextlib/iwidgets/promptdialog.rb, line 58
  def value
    _fromUTF8(tk_send_without_enc('get'))
  end
value=(val)

[Source]

# File tk/lib/tkextlib/iwidgets/promptdialog.rb, line 61
  def value= (val)
    tk_send_without_enc('delete', 0, 'end')
    tk_send_without_enc('insert', 0, _get_eval_enc_str(val))
    val
  end
xview(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/promptdialog.rb, line 117
  def xview(*index)
    if index.size == 0
      list(tk_send_without_enc('xview'))
    else
      tk_send_without_enc('xview', *index)
      self
    end
  end
xview_moveto(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/promptdialog.rb, line 125
  def xview_moveto(*index)
    xview('moveto', *index)
  end
xview_scroll(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/promptdialog.rb, line 128
  def xview_scroll(*index)
    xview('scroll', *index)
  end


Class: Tk::Iwidgets::Pushbutton

Class | Tk::Iwidgets::Pushbutton
In: | tk/lib/tkextlib/iwidgets/pushbutton.rb
Parent: | Tk::Itk::Widget

Methods

flash invoke

Constants

TkCommandNames | = | ['::iwidgets::pushbutton'.freeze].freeze
WidgetClassName | = | 'Pushbutton'.freeze

Public Instance methods

flash()

[Source]

# File tk/lib/tkextlib/iwidgets/pushbutton.rb, line 31
  def flash
    tk_call_without_enc(@path, 'flash')
    self
  end
invoke()

[Source]

# File tk/lib/tkextlib/iwidgets/pushbutton.rb, line 26
  def invoke
    tk_call_without_enc(@path, 'invoke')
    self
  end


Class: Tk::Iwidgets::Radiobox

Class | Tk::Iwidgets::Radiobox
In: | tk/lib/tkextlib/iwidgets/radiobox.rb
Parent: | Tk::Iwidgets::Labeledframe

Methods

add delete deselect flash get index insert select tagid

Included Modules

TkItemConfigMethod

Constants

TkCommandNames | = | ['::iwidgets::radiobox'.freeze].freeze
WidgetClassName | = | 'Radiobox'.freeze

External Aliases

itemcget | -> | buttoncget
itemconfigure | -> | buttonconfigure
itemconfiginfo | -> | buttonconfiginfo
current_itemconfiginfo | -> | current_buttonconfiginfo

Public Instance methods

add(tag=nil, keys={})

[Source]

# File tk/lib/tkextlib/iwidgets/radiobox.rb, line 59
  def add(tag=nil, keys={})
    if tag.kind_of?(Hash)
      keys = tag
      tag = nil
    end
    if tag
      tag = Tk::Itk::Component.new(self, tagid(tag))
    else
      tag = Tk::Itk::Component.new(self)
    end
    tk_call(@path, 'add', tagid(tag), *hash_kv(keys))
    tag
  end
delete(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/radiobox.rb, line 73
  def delete(idx)
    tk_call(@path, 'delete', index(idx))
    self
  end
deselect(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/radiobox.rb, line 78
  def deselect(idx)
    tk_call(@path, 'deselect', index(idx))
    self
  end
flash(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/radiobox.rb, line 83
  def flash(idx)
    tk_call(@path, 'flash', index(idx))
    self
  end
get(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/radiobox.rb, line 88
  def get(idx)
    simplelist(tk_call(@path, 'get', index(idx))).collect{|id|
      Tk::Itk::Component.id2obj(id)
    }
  end
index(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/radiobox.rb, line 94
  def index(idx)
    number(tk_call(@path, 'index', tagid(idx)))
  end
insert(idx, tag=nil, keys={})

[Source]

# File tk/lib/tkextlib/iwidgets/radiobox.rb, line 98
  def insert(idx, tag=nil, keys={})
    if tag.kind_of?(Hash)
      keys = tag
      tag = nil
    end
    if tag
      tag = Tk::Itk::Component.new(self, tagid(tag))
    else
      tag = Tk::Itk::Component.new(self)
    end
    tk_call(@path, 'insert', index(idx), tagid(tag), *hash_kv(keys))
    tag
  end
select(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/radiobox.rb, line 112
  def select(idx)
    tk_call(@path, 'select', index(idx))
    self
  end
tagid(tagOrId)

[Source]

# File tk/lib/tkextlib/iwidgets/radiobox.rb, line 40
  def tagid(tagOrId)
    if tagOrId.kind_of?(Tk::Itk::Component)
      tagOrId.name
    else
      #_get_eval_string(tagOrId)
      tagOrId
    end
  end


Class: Tk::Iwidgets::Scopedobject

Class | Tk::Iwidgets::Scopedobject
In: | tk/lib/tkextlib/iwidgets/scopedobject.rb
Parent: | TkObject

Methods

new

Constants

TkCommandNames | = | ['::iwidgets::scopedobject'.freeze].freeze
WidgetClassName | = | 'Scopedobject'.freeze

Public Class methods

new(obj_name, keys={})

[Source]

# File tk/lib/tkextlib/iwidgets/scopedobject.rb, line 21
  def initialize(obj_name, keys={})
    @path = tk_call(self.class::TkCommandNames[0], obj_name, *hash_kv(keys))
  end


Class: Tk::Iwidgets::Scrolledcanvas

Class | Tk::Iwidgets::Scrolledcanvas
In: | tk/lib/tkextlib/iwidgets/scrolledcanvas.rb
Parent: | Tk::Iwidgets::Scrolledwidget

Methods

addtag addtag_above addtag_all addtag_below addtag_closest addtag_enclosed addtag_overlapping addtag_withtag bbox canvasx canvasy child_site coords create dchars delete dtag find find_above find_all find_below find_closest find_enclosed find_overlapping find_withtag gettags icursor index insert itembind itembind_append itembind_remove itembindinfo itemfocus itemtype justify lower method_missing move new postscript raise remove scale scan_dragto scan_mark select select_adjust select_clear select_from select_item select_to xview xview_moveto xview_scroll yview yview_moveto yview_scroll

Included Modules

TkCanvasItemConfig

Constants

TkCommandNames | = | ['::iwidgets::scrolledcanvas'.freeze].freeze
WidgetClassName | = | 'Scrolledcanvas'.freeze

Public Class methods

new(*args)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 34
  def initialize(*args)
    super(*args)
    @canvas = component_widget('canvas')
  end

Public Instance methods

addtag(tag, mode, *args)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 79
  def addtag(tag, mode, *args)
    tk_send_without_enc('addtag', tagid(tag), mode, *args)
    self
  end
addtag_above(tagOrId, target)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 83
  def addtag_above(tagOrId, target)
    addtag(tagOrId, 'above', tagid(target))
  end
addtag_all(tagOrId)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 86
  def addtag_all(tagOrId)
    addtag(tagOrId, 'all')
  end
addtag_below(tagOrId, target)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 89
  def addtag_below(tagOrId, target)
    addtag(tagOrId, 'below', tagid(target))
  end
addtag_closest(tagOrId, x, y, halo=None, start=None)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 92
  def addtag_closest(tagOrId, x, y, halo=None, start=None)
    addtag(tagOrId, 'closest', x, y, halo, start)
  end
addtag_enclosed(tagOrId, x1, y1, x2, y2)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 95
  def addtag_enclosed(tagOrId, x1, y1, x2, y2)
    addtag(tagOrId, 'enclosed', x1, y1, x2, y2)
  end
addtag_overlapping(tagOrId, x1, y1, x2, y2)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 98
  def addtag_overlapping(tagOrId, x1, y1, x2, y2)
    addtag(tagOrId, 'overlapping', x1, y1, x2, y2)
  end
addtag_withtag(tagOrId, tag)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 101
  def addtag_withtag(tagOrId, tag)
    addtag(tagOrId, 'withtag', tagid(tag))
  end
bbox(tagOrId, *tags)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 105
  def bbox(tagOrId, *tags)
    list(tk_send_without_enc('bbox', tagid(tagOrId),
                             *tags.collect{|t| tagid(t)}))
  end
canvasx(screen_x, *args)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 149
  def canvasx(screen_x, *args)
    #tk_tcl2ruby(tk_send_without_enc('canvasx', screen_x, *args))
    number(tk_send_without_enc('canvasx', screen_x, *args))
  end
canvasy(screen_y, *args)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 153
  def canvasy(screen_y, *args)
    #tk_tcl2ruby(tk_send_without_enc('canvasy', screen_y, *args))
    number(tk_send_without_enc('canvasy', screen_y, *args))
  end
child_site()

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 49
  def child_site
    window(tk_call(@path, 'childsite'))
  end
coords(tag, *args)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 158
  def coords(tag, *args)
    if args == []
      tk_split_list(tk_send_without_enc('coords', tagid(tag)))
    else
      tk_send_without_enc('coords', tagid(tag), *(args.flatten))
      self
    end
  end
create(type, *args)

create a canvas item without creating a TkcItem object

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 73
  def create(type, *args)
    type.create(self, *args)
  end
dchars(tag, first, last=None)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 167
  def dchars(tag, first, last=None)
    tk_send_without_enc('dchars', tagid(tag),
                        _get_eval_enc_str(first), _get_eval_enc_str(last))
    self
  end
delete(*args)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 173
  def delete(*args)
    if TkcItem::CItemID_TBL[self.path]
      find('withtag', *args).each{|item|
        if item.kind_of?(TkcItem)
          TkcItem::CItemID_TBL[self.path].delete(item.id)
        end
      }
    end
    tk_send_without_enc('delete', *args.collect{|t| tagid(t)})
    self
  end
dtag(tag, tag_to_del=None)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 186
  def dtag(tag, tag_to_del=None)
    tk_send_without_enc('dtag', tagid(tag), tag_to_del)
    self
  end
find(mode, *args)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 191
  def find(mode, *args)
    list(tk_send_without_enc('find', mode, *args)).collect!{|id|
      TkcItem.id2obj(self, id)
    }
  end
find_above(target)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 196
  def find_above(target)
    find('above', tagid(target))
  end
find_all()

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 199
  def find_all
    find('all')
  end
find_below(target)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 202
  def find_below(target)
    find('below', tagid(target))
  end
find_closest(x, y, halo=None, start=None)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 205
  def find_closest(x, y, halo=None, start=None)
    find('closest', x, y, halo, start)
  end
find_enclosed(x1, y1, x2, y2)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 208
  def find_enclosed(x1, y1, x2, y2)
    find('enclosed', x1, y1, x2, y2)
  end
find_overlapping(x1, y1, x2, y2)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 211
  def find_overlapping(x1, y1, x2, y2)
    find('overlapping', x1, y1, x2, y2)
  end
find_withtag(tag)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 214
  def find_withtag(tag)
    find('withtag', tag)
  end
gettags(tagOrId)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 232
  def gettags(tagOrId)
    list(tk_send_without_enc('gettags', tagid(tagOrId))).collect{|tag|
      TkcTag.id2obj(self, tag)
    }
  end
icursor(tagOrId, index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 238
  def icursor(tagOrId, index)
    tk_send_without_enc('icursor', tagid(tagOrId), index)
    self
  end
index(tagOrId, idx)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 243
  def index(tagOrId, idx)
    number(tk_send_without_enc('index', tagid(tagOrId), idx))
  end
insert(tagOrId, index, string)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 247
  def insert(tagOrId, index, string)
    tk_send_without_enc('insert', tagid(tagOrId), index,
                        _get_eval_enc_str(string))
    self
  end
itembind(tag, context, *args)

def itembind(tag, context, cmd=Proc.new, *args)

  _bind([path, "bind", tagid(tag)], context, cmd, *args)
  self

end

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 114
  def itembind(tag, context, *args)
    # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    _bind([path, "bind", tagid(tag)], context, cmd, *args)
    self
  end
itembind_append(tag, context, *args)

def itembind_append(tag, context, cmd=Proc.new, *args)

  _bind_append([path, "bind", tagid(tag)], context, cmd, *args)
  self

end

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 129
  def itembind_append(tag, context, *args)
    # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    _bind_append([path, "bind", tagid(tag)], context, cmd, *args)
    self
  end
itembind_remove(tag, context)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 140
  def itembind_remove(tag, context)
    _bind_remove([path, "bind", tagid(tag)], context)
    self
  end
itembindinfo(tag, context=nil)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 145
  def itembindinfo(tag, context=nil)
    _bindinfo([path, "bind", tagid(tag)], context)
  end
itemfocus(tagOrId=nil)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 218
  def itemfocus(tagOrId=nil)
    if tagOrId
      tk_send_without_enc('focus', tagid(tagOrId))
      self
    else
      ret = tk_send_without_enc('focus')
      if ret == ""
        nil
      else
        TkcItem.id2obj(self, ret)
      end
    end
  end
itemtype(tag)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 314
  def itemtype(tag)
    TkcItem.type2class(tk_send('type', tagid(tag)))
  end
justify(dir)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 53
  def justify(dir)
    tk_call(@path, 'justify', dir)
    self
  end
lower(tag, below=nil)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 253
  def lower(tag, below=nil)
    if below
      tk_send_without_enc('lower', tagid(tag), tagid(below))
    else
      tk_send_without_enc('lower', tagid(tag))
    end
    self
  end
method_missing(id, *args)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 39
  def method_missing(id, *args)
    if @canvas.methods.include?(id.id2name)
      @canvas.__send__(id, *args)
    else
      super(id, *args)
    end
  end
move(tag, x, y)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 262
  def move(tag, x, y)
    tk_send_without_enc('move', tagid(tag), x, y)
    self
  end
postscript(keys)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 267
  def postscript(keys)
    tk_send("postscript", *hash_kv(keys))
  end
raise(tag, above=nil)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 271
  def raise(tag, above=nil)
    if above
      tk_send_without_enc('raise', tagid(tag), tagid(above))
    else
      tk_send_without_enc('raise', tagid(tag))
    end
    self
  end
remove(*args)

Alias for delete

scale(tag, x, y, xs, ys)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 280
  def scale(tag, x, y, xs, ys)
    tk_send_without_enc('scale', tagid(tag), x, y, xs, ys)
    self
  end
scan_dragto(x, y)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 289
  def scan_dragto(x, y)
    tk_send_without_enc('scan', 'dragto', x, y)
    self
  end
scan_mark(x, y)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 285
  def scan_mark(x, y)
    tk_send_without_enc('scan', 'mark', x, y)
    self
  end
select(mode, *args)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 294
  def select(mode, *args)
    r = tk_send_without_enc('select', mode, *args)
    (mode == 'item')? TkcItem.id2obj(self, r): self
  end
select_adjust(tagOrId, index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 298
  def select_adjust(tagOrId, index)
    select('adjust', tagid(tagOrId), index)
  end
select_clear()

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 301
  def select_clear
    select('clear')
  end
select_from(tagOrId, index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 304
  def select_from(tagOrId, index)
    select('from', tagid(tagOrId), index)
  end
select_item()

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 307
  def select_item
    select('item')
  end
select_to(tagOrId, index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 310
  def select_to(tagOrId, index)
    select('to', tagid(tagOrId), index)
  end
xview(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 318
  def xview(*index)
    if index.size == 0
      list(tk_send_without_enc('xview'))
    else
      tk_send_without_enc('xview', *index)
      self
    end
  end
xview_moveto(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 326
  def xview_moveto(*index)
    xview('moveto', *index)
  end
xview_scroll(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 329
  def xview_scroll(*index)
    xview('scroll', *index)
  end
yview(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 333
  def yview(*index)
    if index.size == 0
      list(tk_send_without_enc('yview'))
    else
      tk_send_without_enc('yview', *index)
      self
    end
  end
yview_moveto(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 341
  def yview_moveto(*index)
    yview('moveto', *index)
  end
yview_scroll(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledcanvas.rb, line 344
  def yview_scroll(*index)
    yview('scroll', *index)
  end


Class: Tk::Iwidgets::Scrolledframe

Class | Tk::Iwidgets::Scrolledframe
In: | tk/lib/tkextlib/iwidgets/scrolledframe.rb
Parent: | Tk::Iwidgets::Scrolledwidget

Methods

child_site justify xview xview_moveto xview_scroll yview yview_moveto yview_scroll

Constants

TkCommandNames | = | ['::iwidgets::scrolledframe'.freeze].freeze
WidgetClassName | = | 'Scrolledframe'.freeze

Public Instance methods

child_site()

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledframe.rb, line 21
  def child_site
    window(tk_call(@path, 'childsite'))
  end
justify(dir)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledframe.rb, line 25
  def justify(dir)
    tk_call(@path, 'justify', dir)
    self
  end
xview(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledframe.rb, line 30
  def xview(*index)
    if index.size == 0
      list(tk_send_without_enc('xview'))
    else
      tk_send_without_enc('xview', *index)
      self
    end
  end
xview_moveto(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledframe.rb, line 38
  def xview_moveto(*index)
    xview('moveto', *index)
  end
xview_scroll(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledframe.rb, line 41
  def xview_scroll(*index)
    xview('scroll', *index)
  end
yview(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledframe.rb, line 45
  def yview(*index)
    if index.size == 0
      list(tk_send_without_enc('yview'))
    else
      tk_send_without_enc('yview', *index)
      self
    end
  end
yview_moveto(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledframe.rb, line 53
  def yview_moveto(*index)
    yview('moveto', *index)
  end
yview_scroll(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledframe.rb, line 56
  def yview_scroll(*index)
    yview('scroll', *index)
  end


Class: Tk::Iwidgets::Scrolledhtml

Class | Tk::Iwidgets::Scrolledhtml
In: | tk/lib/tkextlib/iwidgets/scrolledhtml.rb
Parent: | Tk::Iwidgets::Scrolledtext

Methods

import import_link pwd render title

Constants

TkCommandNames | = | ['::iwidgets::scrolledhtml'.freeze].freeze
WidgetClassName | = | 'Scrolledhtml'.freeze

Public Instance methods

import(href)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledhtml.rb, line 36
  def import(href)
    tk_call(@path, 'import', href)
    self
  end
import_link(href)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledhtml.rb, line 41
  def import_link(href)
    tk_call(@path, 'import', '-link', href)
    self
  end
pwd()

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledhtml.rb, line 46
  def pwd
    tk_call(@path, 'pwd')
  end
render(htmltext, workdir=None)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledhtml.rb, line 50
  def render(htmltext, workdir=None)
    tk_call(@path, 'render', htmltext, workdir)
    self
  end
title()

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledhtml.rb, line 55
  def title
    tk_call(@path, 'title')
  end


Class: Tk::Iwidgets::Scrolledlistbox

Class | Tk::Iwidgets::Scrolledlistbox
In: | tk/lib/tkextlib/iwidgets/scrolledlistbox.rb
Parent: | Tk::Iwidgets::Scrolledwidget

Methods

activate bbox clear curselection delete get get get_curselection index insert justify method_missing nearest new scan_dragto scan_mark see selected_item_count selection_anchor selection_clear selection_includes selection_set size sort sort_ascending sort_descending xview xview_moveto xview_scroll yview yview_moveto yview_scroll

Included Modules

TkListItemConfig

Constants

TkCommandNames | = | ['::iwidgets::scrolledlistbox'.freeze].freeze
WidgetClassName | = | 'Scrolledlistbox'.freeze

Public Class methods

new(*args)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledlistbox.rb, line 39
  def initialize(*args)
    super(*args)
    @listbox = component_widget('listbox')
  end

Public Instance methods

activate(y)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledlistbox.rb, line 134
  def activate(y)
    tk_send_without_enc('activate', y)
    self
  end
bbox(index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledlistbox.rb, line 92
  def bbox(index)
    list(tk_send_without_enc('bbox', index))
  end
clear()

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledlistbox.rb, line 54
  def clear
    tk_call(@path, 'clear')
    self
  end
curselection()

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledlistbox.rb, line 138
  def curselection
    list(tk_send_without_enc('curselection'))
  end
delete(first, last=None)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledlistbox.rb, line 95
  def delete(first, last=None)
    tk_send_without_enc('delete', first, last)
    self
  end
get(first, last=nil)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledlistbox.rb, line 141
  def get(first, last=nil)
    if last
      # tk_split_simplelist(_fromUTF8(tk_send_without_enc('get', first, last)))
      tk_split_simplelist(tk_send_without_enc('get', first, last),
                          false, true)
    else
      _fromUTF8(tk_send_without_enc('get', first))
    end
  end
get(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledlistbox.rb, line 99
  def get(*index)
    _fromUTF8(tk_send_without_enc('get', *index))
  end
get_curselection()

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledlistbox.rb, line 59
  def get_curselection
    tk_call(@path, 'getcurselection')
  end
index(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledlistbox.rb, line 172
  def index(idx)
    tk_send_without_enc('index', idx).to_i
  end
insert(index, *args)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledlistbox.rb, line 102
  def insert(index, *args)
    tk_send('insert', index, *args)
    self
  end
justify(dir)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledlistbox.rb, line 63
  def justify(dir)
    tk_call(@path, 'justify', dir)
    self
  end
method_missing(id, *args)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledlistbox.rb, line 44
  def method_missing(id, *args)
    if @listbox.methods.include?(id.id2name)
      @listbox.__send__(id, *args)
    else
      super(id, *args)
    end
  end
nearest(y)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledlistbox.rb, line 150
  def nearest(y)
    tk_send_without_enc('nearest', y).to_i
  end
scan_dragto(x, y)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledlistbox.rb, line 110
  def scan_dragto(x, y)
    tk_send_without_enc('scan', 'dragto', x, y)
    self
  end
scan_mark(x, y)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledlistbox.rb, line 106
  def scan_mark(x, y)
    tk_send_without_enc('scan', 'mark', x, y)
    self
  end
see(index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledlistbox.rb, line 114
  def see(index)
    tk_send_without_enc('see', index)
    self
  end
selected_item_count()

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledlistbox.rb, line 68
  def selected_item_count
    number(tk_call(@path, 'selecteditemcount'))
  end
selection_anchor(index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledlistbox.rb, line 156
  def selection_anchor(index)
    tk_send_without_enc('selection', 'anchor', index)
    self
  end
selection_clear(first, last=None)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledlistbox.rb, line 160
  def selection_clear(first, last=None)
    tk_send_without_enc('selection', 'clear', first, last)
    self
  end
selection_includes(index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledlistbox.rb, line 164
  def selection_includes(index)
    bool(tk_send_without_enc('selection', 'includes', index))
  end
selection_set(first, last=None)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledlistbox.rb, line 167
  def selection_set(first, last=None)
    tk_send_without_enc('selection', 'set', first, last)
    self
  end
size()

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledlistbox.rb, line 153
  def size
    tk_send_without_enc('size').to_i
  end
sort(*params, &b)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledlistbox.rb, line 72
  def sort(*params, &b)
    # see 'lsort' man page about params
    if b
      tk_call(@path, 'sort', '-command', proc(&b), *params)
    else
      tk_call(@path, 'sort', *params)
    end
    self
  end
sort_ascending()

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledlistbox.rb, line 81
  def sort_ascending
    tk_call(@path, 'sort', 'ascending')
    self
  end
sort_descending()

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledlistbox.rb, line 85
  def sort_descending
    tk_call(@path, 'sort', 'descending')
    self
  end
xview(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledlistbox.rb, line 178
  def xview(*index)
    if index.size == 0
      list(tk_send_without_enc('xview'))
    else
      tk_send_without_enc('xview', *index)
      self
    end
  end
xview_moveto(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledlistbox.rb, line 186
  def xview_moveto(*index)
    xview('moveto', *index)
  end
xview_scroll(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledlistbox.rb, line 189
  def xview_scroll(*index)
    xview('scroll', *index)
  end
yview(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledlistbox.rb, line 193
  def yview(*index)
    if index.size == 0
      list(tk_send_without_enc('yview'))
    else
      tk_send_without_enc('yview', *index)
      self
    end
  end
yview_moveto(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledlistbox.rb, line 201
  def yview_moveto(*index)
    yview('moveto', *index)
  end
yview_scroll(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledlistbox.rb, line 204
  def yview_scroll(*index)
    yview('scroll', *index)
  end


Class: Tk::Iwidgets::Scrolledtext

Class | Tk::Iwidgets::Scrolledtext
In: | tk/lib/tkextlib/iwidgets/scrolledtext.rb
Parent: | Tk::Iwidgets::Scrolledwidget

Methods

bbox child_site clear compare current_image_configinfo debug debug= delete dlineinfo export get get_displaychars image_cget image_configinfo image_configure image_names import index insert mark_gravity mark_names mark_next mark_previous mark_set mark_unset method_missing new next_mark previous_mark rsearch rsearch_with_length scan_dragto scan_mark search search_with_length see set_mark tksearch tksearch_with_count unset_mark xview xview_moveto xview_scroll yview yview_moveto yview_scroll

Included Modules

TkTextTagConfig

Constants

TkCommandNames | = | ['::iwidgets::scrolledtext'.freeze].freeze
WidgetClassName | = | 'Scrolledtext'.freeze

Public Class methods

new(*args)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 34
  def initialize(*args)
    super(*args)
    @text = component_widget('text')
  end

Public Instance methods

bbox(index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 85
  def bbox(index)
    list(tk_send('bbox', index))
  end
child_site()

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 49
  def child_site
    window(tk_call(@path, 'childsite'))
  end
clear()

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 53
  def clear
    tk_call(@path, 'clear')
    self
  end
compare(idx1, op, idx2)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 88
  def compare(idx1, op, idx2)
    bool(tk_send_without_enc('compare', _get_eval_enc_str(idx1),
                             op, _get_eval_enc_str(idx2)))
  end
current_image_configinfo(index, slot = nil)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 234
  def current_image_configinfo(index, slot = nil)
    if TkComm::GET_CONFIGINFO_AS_ARRAY
      if slot
        conf = image_configinfo(index, slot)
        {conf[0] => conf[4]}
      else
        ret = {}
        image_configinfo(index).each{|conf|
          ret[conf[0]] = conf[4] if conf.size > 2
        }
        ret
      end
    else # ! TkComm::GET_CONFIGINFO_AS_ARRAY
      ret = {}
      image_configinfo(index, slot).each{|k, conf|
        ret[k] = conf[-1] if conf.kind_of?(Array)
      }
      ret
    end
  end
debug()

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 93
  def debug
    bool(tk_send_without_enc('debug'))
  end
debug=(boolean)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 96
  def debug=(boolean)
    tk_send_without_enc('debug', boolean)
    #self
    boolean
  end
delete(first, last=None)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 102
  def delete(first, last=None)
    tk_send_without_enc('delete', first, last)
    self
  end
dlineinfo(index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 107
  def dlineinfo(index)
    list(tk_send_without_enc('dlineinfo', _get_eval_enc_str(index)))
  end
export(file)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 67
  def export(file)
    tk_call(@path, 'export', file)
    self
  end
get(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 111
  def get(*index)
    _fromUTF8(tk_send_without_enc('get', *index))
  end
get_displaychars(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 114
  def get_displaychars(*index)
    # Tk8.5 feature
    get('-displaychars', *index)
  end
image_cget(index, slot)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 119
  def image_cget(index, slot)
    case slot.to_s
    when 'text', 'label', 'show', 'data', 'file'
      _fromUTF8(tk_send_without_enc('image', 'cget',
                                    _get_eval_enc_str(index), "-#{slot}"))
    else
      tk_tcl2ruby(_fromUTF8(tk_send_without_enc('image', 'cget',
                                                _get_eval_enc_str(index),
                                                "-#{slot}")))
    end
  end
image_configinfo(index, slot = nil)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 145
  def image_configinfo(index, slot = nil)
    if TkComm::GET_CONFIGINFO_AS_ARRAY
      if slot
        case slot.to_s
        when 'text', 'label', 'show', 'data', 'file'
          #conf = tk_split_simplelist(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}")))
          conf = tk_split_simplelist(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}"), false, true)
        else
          #conf = tk_split_list(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}")))
          conf = tk_split_list(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}"), 0, false, true)
        end
        conf[0] = conf[0][1..-1]
        conf
      else
        #tk_split_simplelist(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index)))).collect{|conflist|
        #  conf = tk_split_simplelist(conflist)
        tk_split_simplelist(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index)), false, false).collect{|conflist|
          conf = tk_split_simplelist(conflist, false, true)
          conf[0] = conf[0][1..-1]
          case conf[0]
          when 'text', 'label', 'show', 'data', 'file'
          else
            if conf[3]
              if conf[3].index('{')
                conf[3] = tk_split_list(conf[3])
              else
                conf[3] = tk_tcl2ruby(conf[3])
              end
            end
            if conf[4]
              if conf[4].index('{')
                conf[4] = tk_split_list(conf[4])
              else
                conf[4] = tk_tcl2ruby(conf[4])
              end
            end
          end
          conf[1] = conf[1][1..-1] if conf.size == 2 # alias info
          conf
        }
      end
    else # ! TkComm::GET_CONFIGINFO_AS_ARRAY
      if slot
        case slot.to_s
        when 'text', 'label', 'show', 'data', 'file'
          #conf = tk_split_simplelist(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}")))
          conf = tk_split_simplelist(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}"), false, true)
        else
          #conf = tk_split_list(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}")))
          conf = tk_split_list(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}"), 0, false, true)
        end
        key = conf.shift[1..-1]
        { key => conf }
      else
        ret = {}
        #tk_split_simplelist(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index)))).each{|conflist|
        #  conf = tk_split_simplelist(conflist)
        tk_split_simplelist(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index)), false, false).each{|conflist|
          conf = tk_split_simplelist(conflist, false, true)
          key = conf.shift[1..-1]
          case key
          when 'text', 'label', 'show', 'data', 'file'
          else
            if conf[2]
              if conf[2].index('{')
                conf[2] = tk_split_list(conf[2])
              else
                conf[2] = tk_tcl2ruby(conf[2])
              end
            end
            if conf[3]
              if conf[3].index('{')
                conf[3] = tk_split_list(conf[3])
              else
                conf[3] = tk_tcl2ruby(conf[3])
              end
            end
          end
          if conf.size == 1
            ret[key] = conf[0][1..-1]  # alias info
          else
            ret[key] = conf
          end
        }
        ret
      end
    end
  end
image_configure(index, slot, value=None)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 131
  def image_configure(index, slot, value=None)
    if slot.kind_of? Hash
      _fromUTF8(tk_send_without_enc('image', 'configure',
                                    _get_eval_enc_str(index),
                                    *hash_kv(slot, true)))
    else
      _fromUTF8(tk_send_without_enc('image', 'configure',
                                    _get_eval_enc_str(index),
                                    "-#{slot}",
                                    _get_eval_enc_str(value)))
    end
    self
  end
image_names()

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 255
  def image_names
    #tk_split_simplelist(_fromUTF8(tk_send_without_enc('image', 'names'))).collect{|elt|
    tk_split_simplelist(tk_send_without_enc('image', 'names'), false, true).collect{|elt|
      tagid2obj(elt)
    }
  end
import(file, idx=nil)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 58
  def import(file, idx=nil)
    if idx
      tk_call(@path, 'import', file, index(idx))
    else
      tk_call(@path, 'import', file)
    end
    self
  end
index(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 262
  def index(idx)
    tk_send_without_enc('index', _get_eval_enc_str(idx))
  end
insert(index, *args)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 266
  def insert(index, *args)
    tk_send('insert', index, *args)
    self
  end
mark_gravity(mark, direction=nil)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 278
  def mark_gravity(mark, direction=nil)
    if direction
      tk_send_without_enc('mark', 'gravity',
                          _get_eval_enc_str(mark), direction)
      self
    else
      tk_send_without_enc('mark', 'gravity', _get_eval_enc_str(mark))
    end
  end
mark_names()

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 271
  def mark_names
    #tk_split_simplelist(_fromUTF8(tk_send_without_enc('mark', 'names'))).collect{|elt|
    tk_split_simplelist(tk_send_without_enc('mark', 'names'), false, true).collect{|elt|
      tagid2obj(elt)
    }
  end
mark_next(index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 302
  def mark_next(index)
    tagid2obj(_fromUTF8(tk_send_without_enc('mark', 'next',
                                            _get_eval_enc_str(index))))
  end
mark_previous(index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 308
  def mark_previous(index)
    tagid2obj(_fromUTF8(tk_send_without_enc('mark', 'previous',
                                            _get_eval_enc_str(index))))
  end
mark_set(mark, index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 288
  def mark_set(mark, index)
    tk_send_without_enc('mark', 'set', _get_eval_enc_str(mark),
                        _get_eval_enc_str(index))
    self
  end
mark_unset(*marks)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 295
  def mark_unset(*marks)
    tk_send_without_enc('mark', 'unset',
                        *(marks.collect{|mark| _get_eval_enc_str(mark)}))
    self
  end
method_missing(id, *args)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 39
  def method_missing(id, *args)
    if @text.methods.include?(id.id2name)
      @text.__send__(id, *args)
    else
      super(id, *args)
    end
  end
next_mark(index)

Alias for mark_next

previous_mark(index)

Alias for mark_previous

rsearch(pat,start,stop=None)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 498
  def rsearch(pat,start,stop=None)
    rsearch_with_length(pat,start,stop)[0]
  end
rsearch_with_length(pat,start,stop=None)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 446
  def rsearch_with_length(pat,start,stop=None)
    pat = pat.chr if pat.kind_of? Integer
    if stop != None
      return ["", 0] if compare(start,'<=',stop)
      txt = get(stop,start)
      if (pos = txt.rindex(pat))
        match = $&
        #pos = txt[0..(pos-1)].split('').length if pos > 0
        pos = _ktext_length(txt[0..(pos-1)]) if pos > 0
        if pat.kind_of? String
          #return [index(stop + " + #{pos} chars"), pat.split('').length]
          return [index(stop + " + #{pos} chars"), _ktext_length(pat), pat.dup]
        else
          #return [index(stop + " + #{pos} chars"), $&.split('').length]
          return [index(stop + " + #{pos} chars"), _ktext_length(match), match]
        end
      else
        return ["", 0]
      end
    else
      txt = get('1.0',start)
      if (pos = txt.rindex(pat))
        match = $&
        #pos = txt[0..(pos-1)].split('').length if pos > 0
        pos = _ktext_length(txt[0..(pos-1)]) if pos > 0
        if pat.kind_of? String
          #return [index("1.0 + #{pos} chars"), pat.split('').length]
          return [index("1.0 + #{pos} chars"), _ktext_length(pat), pat.dup]
        else
          #return [index("1.0 + #{pos} chars"), $&.split('').length]
          return [index("1.0 + #{pos} chars"), _ktext_length(match), match]
        end
      else
        txt = get('1.0','end - 1 char')
        if (pos = txt.rindex(pat))
          match = $&
          #pos = txt[0..(pos-1)].split('').length if pos > 0
          pos = _ktext_length(txt[0..(pos-1)]) if pos > 0
          if pat.kind_of? String
            #return [index("1.0 + #{pos} chars"), pat.split('').length]
            return [index("1.0 + #{pos} chars"), _ktext_length(pat), pat.dup]
          else
            #return [index("1.0 + #{pos} chars"), $&.split('').length]
            return [index("1.0 + #{pos} chars"), _ktext_length(match), match]
          end
        else
          return ["", 0]
        end
      end
    end
  end
scan_dragto(x, y)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 318
  def scan_dragto(x, y)
    tk_send_without_enc('scan', 'dragto', x, y)
    self
  end
scan_mark(x, y)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 314
  def scan_mark(x, y)
    tk_send_without_enc('scan', 'mark', x, y)
    self
  end
search(pat,start,stop=None)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 442
  def search(pat,start,stop=None)
    search_with_length(pat,start,stop)[0]
  end
search_with_length(pat,start,stop=None)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 385
  def search_with_length(pat,start,stop=None)
    pat = pat.chr if pat.kind_of? Integer
    if stop != None
      return ["", 0] if compare(start,'>=',stop)
      txt = get(start,stop)
      if (pos = txt.index(pat))
        match = $&
        #pos = txt[0..(pos-1)].split('').length if pos > 0
        pos = _ktext_length(txt[0..(pos-1)]) if pos > 0
        if pat.kind_of? String
          #return [index(start + " + #{pos} chars"), pat.split('').length]
          return [index(start + " + #{pos} chars"),
                  _ktext_length(pat), pat.dup]
        else
          #return [index(start + " + #{pos} chars"), $&.split('').length]
          return [index(start + " + #{pos} chars"),
                  _ktext_length(match), match]
        end
      else
        return ["", 0]
      end
    else
      txt = get(start,'end - 1 char')
      if (pos = txt.index(pat))
        match = $&
        #pos = txt[0..(pos-1)].split('').length if pos > 0
        pos = _ktext_length(txt[0..(pos-1)]) if pos > 0
        if pat.kind_of? String
          #return [index(start + " + #{pos} chars"), pat.split('').length]
          return [index(start + " + #{pos} chars"),
                  _ktext_length(pat), pat.dup]
        else
          #return [index(start + " + #{pos} chars"), $&.split('').length]
          return [index(start + " + #{pos} chars"),
                  _ktext_length(match), match]
        end
      else
        txt = get('1.0','end - 1 char')
        if (pos = txt.index(pat))
          match = $&
          #pos = txt[0..(pos-1)].split('').length if pos > 0
          pos = _ktext_length(txt[0..(pos-1)]) if pos > 0
          if pat.kind_of? String
            #return [index("1.0 + #{pos} chars"), pat.split('').length]
            return [index("1.0 + #{pos} chars"),
                    _ktext_length(pat), pat.dup]
          else
            #return [index("1.0 + #{pos} chars"), $&.split('').length]
            return [index("1.0 + #{pos} chars"), _ktext_length(match), match]
          end
        else
          return ["", 0]
        end
      end
    end
  end
see(index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 502
  def see(index)
    tk_send_without_enc('see', index)
    self
  end
set_mark(mark, index)

Alias for mark_set

tksearch(*args)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 345
  def tksearch(*args)
    # call 'search' subcommand of text widget
    #   args ::= [<array_of_opts>] <pattern> <start_index> [<stop_index>]
    # If <pattern> is regexp, then it must be a regular expression of Tcl
    if args[0].kind_of?(Array)
      opts = args.shift.collect{|opt| '-' + opt.to_s }
    else
      opts = []
    end

    opts << '--'

    ret = tk_send('search', *(opts + args))
    if ret == ""
      nil
    else
      ret
    end
  end
tksearch_with_count(*args)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 365
  def tksearch_with_count(*args)
    # call 'search' subcommand of text widget
    #   args ::= [<array_of_opts>] <var> <pattern> <start_index> [<stop_index>]
    # If <pattern> is regexp, then it must be a regular expression of Tcl
    if args[0].kind_of?(Array)
      opts = args.shift.collect{|opt| '-' + opt.to_s }
    else
      opts = []
    end

    opts << '-count' << args.shift << '--'

    ret = tk_send('search', *(opts + args))
    if ret == ""
      nil
    else
      ret
    end
  end
unset_mark(*marks)

Alias for mark_unset

xview(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 509
  def xview(*index)
    if index.size == 0
      list(tk_send_without_enc('xview'))
    else
      tk_send_without_enc('xview', *index)
      self
    end
  end
xview_moveto(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 517
  def xview_moveto(*index)
    xview('moveto', *index)
  end
xview_scroll(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 520
  def xview_scroll(*index)
    xview('scroll', *index)
  end
yview(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 524
  def yview(*index)
    if index.size == 0
      list(tk_send_without_enc('yview'))
    else
      tk_send_without_enc('yview', *index)
      self
    end
  end
yview_moveto(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 532
  def yview_moveto(*index)
    yview('moveto', *index)
  end
yview_scroll(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/scrolledtext.rb, line 535
  def yview_scroll(*index)
    yview('scroll', *index)
  end


Class: Tk::Iwidgets::Scrolledwidget

Class | Tk::Iwidgets::Scrolledwidget
In: | tk/lib/tkextlib/iwidgets/scrolledwidget.rb
Parent: | Tk::Iwidgets::Labeledwidget

Constants

TkCommandNames | = | ['::iwidgets::scrolledwidget'.freeze].freeze
WidgetClassName | = | 'Scrolledwidget'.freeze


Class: Tk::Iwidgets::Selectionbox

Class | Tk::Iwidgets::Selectionbox
In: | tk/lib/tkextlib/iwidgets/selectionbox.rb
Parent: | Tk::Itk::Widget

Methods

child_site clear_items clear_selection curselection delete get index insert_items insert_selection nearest scan_dragto scan_mark select_item selection_anchor selection_clear selection_includes selection_set size

Constants

TkCommandNames | = | ['::iwidgets::selectionbox'.freeze].freeze
WidgetClassName | = | 'Selectionbox'.freeze

Public Instance methods

child_site()

[Source]

# File tk/lib/tkextlib/iwidgets/selectionbox.rb, line 31
  def child_site
    window(tk_call(@path, 'childsite'))
  end
clear_items()

[Source]

# File tk/lib/tkextlib/iwidgets/selectionbox.rb, line 35
  def clear_items
    tk_call(@path, 'clear', 'items')
    self
  end
clear_selection()

[Source]

# File tk/lib/tkextlib/iwidgets/selectionbox.rb, line 40
  def clear_selection
    tk_call(@path, 'clear', 'selection')
    self
  end
curselection()

based on TkListbox ( and TkTextWin )

[Source]

# File tk/lib/tkextlib/iwidgets/selectionbox.rb, line 63
  def curselection
    list(tk_send_without_enc('curselection'))
  end
delete(first, last=None)

[Source]

# File tk/lib/tkextlib/iwidgets/selectionbox.rb, line 66
  def delete(first, last=None)
    tk_send_without_enc('delete', first, last)
    self
  end
get()

[Source]

# File tk/lib/tkextlib/iwidgets/selectionbox.rb, line 45
  def get
    tk_call(@path, 'get')
  end
index(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/selectionbox.rb, line 70
  def index(idx)
    tk_send_without_enc('index', idx).to_i
  end
insert_items(idx, *args)

[Source]

# File tk/lib/tkextlib/iwidgets/selectionbox.rb, line 49
  def insert_items(idx, *args)
    tk_call(@path, 'insert', 'items', idx, *args)
  end
insert_selection(pos, text)

[Source]

# File tk/lib/tkextlib/iwidgets/selectionbox.rb, line 53
  def insert_selection(pos, text)
    tk_call(@path, 'insert', 'selection', pos, text)
  end
nearest(y)

[Source]

# File tk/lib/tkextlib/iwidgets/selectionbox.rb, line 73
  def nearest(y)
    tk_send_without_enc('nearest', y).to_i
  end
scan_dragto(x, y)

[Source]

# File tk/lib/tkextlib/iwidgets/selectionbox.rb, line 80
  def scan_dragto(x, y)
    tk_send_without_enc('scan', 'dragto', x, y)
    self
  end
scan_mark(x, y)

[Source]

# File tk/lib/tkextlib/iwidgets/selectionbox.rb, line 76
  def scan_mark(x, y)
    tk_send_without_enc('scan', 'mark', x, y)
    self
  end
select_item()

[Source]

# File tk/lib/tkextlib/iwidgets/selectionbox.rb, line 57
  def select_item
    tk_call(@path, 'selectitem')
    self
  end
selection_anchor(index)

[Source]

# File tk/lib/tkextlib/iwidgets/selectionbox.rb, line 84
  def selection_anchor(index)
    tk_send_without_enc('selection', 'anchor', index)
    self
  end
selection_clear(first, last=None)

[Source]

# File tk/lib/tkextlib/iwidgets/selectionbox.rb, line 88
  def selection_clear(first, last=None)
    tk_send_without_enc('selection', 'clear', first, last)
    self
  end
selection_includes(index)

[Source]

# File tk/lib/tkextlib/iwidgets/selectionbox.rb, line 92
  def selection_includes(index)
    bool(tk_send_without_enc('selection', 'includes', index))
  end
selection_set(first, last=None)

[Source]

# File tk/lib/tkextlib/iwidgets/selectionbox.rb, line 95
  def selection_set(first, last=None)
    tk_send_without_enc('selection', 'set', first, last)
    self
  end
size()

[Source]

# File tk/lib/tkextlib/iwidgets/selectionbox.rb, line 99
  def size
    tk_send_without_enc('size').to_i
  end


Class: Tk::Iwidgets::Selectiondialog

Class | Tk::Iwidgets::Selectiondialog
In: | tk/lib/tkextlib/iwidgets/selectiondialog.rb
Parent: | Tk::Iwidgets::Dialog

Methods

child_site clear_items clear_selection curselection delete get index insert_items insert_selection nearest scan_dragto scan_mark select_item selection_anchor selection_clear selection_includes selection_set size

Constants

TkCommandNames | = | ['::iwidgets::selectiondialog'.freeze].freeze
WidgetClassName | = | 'Selectiondialog'.freeze

Public Instance methods

child_site()

[Source]

# File tk/lib/tkextlib/iwidgets/selectiondialog.rb, line 21
  def child_site
    window(tk_call(@path, 'childsite'))
  end
clear_items()

[Source]

# File tk/lib/tkextlib/iwidgets/selectiondialog.rb, line 25
  def clear_items
    tk_call(@path, 'clear', 'items')
    self
  end
clear_selection()

[Source]

# File tk/lib/tkextlib/iwidgets/selectiondialog.rb, line 30
  def clear_selection
    tk_call(@path, 'clear', 'selection')
    self
  end
curselection()

based on TkListbox ( and TkTextWin )

[Source]

# File tk/lib/tkextlib/iwidgets/selectiondialog.rb, line 53
  def curselection
    list(tk_send_without_enc('curselection'))
  end
delete(first, last=None)

[Source]

# File tk/lib/tkextlib/iwidgets/selectiondialog.rb, line 56
  def delete(first, last=None)
    tk_send_without_enc('delete', first, last)
    self
  end
get()

[Source]

# File tk/lib/tkextlib/iwidgets/selectiondialog.rb, line 35
  def get
    tk_call(@path, 'get')
  end
index(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/selectiondialog.rb, line 60
  def index(idx)
    tk_send_without_enc('index', idx).to_i
  end
insert_items(idx, *args)

[Source]

# File tk/lib/tkextlib/iwidgets/selectiondialog.rb, line 39
  def insert_items(idx, *args)
    tk_call(@path, 'insert', 'items', idx, *args)
  end
insert_selection(pos, text)

[Source]

# File tk/lib/tkextlib/iwidgets/selectiondialog.rb, line 43
  def insert_selection(pos, text)
    tk_call(@path, 'insert', 'selection', pos, text)
  end
nearest(y)

[Source]

# File tk/lib/tkextlib/iwidgets/selectiondialog.rb, line 63
  def nearest(y)
    tk_send_without_enc('nearest', y).to_i
  end
scan_dragto(x, y)

[Source]

# File tk/lib/tkextlib/iwidgets/selectiondialog.rb, line 70
  def scan_dragto(x, y)
    tk_send_without_enc('scan', 'dragto', x, y)
    self
  end
scan_mark(x, y)

[Source]

# File tk/lib/tkextlib/iwidgets/selectiondialog.rb, line 66
  def scan_mark(x, y)
    tk_send_without_enc('scan', 'mark', x, y)
    self
  end
select_item()

[Source]

# File tk/lib/tkextlib/iwidgets/selectiondialog.rb, line 47
  def select_item
    tk_call(@path, 'selectitem')
    self
  end
selection_anchor(index)

[Source]

# File tk/lib/tkextlib/iwidgets/selectiondialog.rb, line 74
  def selection_anchor(index)
    tk_send_without_enc('selection', 'anchor', index)
    self
  end
selection_clear(first, last=None)

[Source]

# File tk/lib/tkextlib/iwidgets/selectiondialog.rb, line 78
  def selection_clear(first, last=None)
    tk_send_without_enc('selection', 'clear', first, last)
    self
  end
selection_includes(index)

[Source]

# File tk/lib/tkextlib/iwidgets/selectiondialog.rb, line 82
  def selection_includes(index)
    bool(tk_send_without_enc('selection', 'includes', index))
  end
selection_set(first, last=None)

[Source]

# File tk/lib/tkextlib/iwidgets/selectiondialog.rb, line 85
  def selection_set(first, last=None)
    tk_send_without_enc('selection', 'set', first, last)
    self
  end
size()

[Source]

# File tk/lib/tkextlib/iwidgets/selectiondialog.rb, line 89
  def size
    tk_send_without_enc('size').to_i
  end


Class: Tk::Iwidgets::Shell

Class | Tk::Iwidgets::Shell
In: | tk/lib/tkextlib/iwidgets/shell.rb
Parent: | Tk::Itk::Toplevel

Methods

activate center child_site deactivate

Constants

TkCommandNames | = | ['::iwidgets::shell'.freeze].freeze
WidgetClassName | = | 'Shell'.freeze

Public Instance methods

activate()

[Source]

# File tk/lib/tkextlib/iwidgets/shell.rb, line 21
  def activate
    tk_call(@path, 'activate')  # may return val of deactibate method
  end
center(win=None)

[Source]

# File tk/lib/tkextlib/iwidgets/shell.rb, line 25
  def center(win=None)
    tk_call(@path, 'center', win)
    self
  end
child_site()

[Source]

# File tk/lib/tkextlib/iwidgets/shell.rb, line 30
  def child_site
    window(tk_call(@path, 'childsite'))
  end
deactivate(val=None)

[Source]

# File tk/lib/tkextlib/iwidgets/shell.rb, line 34
  def deactivate(val=None)
    tk_call(@path, 'deactivate', val)
    self
  end


Class: Tk::Iwidgets::Spindate

Class | Tk::Iwidgets::Spindate
In: | tk/lib/tkextlib/iwidgets/spindate.rb
Parent: | Tk::Itk::Widget

Methods

get get_clicks get_string show show_now

Constants

TkCommandNames | = | ['::iwidgets::spindate'.freeze].freeze
WidgetClassName | = | 'Spindate'.freeze

Public Instance methods

get()

Alias for get_string

get_clicks()

[Source]

# File tk/lib/tkextlib/iwidgets/spindate.rb, line 36
  def get_clicks
    number(tk_call(@path, 'get', '-clicks'))
  end
get_string()

[Source]

# File tk/lib/tkextlib/iwidgets/spindate.rb, line 31
  def get_string
    tk_call(@path, 'get', '-string')
  end
show(date=None)

[Source]

# File tk/lib/tkextlib/iwidgets/spindate.rb, line 40
  def show(date=None)
    tk_call(@path, 'show', date)
    self
  end
show_now()

[Source]

# File tk/lib/tkextlib/iwidgets/spindate.rb, line 44
  def show_now
    tk_call(@path, 'show', 'now')
    self
  end


Class: Tk::Iwidgets::Spinint

Class | Tk::Iwidgets::Spinint
In: | tk/lib/tkextlib/iwidgets/spinint.rb
Parent: | Tk::Iwidgets::Spinner

Constants

TkCommandNames | = | ['::iwidgets::spinint'.freeze].freeze
WidgetClassName | = | 'Spinint'.freeze


Class: Tk::Iwidgets::Spinner

Class | Tk::Iwidgets::Spinner
In: | tk/lib/tkextlib/iwidgets/spinner.rb
Parent: | Tk::Iwidgets::Labeledwidget

Methods

__validation_class_list clear cursor= delete down dragto get icursor index insert mark selection_adjust selection_clear selection_from selection_present selection_range selection_to set up value value= xview xview_moveto xview_scroll

Included Modules

Tk::ValidateConfigure

Classes and Modules

Class Tk::Iwidgets::Spinner::EntryfieldValidate

Constants

TkCommandNames | = | ['::iwidgets::spinner'.freeze].freeze
WidgetClassName | = | 'Spinner'.freeze

Public Instance methods

__validation_class_list()

[Source]

# File tk/lib/tkextlib/iwidgets/spinner.rb, line 48
  def __validation_class_list
    super() << EntryfieldValidate
  end
clear()

[Source]

# File tk/lib/tkextlib/iwidgets/spinner.rb, line 66
  def clear
    tk_call_without_enc(@path, 'clear')
    self
  end
cursor=(index)

[Source]

# File tk/lib/tkextlib/iwidgets/spinner.rb, line 87
  def cursor=(index)
    tk_send_without_enc('icursor', index)
    #self
    index
  end
delete(first, last=None)

[Source]

# File tk/lib/tkextlib/iwidgets/spinner.rb, line 71
  def delete(first, last=None)
    tk_send_without_enc('delete', first, last)
    self
  end
down()

[Source]

# File tk/lib/tkextlib/iwidgets/spinner.rb, line 61
  def down
    tk_call_without_enc(@path, 'down')
    self
  end
dragto(pos)

[Source]

# File tk/lib/tkextlib/iwidgets/spinner.rb, line 107
  def dragto(pos)
    tk_send_without_enc('scan', 'dragto', pos)
    self
  end
get()

Alias for value

icursor(index)

Alias for cursor=

index(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/spinner.rb, line 94
  def index(idx)
    number(tk_send_without_enc('index', idx))
  end
insert(pos,text)

[Source]

# File tk/lib/tkextlib/iwidgets/spinner.rb, line 98
  def insert(pos,text)
    tk_send_without_enc('insert', pos, _get_eval_enc_str(text))
    self
  end
mark(pos)

[Source]

# File tk/lib/tkextlib/iwidgets/spinner.rb, line 103
  def mark(pos)
    tk_send_without_enc('scan', 'mark', pos)
    self
  end
selection_adjust(index)

[Source]

# File tk/lib/tkextlib/iwidgets/spinner.rb, line 111
  def selection_adjust(index)
    tk_send_without_enc('selection', 'adjust', index)
    self
  end
selection_clear()

[Source]

# File tk/lib/tkextlib/iwidgets/spinner.rb, line 115
  def selection_clear
    tk_send_without_enc('selection', 'clear')
    self
  end
selection_from(index)

[Source]

# File tk/lib/tkextlib/iwidgets/spinner.rb, line 119
  def selection_from(index)
    tk_send_without_enc('selection', 'from', index)
    self
  end
selection_present()

[Source]

# File tk/lib/tkextlib/iwidgets/spinner.rb, line 123
  def selection_present()
    bool(tk_send_without_enc('selection', 'present'))
  end
selection_range(s, e)

[Source]

# File tk/lib/tkextlib/iwidgets/spinner.rb, line 126
  def selection_range(s, e)
    tk_send_without_enc('selection', 'range', s, e)
    self
  end
selection_to(index)

[Source]

# File tk/lib/tkextlib/iwidgets/spinner.rb, line 130
  def selection_to(index)
    tk_send_without_enc('selection', 'to', index)
    self
  end
set(val)

Alias for value=

up()

[Source]

# File tk/lib/tkextlib/iwidgets/spinner.rb, line 56
  def up
    tk_call_without_enc(@path, 'up')
    self
  end
value()

[Source]

# File tk/lib/tkextlib/iwidgets/spinner.rb, line 76
  def value
    _fromUTF8(tk_send_without_enc('get'))
  end
value=(val)

[Source]

# File tk/lib/tkextlib/iwidgets/spinner.rb, line 79
  def value= (val)
    tk_send_without_enc('delete', 0, 'end')
    tk_send_without_enc('insert', 0, _get_eval_enc_str(val))
    val
  end
xview(*index)

based on tk/scrollable.rb

[Source]

# File tk/lib/tkextlib/iwidgets/spinner.rb, line 136
  def xview(*index)
    if index.size == 0
      list(tk_send_without_enc('xview'))
    else
      tk_send_without_enc('xview', *index)
      self
    end
  end
xview_moveto(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/spinner.rb, line 144
  def xview_moveto(*index)
    xview('moveto', *index)
  end
xview_scroll(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/spinner.rb, line 147
  def xview_scroll(*index)
    xview('scroll', *index)
  end


Class: Tk::Iwidgets::Spinner::EntryfieldValidate

Class | Tk::Iwidgets::Spinner::EntryfieldValidate
In: | tk/lib/tkextlib/iwidgets/spinner.rb
Parent: | TkValidateCommand

Methods

_config_keys

Classes and Modules

Class Tk::Iwidgets::Spinner::EntryfieldValidate::ValidateArgs

Public Class methods

_config_keys()

[Source]

# File tk/lib/tkextlib/iwidgets/spinner.rb, line 43
    def self._config_keys
      ['validate', 'invalid']
    end


Class: Tk::Iwidgets::Spinner::EntryfieldValidate::ValidateArgs

Class | Tk::Iwidgets::Spinner::EntryfieldValidate::ValidateArgs
In: | tk/lib/tkextlib/iwidgets/spinner.rb
Parent: | TkUtil::CallbackSubst

class CalCmdArgs < TkUtil::CallbackSubst

Constants

KEY_TBL | = | [ [ ?c, ?s, :char ], [ ?P, ?s, :post ], [ ?S, ?s, :current ], [ ?W, ?w, :widget ], nil
PROC_TBL | = | [ [ ?s, TkComm.method(:string) ], [ ?w, TkComm.method(:window) ], nil


Class: Tk::Iwidgets::Spintime

Class | Tk::Iwidgets::Spintime
In: | tk/lib/tkextlib/iwidgets/spintime.rb
Parent: | Tk::Itk::Widget

Methods

get get_clicks get_string show show_now

Constants

TkCommandNames | = | ['::iwidgets::spintime'.freeze].freeze
WidgetClassName | = | 'Spintime'.freeze

Public Instance methods

get()

Alias for get_string

get_clicks()

[Source]

# File tk/lib/tkextlib/iwidgets/spintime.rb, line 36
  def get_clicks
    number(tk_call(@path, 'get', '-clicks'))
  end
get_string()

[Source]

# File tk/lib/tkextlib/iwidgets/spintime.rb, line 31
  def get_string
    tk_call(@path, 'get', '-string')
  end
show(date=None)

[Source]

# File tk/lib/tkextlib/iwidgets/spintime.rb, line 40
  def show(date=None)
    tk_call(@path, 'show', date)
    self
  end
show_now()

[Source]

# File tk/lib/tkextlib/iwidgets/spintime.rb, line 44
  def show_now
    tk_call(@path, 'show', 'now')
    self
  end


Class: Tk::Iwidgets::Tabnotebook

Class | Tk::Iwidgets::Tabnotebook
In: | tk/lib/tkextlib/iwidgets/tabnotebook.rb
Parent: | Tk::Itk::Widget

Methods

add child_site child_site_list delete index insert new next prev scrollbar scrollcommand select tagid view view_moveto view_scroll xscrollbar xscrollcommand xview xview_moveto xview_scroll yscrollbar yscrollcommand yview yview_moveto yview_scroll

Included Modules

TkItemConfigMethod

Constants

TkCommandNames | = | ['::iwidgets::tabnotebook'.freeze].freeze
WidgetClassName | = | 'Tabnotebook'.freeze

External Aliases

itemcget | -> | pagecget
itemconfigure | -> | pageconfigure
itemconfiginfo | -> | pageconfiginfo
current_itemconfiginfo | -> | current_pageconfiginfo

Public Class methods

new(*args)

[Source]

# File tk/lib/tkextlib/iwidgets/tabnotebook.rb, line 69
  def initialize(*args)
    super(*args)
    @tabset = self.component_widget('tabset')
  end

Public Instance methods

add(keys={})

[Source]

# File tk/lib/tkextlib/iwidgets/tabnotebook.rb, line 74
  def add(keys={})
    window(tk_call(@path, 'add', *hash_kv(keys)))
  end
child_site(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/tabnotebook.rb, line 82
  def child_site(idx)
    window(tk_call(@path, 'childsite', index(idx)))
  end
child_site_list()

[Source]

# File tk/lib/tkextlib/iwidgets/tabnotebook.rb, line 78
  def child_site_list
    list(tk_call(@path, 'childsite'))
  end
delete(idx1, idx2=nil)

[Source]

# File tk/lib/tkextlib/iwidgets/tabnotebook.rb, line 86
  def delete(idx1, idx2=nil)
    if idx2
      tk_call(@path, 'delete', index(idx1), index(idx2))
    else
      tk_call(@path, 'delete', index(idx1))
    end
    self
  end
index(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/tabnotebook.rb, line 95
  def index(idx)
    #number(tk_call(@path, 'index', tagid(idx)))
    @tabset.index(tagid(idx))
  end
insert(idx, keys={})

[Source]

# File tk/lib/tkextlib/iwidgets/tabnotebook.rb, line 100
  def insert(idx, keys={})
    window(tk_call(@path, 'insert', index(idx), *hash_kv(keys)))
  end
next()

[Source]

# File tk/lib/tkextlib/iwidgets/tabnotebook.rb, line 104
  def next
    tk_call(@path, 'next')
    self
  end
prev()

[Source]

# File tk/lib/tkextlib/iwidgets/tabnotebook.rb, line 109
  def prev
    tk_call(@path, 'prev')
    self
  end
scrollbar(bar=nil)

Alias for yscrollbar

scrollcommand(cmd=Proc.new)

[Source]

# File tk/lib/tkextlib/iwidgets/tabnotebook.rb, line 119
  def scrollcommand(cmd=Proc.new)
    configure_cmd 'scrollcommand', cmd
    self
  end
select(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/tabnotebook.rb, line 114
  def select(idx)
    tk_call(@path, 'select', index(idx))
    self
  end
tagid(tagOrId)

[Source]

# File tk/lib/tkextlib/iwidgets/tabnotebook.rb, line 40
  def tagid(tagOrId)
    if tagOrId.kind_of?(Tk::Itk::Component)
      tagOrId.name
    else
      #_get_eval_string(tagOrId)
      tagOrId
    end
  end
view(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/tabnotebook.rb, line 148
  def view(*index)
    if index.size == 0
      window(tk_send_without_enc('view'))
    else
      tk_send_without_enc('view', *index)
      self
    end
  end
view_moveto(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/tabnotebook.rb, line 159
  def view_moveto(*index)
    view('moveto', *index)
  end
view_scroll(*index)

[Source]

# File tk/lib/tkextlib/iwidgets/tabnotebook.rb, line 164
  def view_scroll(*index)
    view('scroll', *index)
  end
xscrollbar(bar=nil)

[Source]

# File tk/lib/tkextlib/iwidgets/tabnotebook.rb, line 126
  def xscrollbar(bar=nil)
    if bar
      @scrollbar = bar
      @scrollbar.orient 'horizontal'
      self.scrollcommand {|*arg| @scrollbar.set(*arg)}
      @scrollbar.command {|*arg| self.xview(*arg)}
      Tk.update  # avoid scrollbar trouble
    end
    @scrollbar
  end
xscrollcommand(cmd=Proc.new)

Alias for scrollcommand

xview(*index)

Alias for view

xview_moveto(*index)

Alias for view_moveto

xview_scroll(*index)

Alias for view_scroll

yscrollbar(bar=nil)

[Source]

# File tk/lib/tkextlib/iwidgets/tabnotebook.rb, line 136
  def yscrollbar(bar=nil)
    if bar
      @scrollbar = bar
      @scrollbar.orient 'vertical'
      self.scrollcommand {|*arg| @scrollbar.set(*arg)}
      @scrollbar.command {|*arg| self.yview(*arg)}
      Tk.update  # avoid scrollbar trouble
    end
    @scrollbar
  end
yscrollcommand(cmd=Proc.new)

Alias for scrollcommand

yview(*index)

Alias for view

yview_moveto(*index)

Alias for view_moveto

yview_scroll(*index)

Alias for view_scroll


Class: Tk::Iwidgets::Tabset

Class | Tk::Iwidgets::Tabset
In: | tk/lib/tkextlib/iwidgets/tabset.rb
Parent: | Tk::Itk::Widget

Methods

add delete index insert next prev select tagid

Included Modules

TkItemConfigMethod

Constants

TkCommandNames | = | ['::iwidgets::tabset'.freeze].freeze
WidgetClassName | = | 'Tabset'.freeze

External Aliases

itemcget | -> | tabcget
itemconfigure | -> | tabconfigure
itemconfiginfo | -> | tabconfiginfo
current_itemconfiginfo | -> | current_tabconfiginfo

Public Instance methods

add(keys={})

[Source]

# File tk/lib/tkextlib/iwidgets/tabset.rb, line 64
  def add(keys={})
    window(tk_call(@path, 'add', *hash_kv(keys)))
  end
delete(idx1, idx2=nil)

[Source]

# File tk/lib/tkextlib/iwidgets/tabset.rb, line 68
  def delete(idx1, idx2=nil)
    if idx2
      tk_call(@path, 'delete', index(idx1), index(idx2))
    else
      tk_call(@path, 'delete', index(idx1))
    end
    self
  end
index(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/tabset.rb, line 77
  def index(idx)
    number(tk_call(@path, 'index', tagid(idx)))
  end
insert(idx, keys={})

[Source]

# File tk/lib/tkextlib/iwidgets/tabset.rb, line 81
  def insert(idx, keys={})
    window(tk_call(@path, 'insert', index(idx), *hash_kv(keys)))
  end
next()

[Source]

# File tk/lib/tkextlib/iwidgets/tabset.rb, line 85
  def next
    tk_call(@path, 'next')
    self
  end
prev()

[Source]

# File tk/lib/tkextlib/iwidgets/tabset.rb, line 90
  def prev
    tk_call(@path, 'prev')
    self
  end
select(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/tabset.rb, line 95
  def select(idx)
    tk_call(@path, 'select', index(idx))
    self
  end
tagid(tagOrId)

[Source]

# File tk/lib/tkextlib/iwidgets/tabset.rb, line 35
  def tagid(tagOrId)
    if tagOrId.kind_of?(Tk::Itk::Component)
      tagOrId.name
    else
      #_get_eval_string(tagOrId)
      tagOrId
    end
  end


Class: Tk::Iwidgets::Timeentry

Class | Tk::Iwidgets::Timeentry
In: | tk/lib/tkextlib/iwidgets/timeentry.rb
Parent: | Tk::Iwidgets::Timefield

Constants

TkCommandNames | = | ['::iwidgets::timeentry'.freeze].freeze
WidgetClassName | = | 'Timeentry'.freeze


Class: Tk::Iwidgets::Timefield

Class | Tk::Iwidgets::Timefield
In: | tk/lib/tkextlib/iwidgets/timefield.rb
Parent: | Tk::Iwidgets::Labeledwidget

Methods

get get_clicks get_string isvalid? show show_now valid?

Constants

TkCommandNames | = | ['::iwidgets::timefield'.freeze].freeze
WidgetClassName | = | 'Timefield'.freeze

Public Instance methods

get()

Alias for get_string

get_clicks()

[Source]

# File tk/lib/tkextlib/iwidgets/timefield.rb, line 41
  def get_clicks
    number(tk_call(@path, 'get', '-clicks'))
  end
get_string()

[Source]

# File tk/lib/tkextlib/iwidgets/timefield.rb, line 36
  def get_string
    tk_call(@path, 'get', '-string')
  end
isvalid?()

Alias for valid?

show(time=None)

[Source]

# File tk/lib/tkextlib/iwidgets/timefield.rb, line 50
  def show(time=None)
    tk_call(@path, 'show', time)
    self
  end
show_now()

[Source]

# File tk/lib/tkextlib/iwidgets/timefield.rb, line 54
  def show_now
    tk_call(@path, 'show', 'now')
    self
  end
valid?()

[Source]

# File tk/lib/tkextlib/iwidgets/timefield.rb, line 45
  def valid?
    bool(tk_call(@path, 'isvalid'))
  end


Class: Tk::Iwidgets::Toolbar

Class | Tk::Iwidgets::Toolbar
In: | tk/lib/tkextlib/iwidgets/toolbar.rb
Parent: | Tk::Itk::Widget

Methods

add delete index insert tagid

Included Modules

TkItemConfigMethod

Constants

TkCommandNames | = | ['::iwidgets::toolbar'.freeze].freeze
WidgetClassName | = | 'Toolbar'.freeze

Public Instance methods

add(type, tag=nil, keys={})

[Source]

# File tk/lib/tkextlib/iwidgets/toolbar.rb, line 71
  def add(type, tag=nil, keys={})
    if tag.kind_of?(Hash)
      keys = tag
      tag = nil
    end
    if tag
      tag = Tk::Itk::Component.new(self, tagid(tag))
    else
      tag = Tk::Itk::Component.new(self)
    end
    window(tk_call(@path, 'add', type, tagid(tag), *hash_kv(keys)))
    tag
  end
delete(idx1, idx2=nil)

[Source]

# File tk/lib/tkextlib/iwidgets/toolbar.rb, line 85
  def delete(idx1, idx2=nil)
    if idx2
      tk_call(@path, 'delete', index(idx1), index(idx2))
    else
      tk_call(@path, 'delete', index(idx1))
    end
    self
  end
index(idx)

[Source]

# File tk/lib/tkextlib/iwidgets/toolbar.rb, line 94
  def index(idx)
    number(tk_call(@path, 'index', tagid(idx)))
  end
insert(idx, type, tag=nil, keys={})

[Source]

# File tk/lib/tkextlib/iwidgets/toolbar.rb, line 98
  def insert(idx, type, tag=nil, keys={})
    if tag.kind_of?(Hash)
      keys = tag
      tag = nil
    end
    if tag
      tag = Tk::Itk::Component.new(self, tagid(tag))
    else
      tag = Tk::Itk::Component.new(self)
    end
    window(tk_call(@path, 'insert', index(idx), type,
                   tagid(tag), *hash_kv(keys)))
    tag
  end
tagid(tagOrId)

[Source]

# File tk/lib/tkextlib/iwidgets/toolbar.rb, line 45
  def tagid(tagOrId)
    if tagOrId.kind_of?(Tk::Itk::Component)
      tagOrId.name
    else
      #_get_eval_string(tagOrId)
      tagOrId
    end
  end


Class: Tk::Iwidgets::Watch

Class | Tk::Iwidgets::Watch
In: | tk/lib/tkextlib/iwidgets/watch.rb
Parent: | Tk::Itk::Widget

Methods

get get_clicks get_string show show_now watch

Constants

TkCommandNames | = | ['::iwidgets::watch'.freeze].freeze
WidgetClassName | = | 'Watch'.freeze

Public Instance methods

get()

Alias for get_string

get_clicks()

[Source]

# File tk/lib/tkextlib/iwidgets/watch.rb, line 37
  def get_clicks
    number(tk_call(@path, 'get', '-clicks'))
  end
get_string()

[Source]

# File tk/lib/tkextlib/iwidgets/watch.rb, line 32
  def get_string
    tk_call(@path, 'get', '-string')
  end
show(time=None)

[Source]

# File tk/lib/tkextlib/iwidgets/watch.rb, line 41
  def show(time=None)
    tk_call(@path, 'show', time)
    self
  end
show_now()

[Source]

# File tk/lib/tkextlib/iwidgets/watch.rb, line 45
  def show_now
    tk_call(@path, 'show', 'now')
    self
  end
watch(*args)

[Source]

# File tk/lib/tkextlib/iwidgets/watch.rb, line 50
  def watch(*args)
    unless args.empty?
      tk_call(@path, 'watch', *args)
    end
    component_path('canvas')
  end


Class: Tk::OptionObj

Class | Tk::OptionObj
In: | tk/lib/tk/optionobj.rb
Parent: | Hash

Methods

+ [] []= apply assign cget configure new notify observ_info observs replace store unassign update

Included Modules

TkUtil

External Aliases

update -> update_without_notify

Public Class methods

new(hash = nil)

[Source]

# File tk/lib/tk/optionobj.rb, line 16
    def initialize(hash = nil)
      super()
      @observ = []
      update_without_notify(_symbolkey2str(hash)) if hash
    end

Public Instance methods

+(hash)

[Source]

# File tk/lib/tk/optionobj.rb, line 162
    def +(hash)
      unless hash.kind_of?(Hash)
        fail ArgumentError, "expect a Hash"
      end
      new_obj = self.dup
      new_obj.update_without_notify(_symbolkey2str(hash))
      new_obj
    end
[](key)

[Source]

# File tk/lib/tk/optionobj.rb, line 186
    def [](key)
      super(key.to_s)
    end
[]=(key, val)

[Source]

# File tk/lib/tk/optionobj.rb, line 196
    def []=(key, val)
      store(key,val)
    end
apply(target = nil)

Alias for notify

assign(*wins)

[Source]

# File tk/lib/tk/optionobj.rb, line 58
    def assign(*wins)
      # win :=
      #   widget             #==> call widget.configure(hash)
      #   [widget]           #==> call widget.configure(hash)
      #   [widget, nil, {src=>target, ... }]
      #                      #==> call widget.configure(hash)
      #                               with converting hash-key
      #   [widget, method]   #==> call widget.method(hash)
      #   [widget, method, {src=>target, ... }]
      #                      #==> call widget.method(hash)
      #                               with converting hash-key
      #   [widget [receiver, method, arg, ... ]]
      #                      #==> call receiver.method(arg, ... , hash)
      #   [widget [receiver, method, arg, ... ], {src=>target, ... }]
      #                      #==> call receiver.method(arg, ... , hash)
      #                               with onverting hash-key
      #
      # src := option_name_on_optobj
      #
      # target :=
      #   nil                #==> not use the src
      #   option_name_on_target_widget
      #   [ option_name_on_target_widget, ... ]
      #                      #==> set all of them
      #
      wins.each{|win|
        _remove_win(win)
        @observ << win
        notify(win)
      }
      self
    end
cget(key)

Alias for #[]

configure(key, value=nil)

[Source]

# File tk/lib/tk/optionobj.rb, line 178
    def configure(key, value=nil)
      if key.kind_of?(Hash)
        update(key)
      else
        store(key,value)
      end
    end
notify(target = nil)

[Source]

# File tk/lib/tk/optionobj.rb, line 98
    def notify(target = nil)
      if target
        targets = [target]
      elsif @observ.empty?
        return self
      else
        targets = @observ.dup
      end

      return self if empty?

      org_hash = _symbolkey2str(self)

      targets.each{|win|
        widget = receiver = win
        hash = org_hash
        begin
          if win.kind_of?(Array)
            widget, method, conv_tbl = win
            receiver = widget

            if conv_tbl
              hash = {}
              org_hash.each{|key, val|
                key = conv_tbl[key] if conv_tbl.key?(key)
                next unless key
                if key.kind_of?(Array)
                  key.each{|k| hash[k] = val}
                else
                  hash[key] = val
                end
              }
            end

            if method.kind_of?(Array)
              receiver, method, *args = method
              receiver.__send__(method, *(args << hash))
            elsif method
              widget.__send__(method, hash)
            else
              widget.configure(hash)
            end

          else
            widget.configure(self)
          end
        rescue => e
          if ( ( widget.kind_of?(TkObject) \
                && widget.respond_to?('exist?') \
                && ! receiver.exist? ) \
            || ( receiver.kind_of?(TkObject) \
                && receiver.respond_to?('exist?') \
                && ! receiver.exist? ) )
            @observ.delete(win)
          else
            fail e
          end
        end
      }

      self
    end
observ_info()

[Source]

# File tk/lib/tk/optionobj.rb, line 22
    def observ_info
      @observ.dup
    end
observs()

[Source]

# File tk/lib/tk/optionobj.rb, line 26
    def observs
      @observ.collect{|win|
        if win.kind_of?(Array)
          win[0]
        else
          win
        end
      }
    end
replace(hash)

[Source]

# File tk/lib/tk/optionobj.rb, line 200
    def replace(hash)
      super(_symbolkey2str(hash))
      notify
    end
store(key, val)

[Source]

# File tk/lib/tk/optionobj.rb, line 191
    def store(key, val)
      key = key.to_s
      super(key, val)
      notify
    end
unassign(*wins)

[Source]

# File tk/lib/tk/optionobj.rb, line 91
    def unassign(*wins)
      wins.each{|win|
        _remove_win(win)
      }
      self
    end
update(hash)

[Source]

# File tk/lib/tk/optionobj.rb, line 173
    def update(hash)
      update_without_notify(_symbolkey2str(hash))
      notify
    end


Module: Tk::Scrollable

Module | Tk::Scrollable
In: | tk/lib/tkextlib/tcllib/autoscroll.rb tk/lib/tk/scrollable.rb

Methods

autoscroll unautoscroll

Included Modules

X_Scrollable Y_Scrollable

Public Instance methods

autoscroll(mode = nil)

[Source]

# File tk/lib/tkextlib/tcllib/autoscroll.rb, line 64
    def autoscroll(mode = nil)
      case mode
      when :x, 'x'
        if @xscrollbar
          Tk::Tcllib::Autoscroll.autoscroll(@xscrollbar)
        end
      when :y, 'y'
        if @yscrollbar
          Tk::Tcllib::Autoscroll.autoscroll(@yscrollbar)
        end
      when nil, :both, 'both'
        if @xscrollbar
          Tk::Tcllib::Autoscroll.autoscroll(@xscrollbar)
        end
        if @yscrollbar
          Tk::Tcllib::Autoscroll.autoscroll(@yscrollbar)
        end
      else
        fail ArgumentError, "'x', 'y' or 'both' (String or Symbol) is expected"
      end
      self
    end
unautoscroll(mode = nil)

[Source]

# File tk/lib/tkextlib/tcllib/autoscroll.rb, line 86
    def unautoscroll(mode = nil)
      case mode
      when :x, 'x'
        if @xscrollbar
          Tk::Tcllib::Autoscroll.unautoscroll(@xscrollbar)
        end
      when :y, 'y'
        if @yscrollbar
          Tk::Tcllib::Autoscroll.unautoscroll(@yscrollbar)
        end
      when nil, :both, 'both'
        if @xscrollbar
          Tk::Tcllib::Autoscroll.unautoscroll(@xscrollbar)
        end
        if @yscrollbar
          Tk::Tcllib::Autoscroll.unautoscroll(@yscrollbar)
        end
      else
        fail ArgumentError, "'x', 'y' or 'both' (String or Symbol) is expected"
      end
      self
    end


Module: Tk::TclX

Module | Tk::TclX
In: | tk/lib/tkextlib/tclx/tclx.rb

Methods

infox package_name package_version signal signal_restart

Classes and Modules

Class Tk::TclX::XPG3_MsgCat

Constants

PACKAGE_NAME = 'Tclx'.freeze

Public Class methods

infox(*args)

[Source]

# File tk/lib/tkextlib/tclx/tclx.rb, line 31
    def self.infox(*args)
      Tk.tk_call('infox', *args)
    end
package_name()

[Source]

# File tk/lib/tkextlib/tclx/tclx.rb, line 19
    def self.package_name
      PACKAGE_NAME
    end
package_version()

[Source]

# File tk/lib/tkextlib/tclx/tclx.rb, line 23
    def self.package_version
      begin
        TkPackage.require('Tclx')
      rescue
        ''
      end
    end
signal(*args)

[Source]

# File tk/lib/tkextlib/tclx/tclx.rb, line 35
    def self.signal(*args)
      warn("Warning: Don't recommend to use TclX's 'signal' command. Please use Ruby's 'Signal.trap' method")
      Tk.tk_call('signal', *args)
    end
signal_restart(*args)

[Source]

# File tk/lib/tkextlib/tclx/tclx.rb, line 40
    def self.signal_restart(*args)
      warn("Warning: Don't recommend to use TclX's 'signal' command. Please use Ruby's 'Signal.trap' method")
      Tk.tk_call('signal', '-restart', *args)
    end


Class: Tk::TclX::XPG3_MsgCat

Class | Tk::TclX::XPG3_MsgCat
In: | tk/lib/tkextlib/tclx/tclx.rb
Parent: | Object

Methods

close get new

External Aliases

new -> open

Public Class methods

new(catname, fail_mode=false)

[Source]

# File tk/lib/tkextlib/tclx/tclx.rb, line 52
      def initialize(catname, fail_mode=false)
        if fail_mode
          @msgcat_id = Tk.tk_call('catopen', '-fail', catname)
        else
          @msgcat_id = Tk.tk_call('catopen', '-nofail', catname)
        end
      end

Public Instance methods

close(fail_mode=false)

[Source]

# File tk/lib/tkextlib/tclx/tclx.rb, line 60
      def close(fail_mode=false)
        if fail_mode
          Tk.tk_call('catclose', '-fail', @msgcat_id)
        else
          Tk.tk_call('catclose', '-nofail', @msgcat_id)
        end
        self
      end
get(setnum, msgnum, defaultstr)

[Source]

# File tk/lib/tkextlib/tclx/tclx.rb, line 69
      def get(setnum, msgnum, defaultstr)
        Tk.tk_call('catgets', @msgcat_id, setnum, msgnum, defaultstr)
      end


Module: Tk::Tcllib

Module | Tk::Tcllib
In: | tk/lib/tkextlib/tcllib.rb tk/lib/tkextlib/tcllib/widget.rb tk/lib/tkextlib/tcllib/tooltip.rb tk/lib/tkextlib/tcllib/tkpiechart.rb tk/lib/tkextlib/tcllib/tablelist_tile.rb tk/lib/tkextlib/tcllib/tablelist_core.rb tk/lib/tkextlib/tcllib/swaplist.rb tk/lib/tkextlib/tcllib/superframe.rb tk/lib/tkextlib/tcllib/style.rb tk/lib/tkextlib/tcllib/scrollwin.rb tk/lib/tkextlib/tcllib/screenruler.rb tk/lib/tkextlib/tcllib/ruler.rb tk/lib/tkextlib/tcllib/plotchart.rb tk/lib/tkextlib/tcllib/panelframe.rb tk/lib/tkextlib/tcllib/ip_entry.rb tk/lib/tkextlib/tcllib/ico.rb tk/lib/tkextlib/tcllib/history.rb tk/lib/tkextlib/tcllib/getstring.rb tk/lib/tkextlib/tcllib/dialog.rb tk/lib/tkextlib/tcllib/datefield.rb tk/lib/tkextlib/tcllib/cursor.rb tk/lib/tkextlib/tcllib/ctext.rb tk/lib/tkextlib/tcllib/autoscroll.rb

Classes and Modules

Module Tk::Tcllib::Autoscroll
Module Tk::Tcllib::Cursor
Module Tk::Tcllib::History
Module Tk::Tcllib::Plotchart
Module Tk::Tcllib::Style
Module Tk::Tcllib::TablelistItemConfig
Module Tk::Tcllib::Tkpiechart
Module Tk::Tcllib::Tooltip
Module Tk::Tcllib::Widget
Class Tk::Tcllib::CText
Class Tk::Tcllib::Datefield
Class Tk::Tcllib::GetString_Dialog
Class Tk::Tcllib::ICO
Class Tk::Tcllib::IP_Entry
Class Tk::Tcllib::Swaplist_Dialog
Class Tk::Tcllib::Tablelist

Constants

Tablelist_Tile | = | Tablelist
TableList_Tile | = | Tablelist
TableList | = | Tablelist
IPEntry | = | IP_Entry
DateField | = | Datefield


Module: Tk::Tcllib::Autoscroll

Module | Tk::Tcllib::Autoscroll
In: | tk/lib/tkextlib/tcllib/autoscroll.rb

Methods

autoscroll autoscroll not_available package_name package_version unautoscroll unautoscroll unwrap wrap

Constants

PACKAGE_NAME = 'autoscroll'.freeze

Public Class methods

autoscroll(win)

[Source]

# File tk/lib/tkextlib/tcllib/autoscroll.rb, line 139
      def self.autoscroll(win)
        tk_call_without_enc('::autoscroll::autoscroll', win.path)
      end
autoscroll(win)

[Source]

# File tk/lib/tkextlib/tcllib/autoscroll.rb, line 51
      def self.autoscroll(win)
        Tk::Tcllib::Autoscroll.not_available
      end
not_available()

[Source]

# File tk/lib/tkextlib/tcllib/autoscroll.rb, line 47
      def self.not_available
        fail RuntimeError, "'tkextlib/tcllib/autoscroll' extension is not available on your current environment."
      end
package_name()

[Source]

# File tk/lib/tkextlib/tcllib/autoscroll.rb, line 35
      def self.package_name
        PACKAGE_NAME
      end
package_version()

[Source]

# File tk/lib/tkextlib/tcllib/autoscroll.rb, line 39
      def self.package_version
        begin
          TkPackage.require('autoscroll')
        rescue
          ''
        end
      end
unautoscroll(win)

[Source]

# File tk/lib/tkextlib/tcllib/autoscroll.rb, line 143
      def self.unautoscroll(win)
        tk_call_without_enc('::autoscroll::unautoscroll', win.path)
      end
unautoscroll(win)

[Source]

# File tk/lib/tkextlib/tcllib/autoscroll.rb, line 55
      def self.unautoscroll(win)
        Tk::Tcllib::Autoscroll.not_available
      end
unwrap()

[Source]

# File tk/lib/tkextlib/tcllib/autoscroll.rb, line 152
      def self.unwrap
        # v1.1
        tk_call_without_enc('::autoscroll::unwrap')
      end
wrap()

[Source]

# File tk/lib/tkextlib/tcllib/autoscroll.rb, line 147
      def self.wrap
        # v1.1
        tk_call_without_enc('::autoscroll::wrap')
      end


Class: Tk::Tcllib::CText

Class | Tk::Tcllib::CText
In: | tk/lib/tkextlib/tcllib/ctext.rb
Parent: | TkText

Methods

add_highlight_class add_highlight_class_for_regexp add_highlight_class_for_special_chars add_highlight_class_with_only_char_start append clear_highlight_classes copy cut delete_highlight_class disable_C_comments edit enable_C_comments fast_delete fast_insert find_next_char find_next_space find_previous_space get_highlight_classes highlight modified? package_name package_version paste set_update_proc

Constants

PACKAGE_NAME | = | 'ctext'.freeze
TkCommandNames | = | ['ctext'.freeze].freeze
WidgetClassName | = | 'Ctext'.freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/tcllib/ctext.rb, line 20
      def self.package_name
        PACKAGE_NAME
      end
package_version()

[Source]

# File tk/lib/tkextlib/tcllib/ctext.rb, line 24
      def self.package_version
        begin
          TkPackage.require('ctext')
        rescue
          ''
        end
      end

Public Instance methods

add_highlight_class(klass, col, *keywords)

[Source]

# File tk/lib/tkextlib/tcllib/ctext.rb, line 93
  def add_highlight_class(klass, col, *keywords)
    tk_call('ctext::addHighlightClass', @path, klass, col, keywords.flatten)
    self
  end
add_highlight_class_for_regexp(klass, col, tcl_regexp)

[Source]

# File tk/lib/tkextlib/tcllib/ctext.rb, line 104
  def add_highlight_class_for_regexp(klass, col, tcl_regexp)
    tk_call('ctext::addHighlightClassForRegexp',
            @path, klass, col, tcl_regexp)
    self
  end
add_highlight_class_for_special_chars(klass, col, *chrs)

[Source]

# File tk/lib/tkextlib/tcllib/ctext.rb, line 98
  def add_highlight_class_for_special_chars(klass, col, *chrs)
    tk_call('ctext::addHighlightClassForSpecialChars',
            @path, klass, col, chrs.join(''))
    self
  end
add_highlight_class_with_only_char_start(klass, col, chr)

[Source]

# File tk/lib/tkextlib/tcllib/ctext.rb, line 110
  def add_highlight_class_with_only_char_start(klass, col, chr)
    tk_call('ctext::addHighlightClassWithOnlyCharStart',
            @path, klass, col, chr)
    self
  end
append(*args)

[Source]

# File tk/lib/tkextlib/tcllib/ctext.rb, line 61
  def append(*args)
    tk_send('append', *args)
  end
clear_highlight_classes()

[Source]

# File tk/lib/tkextlib/tcllib/ctext.rb, line 116
  def clear_highlight_classes
    tk_call('ctext::clearHighlightClasses', @path)
    self
  end
copy()

[Source]

# File tk/lib/tkextlib/tcllib/ctext.rb, line 65
  def copy
    tk_send('copy')
  end
cut()

[Source]

# File tk/lib/tkextlib/tcllib/ctext.rb, line 69
  def cut
    tk_send('cut')
  end
delete_highlight_class(klass)

[Source]

# File tk/lib/tkextlib/tcllib/ctext.rb, line 125
  def delete_highlight_class(klass)
    tk_call('ctext::deleteHighlightClass', @path, klass)
    self
  end
disable_C_comments()

[Source]

# File tk/lib/tkextlib/tcllib/ctext.rb, line 135
  def disable_C_comments
    tk_call('ctext::disableComments', @path)
    self
  end
edit(*args)

[Source]

# File tk/lib/tkextlib/tcllib/ctext.rb, line 89
  def edit(*args)
    tk_send('edit', *args)
  end
enable_C_comments()

[Source]

# File tk/lib/tkextlib/tcllib/ctext.rb, line 130
  def enable_C_comments
    tk_call('ctext::enableComments', @path)
    self
  end
fast_delete(*args)

[Source]

# File tk/lib/tkextlib/tcllib/ctext.rb, line 73
  def fast_delete(*args)
    tk_send('fastdelete', *args)
  end
fast_insert(*args)

[Source]

# File tk/lib/tkextlib/tcllib/ctext.rb, line 77
  def fast_insert(*args)
    tk_send('fastinsert', *args)
  end
find_next_char(idx, chr)

[Source]

# File tk/lib/tkextlib/tcllib/ctext.rb, line 140
  def find_next_char(idx, chr)
    tk_call('ctext::findNextChar', @path, idx, chr)
  end
find_next_space(idx)

[Source]

# File tk/lib/tkextlib/tcllib/ctext.rb, line 144
  def find_next_space(idx)
    tk_call('ctext::findNextSpace', @path, idx)
  end
find_previous_space(idx)

[Source]

# File tk/lib/tkextlib/tcllib/ctext.rb, line 148
  def find_previous_space(idx)
    tk_call('ctext::findPreviousSpace', @path, idx)
  end
get_highlight_classes()

[Source]

# File tk/lib/tkextlib/tcllib/ctext.rb, line 121
  def get_highlight_classes
    tk_split_simplelist(tk_call('ctext::getHighlightClasses', @path))
  end
highlight(*args)

[Source]

# File tk/lib/tkextlib/tcllib/ctext.rb, line 81
  def highlight(*args)
    tk_send('highlight', *args)
  end
modified?(mode)

[Source]

# File tk/lib/tkextlib/tcllib/ctext.rb, line 157
  def modified?(mode)
    bool(tk_call('ctext::modified', @path, mode))
  end
paste()

[Source]

# File tk/lib/tkextlib/tcllib/ctext.rb, line 85
  def paste
    tk_send('paste')
  end
set_update_proc(cmd=Proc.new)

[Source]

# File tk/lib/tkextlib/tcllib/ctext.rb, line 152
  def set_update_proc(cmd=Proc.new)
    tk_call('proc', 'ctext::update', '', cmd)
    self
  end


Module: Tk::Tcllib::Cursor

Module | Tk::Tcllib::Cursor
In: | tk/lib/tkextlib/tcllib/cursor.rb

Methods

cursor_display cursor_display cursor_propagate cursor_propagate cursor_restore cursor_restore not_available package_name package_version

Constants

PACKAGE_NAME = 'cursor'.freeze

Public Class methods

cursor_display(win=None)

[Source]

# File tk/lib/tkextlib/tcllib/cursor.rb, line 82
      def self.cursor_display(win=None)
        tk_call_without_enc('::cursor::display', _epath(win))
      end
cursor_display(win=None)

[Source]

# File tk/lib/tkextlib/tcllib/cursor.rb, line 32
      def self.cursor_display(win=None)
        Tk::Tcllib::Cursor.not_available
      end
cursor_propagate(win, cursor)

[Source]

# File tk/lib/tkextlib/tcllib/cursor.rb, line 36
      def self.cursor_propagate(win, cursor)
        Tk::Tcllib::Cursor.not_available
      end
cursor_propagate(win, cursor)

[Source]

# File tk/lib/tkextlib/tcllib/cursor.rb, line 86
      def self.cursor_propagate(win, cursor)
        #tk_call_without_enc('::cursor::propagate', win.path, cursor)
        tk_call_without_enc('::cursor::propagate', _epath(win), cursor)
      end
cursor_restore(win, cursor = None)

[Source]

# File tk/lib/tkextlib/tcllib/cursor.rb, line 40
      def self.cursor_restore(win, cursor = None)
        Tk::Tcllib::Cursor.not_available
      end
cursor_restore(win, cursor = None)

[Source]

# File tk/lib/tkextlib/tcllib/cursor.rb, line 91
      def self.cursor_restore(win, cursor = None)
        #tk_call_without_enc('::cursor::restore', win.path, cursor)
        tk_call_without_enc('::cursor::restore', _epath(win), cursor)
      end
not_available()

[Source]

# File tk/lib/tkextlib/tcllib/cursor.rb, line 28
      def self.not_available
        fail RuntimeError, "'tkextlib/tcllib/cursor' extension is not available on your current environment."
      end
package_name()

[Source]

# File tk/lib/tkextlib/tcllib/cursor.rb, line 16
      def self.package_name
        PACKAGE_NAME
      end
package_version()

[Source]

# File tk/lib/tkextlib/tcllib/cursor.rb, line 20
      def self.package_version
        begin
          TkPackage.require('cursor')
        rescue
          ''
        end
      end


Class: Tk::Tcllib::Datefield

Class | Tk::Tcllib::Datefield
In: | tk/lib/tkextlib/tcllib/datefield.rb
Parent: | TkEntry

Methods

package_name package_version

Constants

PACKAGE_NAME | = | 'datefield'.freeze
TkCommandNames | = | ['::datefield::datefield'.freeze].freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/tcllib/datefield.rb, line 29
      def self.package_name
        PACKAGE_NAME
      end
package_version()

[Source]

# File tk/lib/tkextlib/tcllib/datefield.rb, line 33
      def self.package_version
        begin
          TkPackage.require('datefield')
        rescue
          ''
        end
      end


Class: Tk::Tcllib::GetString_Dialog

Class | Tk::Tcllib::GetString_Dialog
In: | tk/lib/tkextlib/tcllib/getstring.rb
Parent: | TkWindow

Methods

cget configinfo configure display display new package_name package_version show show status value

Constants

PACKAGE_NAME | = | 'getstring'.freeze
TkCommandNames | = | ['::getstring::tk_getString'.freeze].freeze
WidgetClassName | = | 'TkSDialog'.freeze

Public Class methods

display(*args)

[Source]

# File tk/lib/tkextlib/tcllib/getstring.rb, line 44
  def self.display(*args)
    self.show(*args)
  end
new(*args)

[Source]

# File tk/lib/tkextlib/tcllib/getstring.rb, line 48
  def initialize(*args)   # args = (parent=nil, text='', keys=nil)
    keys = args.pop
    if keys.kind_of?(Hash)
      text = args.pop
      @keys = _symbolkey2str(keys)
      args.push(keys)
    else
      text = keys
      @keys = {}
    end
    if text
      @text = text.dup
    else
      @text = ''
    end

    @variable = TkVariable.new
    @status = nil

    super(*args)
  end
package_name()

[Source]

# File tk/lib/tkextlib/tcllib/getstring.rb, line 19
    def self.package_name
      PACKAGE_NAME
    end
package_version()

[Source]

# File tk/lib/tkextlib/tcllib/getstring.rb, line 23
    def self.package_version
      begin
        TkPackage.require('getstring')
      rescue
        ''
      end
    end
show(*args)

[Source]

# File tk/lib/tkextlib/tcllib/getstring.rb, line 39
  def self.show(*args)
    dialog = self.new(*args)
    dialog.show
    [dialog.status, dialog.value]
  end

Public Instance methods

cget(slot)

[Source]

# File tk/lib/tkextlib/tcllib/getstring.rb, line 90
  def cget(slot)
    slot = slot.to_s
    if slot == 'text'
      @text
    else
      @keys[slot]
    end
  end
configinfo(slot = nil)

[Source]

# File tk/lib/tkextlib/tcllib/getstring.rb, line 122
  def configinfo(slot = nil)
    if slot
      slot = slot.to_s
      [ slot, nil, nil, nil, ( (slot == 'text')? @text: @keys[slot] ) ]
    else
      @keys.collect{|k, v| [ k, nil, nil, nil, v ] }   \
      << [ 'text', nil, nil, nil, @text ]
    end
  end
configure(slot, value=None)

[Source]

# File tk/lib/tkextlib/tcllib/getstring.rb, line 99
  def configure(slot, value=None)
    if slot.kind_of?(Hash)
      slot.each{|k, v| configure(k, v)}
    else
      slot = slot.to_s
      value = _symbolkey2str(value) if value.kind_of?(Hash)
      if value && value != None
        if slot == 'text'
          @text = value.to_s
        else
          @keys[slot] = value
        end
      else
        if slot == 'text'
          @text = ''
        else
          @keys.delete(slot)
        end
      end
    end
    self
  end
display()

Alias for show

show()

[Source]

# File tk/lib/tkextlib/tcllib/getstring.rb, line 75
  def show
    @variable.value = ''
    @status = bool(tk_call(self.class::TkCommandNames[0],
                           @path, @variable, @text, *hash_kv(@keys)))
  end
status()

[Source]

# File tk/lib/tkextlib/tcllib/getstring.rb, line 82
  def status
    @status
  end
value()

[Source]

# File tk/lib/tkextlib/tcllib/getstring.rb, line 86
  def value
    @variable.value
  end


Module: Tk::Tcllib::History

Module | Tk::Tcllib::History
In: | tk/lib/tkextlib/tcllib/history.rb

Methods

history_add history_clear history_configinfo history_configure history_get history_remove init package_name package_version remove

Constants

PACKAGE_NAME = 'history'.freeze

Public Class methods

init(entry, length=None)

[Source]

# File tk/lib/tkextlib/tcllib/history.rb, line 36
  def self.init(entry, length=None)
    tk_call_without_enc('::history::init', entry.path, length)
    entry.extend(self)  # add methods to treat history to the entry widget
  end
package_name()

[Source]

# File tk/lib/tkextlib/tcllib/history.rb, line 19
    def self.package_name
      PACKAGE_NAME
    end
package_version()

[Source]

# File tk/lib/tkextlib/tcllib/history.rb, line 23
    def self.package_version
      begin
        TkPackage.require('history')
      rescue
        ''
      end
    end
remove(entry)

[Source]

# File tk/lib/tkextlib/tcllib/history.rb, line 41
  def self.remove(entry)
    tk_call_without_enc('::history::remove', entry.path)
    entry
  end

Public Instance methods

history_add(text)

[Source]

# File tk/lib/tkextlib/tcllib/history.rb, line 51
  def history_add(text)
    tk_call('::history::add', @path, text)
    self
  end
history_clear()

[Source]

# File tk/lib/tkextlib/tcllib/history.rb, line 60
  def history_clear
    tk_call_without_enc('::history::clear', @path)
    self
  end
history_configinfo(opt)

[Source]

# File tk/lib/tkextlib/tcllib/history.rb, line 70
  def history_configinfo(opt)
    tk_call('::history::configure', @path, opt)
  end
history_configure(opt, value)

[Source]

# File tk/lib/tkextlib/tcllib/history.rb, line 65
  def history_configure(opt, value)
    tk_call('::history::configure', @path, opt, value)
    self
  end
history_get()

[Source]

# File tk/lib/tkextlib/tcllib/history.rb, line 56
  def history_get
    simplelist(tk_call_without_enc('::history::get', @path))
  end
history_remove()

[Source]

# File tk/lib/tkextlib/tcllib/history.rb, line 46
  def history_remove
    tk_call_without_enc('::history::remove', @path)
    self
  end


Class: Tk::Tcllib::ICO

Class | Tk::Tcllib::ICO
In: | tk/lib/tkextlib/tcllib/ico.rb
Parent: | TkImage

Methods

clear_cache copy exe_to_ico get get_data get_image list new package_name package_version show transparent_color transparent_color write write

Constants

PACKAGE_NAME = 'ico'.freeze

Public Class methods

clear_cache(file=None)

[Source]

# File tk/lib/tkextlib/tcllib/ico.rb, line 73
  def self.clear_cache(file=None)
    tk_call_without_enc('::ico::clearCache', file)
  end
copy(from_file, from_index, to_file, to_index, keys=nil)

[Source]

# File tk/lib/tkextlib/tcllib/ico.rb, line 62
  def self.copy(from_file, from_index, to_file, to_index, keys=nil)
    tk_call_without_enc('::ico::copyIcon',
                        from_file, from_index, to_file, to_index,
                        *hash_kv(keys, true))
  end
exe_to_ico(exe_file, ico_file, keys=nil)

[Source]

# File tk/lib/tkextlib/tcllib/ico.rb, line 68
  def self.exe_to_ico(exe_file, ico_file, keys=nil)
    tk_call_without_enc('::ico::copyIcon', exe_file, ico_file,
                        *hash_kv(keys, true))
  end
get(file, index, keys=nil)

[Source]

# File tk/lib/tkextlib/tcllib/ico.rb, line 41
  def self.get(file, index, keys=nil)
    tk_call_without_enc('::ico::getIcon', file, index, *hash_kv(keys, true))
  end
get_data(file, index, keys={})

[Source]

# File tk/lib/tkextlib/tcllib/ico.rb, line 51
  def self.get_data(file, index, keys={})
    keys['format'] = 'data'
    tk_split_list(tk_call_without_enc('::ico::getIcon', file, index,
                                      *hash_kv(keys, true)))
  end
get_image(file, index, keys={})

[Source]

# File tk/lib/tkextlib/tcllib/ico.rb, line 45
  def self.get_image(file, index, keys={})
    keys = _symbolkey2str(keys)
    keys.delete('format')
    self.new(file, index, keys)
  end
list(file, keys=nil)

[Source]

# File tk/lib/tkextlib/tcllib/ico.rb, line 36
  def self.list(file, keys=nil)
    tk_split_list(tk_call_without_enc('::ico::getIconList', file,
                                      *hash_kv(keys, true)))
  end
new(file, index, keys=nil)

[Source]

# File tk/lib/tkextlib/tcllib/ico.rb, line 92
  def initialize(file, index, keys=nil)
    keys = _symbolkey2str(keys)
    if keys.key?('name')
      @path = keys['name'].to_s
    else
      @path = Tk_Image_ID.join(TkCore::INTERP._ip_id_)
      Tk_Image_ID[1].succ!
    end
    tk_call_without_enc('::ico::getIcon', file, index, '-name', @path,
                        '-format', 'image', *hash_kv(keys, true))
    Tk_IMGTBL[@path] = self
  end
package_name()

[Source]

# File tk/lib/tkextlib/tcllib/ico.rb, line 20
      def self.package_name
        PACKAGE_NAME
      end
package_version()

[Source]

# File tk/lib/tkextlib/tcllib/ico.rb, line 24
      def self.package_version
        begin
          TkPackage.require('ico')
        rescue
          ''
        end
      end
show(file, keys=nil)

[Source]

# File tk/lib/tkextlib/tcllib/ico.rb, line 86
  def self.show(file, keys=nil)
    tk_call_without_enc('::ico::Show', file, *hash_kv(keys, true))
  end
transparent_color(image, color)

[Source]

# File tk/lib/tkextlib/tcllib/ico.rb, line 77
  def self.transparent_color(image, color)
    if image.kind_of?(Array)
      tk_split_list(tk_call_without_enc('::ico::transparentColor',
                                        image, color))
    else
      tk_call_without_enc('::ico::transparentColor', image, color)
    end
  end
write(file, index, depth, data, keys=nil)

[Source]

# File tk/lib/tkextlib/tcllib/ico.rb, line 57
  def self.write(file, index, depth, data, keys=nil)
    tk_call_without_enc('::ico::writeIcon', file, index, depth, data,
                        *hash_kv(keys, true))
  end

Public Instance methods

transparent_color(color)

[Source]

# File tk/lib/tkextlib/tcllib/ico.rb, line 110
  def transparent_color(color)
    tk_call_without_enc('::ico::transparentColor', @path, color)
    self
  end
write(file, index, depth, keys=nil)

[Source]

# File tk/lib/tkextlib/tcllib/ico.rb, line 105
  def write(file, index, depth, keys=nil)
    Tk::Tcllib::ICO.write(file, index, depth, @path, keys=nil)
    self
  end


Class: Tk::Tcllib::IP_Entry

Class | Tk::Tcllib::IP_Entry
In: | tk/lib/tkextlib/tcllib/ip_entry.rb
Parent: | TkEntry

Methods

complete? insert package_name package_version

Constants

PACKAGE_NAME | = | 'ipentry'.freeze
TkCommandNames | = | ['::ipentry::ipentry'.freeze].freeze
WidgetClassName | = | 'IPEntry'.freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/tcllib/ip_entry.rb, line 23
      def self.package_name
        PACKAGE_NAME
      end
package_version()

[Source]

# File tk/lib/tkextlib/tcllib/ip_entry.rb, line 27
      def self.package_version
        begin
          TkPackage.require('ipentry')
        rescue
          ''
        end
      end

Public Instance methods

complete?()

[Source]

# File tk/lib/tkextlib/tcllib/ip_entry.rb, line 59
  def complete?
    bool(tk_send_without_enc('complete'))
  end
insert(*ip)

[Source]

# File tk/lib/tkextlib/tcllib/ip_entry.rb, line 63
  def insert(*ip)
    tk_send_without_enc('insert', array2tk_list(ip.flatten))
  end


Module: Tk::Tcllib::Plotchart

Module | Tk::Tcllib::Plotchart
In: | tk/lib/tkextlib/tcllib/plotchart.rb

Methods

coords_3D_to_pixel coords_to_pixel determine_scale package_name package_version pixel_to_coords polar_coordinates polar_to_pixel set_zoom_pan view_port world_3D_coordinates world_coordinates

Classes and Modules

Module Tk::Tcllib::Plotchart::ChartMethod
Class Tk::Tcllib::Plotchart::Barchart
Class Tk::Tcllib::Plotchart::Gnattchart
Class Tk::Tcllib::Plotchart::HorizontalBarchart
Class Tk::Tcllib::Plotchart::IsometricPlot
Class Tk::Tcllib::Plotchart::Piechart
Class Tk::Tcllib::Plotchart::Plot3D
Class Tk::Tcllib::Plotchart::PlotSeries
Class Tk::Tcllib::Plotchart::PolarPlot
Class Tk::Tcllib::Plotchart::Stripchart
Class Tk::Tcllib::Plotchart::Timechart
Class Tk::Tcllib::Plotchart::XYPlot

Constants

PACKAGE_NAME | = | 'Plotchart'.freeze
Polarplot | = | PolarPlot
Isometricplot | = | IsometricPlot

Public Class methods

coords_3D_to_pixel(w, x, y, z)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 108
  def self.coords_3D_to_pixel(w, x, y, z)
    list(tk_call_without_enc('::Plotchart::coords3DToPixel', w.path, x, y, z))
  end
coords_to_pixel(w, x, y)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 104
  def self.coords_to_pixel(w, x, y)
    list(tk_call_without_enc('::Plotchart::coordsToPixel', w.path, x, y))
  end
determine_scale(w, xmax, ymax)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 124
  def self.determine_scale(w, xmax, ymax)
    tk_call_without_enc('::Plotchart::determineScale', w.path, xmax, ymax)
  end
package_name()

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 71
      def self.package_name
        PACKAGE_NAME
      end
package_version()

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 75
      def self.package_version
        begin
          TkPackage.require('Plotchart')
        rescue
          ''
        end
      end
pixel_to_coords(w, x, y)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 120
  def self.pixel_to_coords(w, x, y)
    list(tk_call_without_enc('::Plotchart::coordsToPixel', w.path, x, y))
  end
polar_coordinates(w, radmax)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 112
  def self.polar_coordinates(w, radmax)
    tk_call_without_enc('::Plotchart::polarCoordinates', w.path, radmax)
  end
polar_to_pixel(w, rad, phi)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 116
  def self.polar_to_pixel(w, rad, phi)
    list(tk_call_without_enc('::Plotchart::polarToPixel', w.path, rad, phi))
  end
set_zoom_pan(w)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 128
  def self.set_zoom_pan(w)
    tk_call_without_enc('::Plotchart::setZoomPan', w.path)
  end
view_port(w, *args)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 89
  def self.view_port(w, *args) # args := pxmin, pymin, pxmax, pymax
    tk_call_without_enc('::Plotchart::viewPort', w.path, *(args.flatten))
  end
world_3D_coordinates(w, *args)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 98
  def self.world_3D_coordinates(w, *args)
    # args := xmin, ymin, zmin, xmax, ymax, zmax
    tk_call_without_enc('::Plotchart::world3DCoordinates',
                        w.path, *(args.flatten))
  end
world_coordinates(w, *args)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 93
  def self.world_coordinates(w, *args) # args := xmin, ymin, xmax, ymax
    tk_call_without_enc('::Plotchart::worldCoordinates',
                        w.path, *(args.flatten))
  end


Class: Tk::Tcllib::Plotchart::Barchart

Class | Tk::Tcllib::Plotchart::Barchart
In: | tk/lib/tkextlib/tcllib/plotchart.rb
Parent: | TkCanvas

Methods

__destroy_hook__ color colors colour colours new plot

Included Modules

ChartMethod

Constants

TkCommandNames = [ 'canvas'.freeze, '::Plotchart::createBarchart'.freeze

Public Class methods

new(*args)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 599
    def initialize(*args)
      # args := ([parent,] xlabels, ylabels [, series] [, keys])
      # xlabels, ylabels := labels | axis ( depend on normal or horizontal )
      # labels := Array of [label, label, ...]
      #   (It determines the number of bars that will be plotted per series.)
      # axis := Array of [minimum, maximum, stepsize]
      # series := Integer number of data series | 'stacked' | :stacked
      if args[0].kind_of?(Array)
        @xlabels = args.shift
        @ylabels  = args.shift

        if args[0].kind_of?(Hash)
          @series_size = :stacked
        else
          @series_size  = args.shift
        end

        super(*args) # create canvas widget
      else
        parent = args.shift

        @xlabels = args.shift
        @ylabels = args.shift

        if args[0].kind_of?(Hash)
          @series_size = :stacked
        else
          @series_size  = args.shift
        end

        if parent.kind_of?(TkCanvas)
          @path = parent.path
        else
          super(parent, *args) # create canvas widget
        end
      end

      @chart = _create_chart
    end

Public Instance methods

__destroy_hook__()

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 647
    def __destroy_hook__
      Tk::Tcllib::Plotchart::PlotSeries::SeriesID_TBL.delete(@path)
    end
color(*cols)

Alias for colours

colors(*cols)

Alias for colours

colour(*cols)

Alias for colours

colours(*cols)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 656
    def colours(*cols)
      # set the colours to be used
      tk_call_without_enc(@chart, 'colours', *cols)
      self
    end
plot(series, dat, col=None)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 651
    def plot(series, dat, col=None)
      tk_call_without_enc(@chart, 'plot', series, dat, col)
      self
    end


Module: Tk::Tcllib::Plotchart::ChartMethod

Module | Tk::Tcllib::Plotchart::ChartMethod
In: | tk/lib/tkextlib/tcllib/plotchart.rb

Methods

coords_3D_to_pixel coords_to_pixel determine_scale pixel_to_coords polar_coordinates polar_to_pixel save_plot set_zoom_pan title view_port world_3D_coordinates world_coordinates xconfig xtext yconfig ytext

Included Modules

TkCore

Public Instance methods

coords_3D_to_pixel(x, y, z)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 199
    def coords_3D_to_pixel(x, y, z)
      list(tk_call_without_enc('::Plotchart::coords3DToPixel', @path, x, y, z))
    end
coords_to_pixel(x, y)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 195
    def coords_to_pixel(x, y)
      list(tk_call_without_enc('::Plotchart::coordsToPixel', @path, x, y))
    end
determine_scale(xmax, ymax)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 216
    def determine_scale(xmax, ymax)
      tk_call_without_enc('::Plotchart::determineScale', @path, xmax, ymax)
      self
    end
pixel_to_coords(x, y)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 212
    def pixel_to_coords(x, y)
      list(tk_call_without_enc('::Plotchart::coordsToPixel', @path, x, y))
    end
polar_coordinates(radmax)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 203
    def polar_coordinates(radmax)
      tk_call_without_enc('::Plotchart::polarCoordinates', @path, radmax)
      self
    end
polar_to_pixel(rad, phi)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 208
    def polar_to_pixel(rad, phi)
      list(tk_call_without_enc('::Plotchart::polarToPixel', @path, rad, phi))
    end
save_plot(filename)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 141
    def save_plot(filename)
      tk_call_without_enc(@chart, 'saveplot', filename)
      self
    end
set_zoom_pan()

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 221
    def set_zoom_pan()
      tk_call_without_enc('::Plotchart::setZoomPan', @path)
      self
    end
title(str)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 136
    def title(str)
      tk_call_without_enc(@chart, 'title', _get_eval_enc_str(str))
      self
    end
view_port(*args)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 177
    def view_port(*args) # args := pxmin, pymin, pxmax, pymax
      tk_call_without_enc('::Plotchart::viewPort', @path, *(args.flatten))
      self
    end
world_3D_coordinates(*args)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 188
    def world_3D_coordinates(*args)
      # args := xmin, ymin, zmin, xmax, ymax, zmax
      tk_call_without_enc('::Plotchart::world3DCoordinates',
                          @path, *(args.flatten))
      self
    end
world_coordinates(*args)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 182
    def world_coordinates(*args) # args := xmin, ymin, xmax, ymax
      tk_call_without_enc('::Plotchart::worldCoordinates',
                          @path, *(args.flatten))
      self
    end
xconfig(key, value=None)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 156
    def xconfig(key, value=None)
      if key.kind_of?(Hash)
        tk_call_without_enc(@chart, 'xconfig', *hash_kv(key, true))
      else
        tk_call_without_enc(@chart, 'xconfig',
                            "-#{key}", _get_eval_enc_str(value))
      end
      self
    end
xtext(str)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 146
    def xtext(str)
      tk_call_without_enc(@chart, 'xtext', _get_eval_enc_str(str))
      self
    end
yconfig(key, value=None)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 166
    def yconfig(key, value=None)
      if key.kind_of?(Hash)
        tk_call_without_enc(@chart, 'yconfig', *hash_kv(key, true))
      else
        tk_call_without_enc(@chart, 'yconfig',
                            "-#{key}", _get_eval_enc_str(value))
      end
      self
    end
ytext(str)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 151
    def ytext(str)
      tk_call_without_enc(@chart, 'ytext', _get_eval_enc_str(str))
      self
    end


Class: Tk::Tcllib::Plotchart::Gnattchart

Class | Tk::Tcllib::Plotchart::Gnattchart
In: | tk/lib/tkextlib/tcllib/plotchart.rb
Parent: | TkCanvas

Methods

color_of_part connect font_of_part milestone new summary task vertline

Included Modules

ChartMethod

Constants

TkCommandNames = [ 'canvas'.freeze, '::Plotchart::createGnattchart'.freeze

Public Class methods

new(*args)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 744
    def initialize(*args)
      # args := ([parent,] time_begin, time_end, items [, text_width] [, keys])
      # time_begin := String of time format (e.g. "1 january 2004")
      # time_end   := String of time format (e.g. "1 january 2004")
      # items := Expected/maximum number of items
      #          ( This determines the vertical spacing. )
      if args[0].kind_of?(String)
        @time_begin = args.shift
        @time_end   = args.shift
        @items      = args.shift

        if args[0].kind_of?(Fixnum)
          @text_width = args.shift
        else
          @text_width = None
        end

        super(*args) # create canvas widget
      else
        parent = args.shift

        @time_begin = args.shift
        @time_end   = args.shift
        @items      = args.shift

        if args[0].kind_of?(Fixnum)
          @text_width = args.shift
        else
          @text_width = None
        end

        if parent.kind_of?(TkCanvas)
          @path = parent.path
        else
          super(parent, *args) # create canvas widget
        end
      end

      @chart = _create_chart
    end

Public Instance methods

color_of_part(keyword, newcolor)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 823
    def color_of_part(keyword, newcolor)
      tk_call_without_enc(@chart, 'color', keyword, newcolor)
      self
    end
connect(from_task, to_task)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 809
    def connect(from_task, to_task)
      from_task = array2tk_list(from_task) if from_task.kind_of?(Array)
      to_task   = array2tk_list(to_task)   if to_task.kind_of?(Array)

      tk_call_without_enc(@chart, 'connect', from_task, to_task)
      self
    end
font_of_part(keyword, newfont)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 828
    def font_of_part(keyword, newfont)
      tk_call_without_enc(@chart, 'font', keyword, newfont)
      self
    end
milestone(txt, time, col=None)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 799
    def milestone(txt, time, col=None)
      tk_call_without_enc(@chart, 'milestone', txt, time, col)
      self
    end
summary(txt, tasks)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 817
    def summary(txt, tasks)
      tasks = array2tk_list(tasks) if tasks.kind_of?(Array)
      tk_call_without_enc(@chart, 'summary', tasks)
      self
    end
task(txt, time_begin, time_end, completed=0.0)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 792
    def task(txt, time_begin, time_end, completed=0.0)
      list(tk_call_without_enc(@chart, 'task', txt, time_begin, time_end,
                               completed)).collect!{|id|
        TkcItem.id2obj(self, id)
      }
    end
vertline(txt, time)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 804
    def vertline(txt, time)
      tk_call_without_enc(@chart, 'vertline', txt, time)
      self
    end


Class: Tk::Tcllib::Plotchart::HorizontalBarchart

Class | Tk::Tcllib::Plotchart::HorizontalBarchart
In: | tk/lib/tkextlib/tcllib/plotchart.rb
Parent: | Barchart

Constants

TkCommandNames = [ 'canvas'.freeze, '::Plotchart::createHorizontalBarchart'.freeze


Class: Tk::Tcllib::Plotchart::IsometricPlot

Class | Tk::Tcllib::Plotchart::IsometricPlot
In: | tk/lib/tkextlib/tcllib/plotchart.rb
Parent: | TkCanvas

Methods

new plot plot_circle plot_filled_circle plot_filled_rectangle plot_rectangle

Included Modules

ChartMethod

Constants

TkCommandNames = [ 'canvas'.freeze, '::Plotchart::createIsometricPlot'.freeze

Public Class methods

new(*args)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 406
    def initialize(*args) # args := ([parent,] xaxis, yaxis, [, step] [, keys])
                          # xaxis := Array of [minimum, maximum]
                          # yaxis := Array of [minimum, maximum]
                          # step := Float of stepsize | "noaxes" | :noaxes
      if args[0].kind_of?(Array)
        @xaxis = args.shift
        @yaxis = args.shift

        if args[0].kind_of?(Hash)
          @stepsize = :noaxes
        else
          @stepsize = args.shift
        end

        super(*args) # create canvas widget
      else
        parent = args.shift

        @xaxis = args.shift
        @yaxis = args.shift

        if args[0].kind_of?(Hash)
          @stepsize = :noaxes
        else
          @stepsize = args.shift
        end

        if parent.kind_of?(TkCanvas)
          @path = parent.path
        else
          super(parent, *args) # create canvas widget
        end
      end

      @chart = _create_chart
    end

Public Instance methods

plot(type, *args)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 451
    def plot(type, *args)
      self.__send__("plot_#{type.to_s.tr('-', '_')}", *args)
    end
plot_circle(*args)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 465
    def plot_circle(*args) # args := xc, yc, radius, color
      tk_call_without_enc(@chart, 'plot', 'circle', *(args.flatten))
      self
    end
plot_filled_circle(*args)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 470
    def plot_filled_circle(*args) # args := xc, yc, radius, color
      tk_call_without_enc(@chart, 'plot', 'filled-circle', *(args.flatten))
      self
    end
plot_filled_rectangle(*args)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 460
    def plot_filled_rectangle(*args) # args := x1, y1, x2, y2, color
      tk_call_without_enc(@chart, 'plot', 'filled-rectangle', *(args.flatten))
      self
    end
plot_rectangle(*args)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 455
    def plot_rectangle(*args) # args := x1, y1, x2, y2, color
      tk_call_without_enc(@chart, 'plot', 'rectangle', *(args.flatten))
      self
    end


Class: Tk::Tcllib::Plotchart::Piechart

Class | Tk::Tcllib::Plotchart::Piechart
In: | tk/lib/tkextlib/tcllib/plotchart.rb
Parent: | TkCanvas

Methods

new plot

Included Modules

ChartMethod

Constants

TkCommandNames = [ 'canvas'.freeze, '::Plotchart::createPiechart'.freeze

Public Class methods

new(*args)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 568
    def initialize(*args) # args := ([parent] [, keys])
      if args[0].kind_of?(TkCanvas)
        parent = args.shift
        @path = parent.path
      else
        super(*args) # create canvas widget
      end
      @chart = _create_chart
    end

Public Instance methods

plot(*dat)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 584
    def plot(*dat)  # argument is a list of [label, value]
      tk_call_without_enc(@chart, 'plot', dat.flatten)
      self
    end


Class: Tk::Tcllib::Plotchart::Plot3D

Class | Tk::Tcllib::Plotchart::Plot3D
In: | tk/lib/tkextlib/tcllib/plotchart.rb
Parent: | TkCanvas

Methods

color colors colour colours grid_size new plot_data plot_funcont plot_function

Included Modules

ChartMethod

Constants

TkCommandNames = [ 'canvas'.freeze, '::Plotchart::create3DPlot'.freeze

Public Class methods

new(*args)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 486
    def initialize(*args) # args := ([parent,] xaxis, yaxis, zaxis [, keys])
                          # xaxis := Array of [minimum, maximum, stepsize]
                          # yaxis := Array of [minimum, maximum, stepsize]
                          # zaxis := Array of [minimum, maximum, stepsize]
      if args[0].kind_of?(Array)
        @xaxis = args.shift
        @yaxis = args.shift
        @zaxis = args.shift

        super(*args) # create canvas widget
      else
        parent = args.shift

        @xaxis = args.shift
        @yaxis = args.shift
        @zaxis = args.shift

        if parent.kind_of?(TkCanvas)
          @path = parent.path
        else
          super(parent, *args) # create canvas widget
        end
      end

      @chart = _create_chart
    end

Public Instance methods

color(fill, border)

Alias for colour

colors(fill, border)

Alias for colour

colour(fill, border)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 549
    def colour(fill, border)
      # configure the colours to use for polygon borders and inner area
      tk_call_without_enc(@chart, 'colour', fill, border)
      self
    end
colours(fill, border)

Alias for colour

grid_size(nxcells, nycells)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 535
    def grid_size(nxcells, nycells)
      tk_call_without_enc(@chart, 'gridsize', nxcells, nycells)
      self
    end
plot_data(dat)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 540
    def plot_data(dat)
      # dat has to be provided as a 2 level array.
      # 1st level contains rows, drawn in y-direction,
      # and each row is an array whose elements are drawn in x-direction,
      # for the columns.
      tk_call_without_enc(@chart, 'plotdata', dat)
      self
    end
plot_funcont(conts, cmd=Proc.new)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 528
    def plot_funcont(conts, cmd=Proc.new)
      conts = array2tk_list(conts) if conts.kind_of?(Array)
      Tk.ip_eval("proc #{@path}_#{@chart} {x y} {#{install_cmd(cmd)} $x $y}")
      tk_call_without_enc(@chart, 'plotfuncont', "#{@path}_#{@chart}", conts)
      self
    end
plot_function(cmd=Proc.new)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 522
    def plot_function(cmd=Proc.new)
      Tk.ip_eval("proc #{@path}_#{@chart} {x y} {#{install_cmd(cmd)} $x $y}")
      tk_call_without_enc(@chart, 'plotfunc', "#{@path}_#{@chart}")
      self
    end


Class: Tk::Tcllib::Plotchart::PlotSeries

Class | Tk::Tcllib::Plotchart::PlotSeries
In: | tk/lib/tkextlib/tcllib/plotchart.rb
Parent: | TkObject

Methods

dataconfig id2obj new plot

Constants

SeriesID_TBL | = | TkCore::INTERP.create_table
Series_ID | = | ['series'.freeze, '00000'.taint].freeze

Public Class methods

id2obj(chart, id)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 840
    def self.id2obj(chart, id)
      path = chart.path
      return id unless SeriesID_TBL[path]
      SeriesID_TBL[path][id]? SeriesID_TBL[path][id]: id
    end
new(chart, keys=nil)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 846
    def initialize(chart, keys=nil)
      @parent = @chart_obj = chart
      @ppath = @chart_obj.path
      @path = @series = @id = Series_ID.join(TkCore::INTERP._ip_id_)
      # SeriesID_TBL[@id] = self
      SeriesID_TBL[@ppath] = {} unless SeriesID_TBL[@ppath]
      SeriesID_TBL[@ppath][@id] = self
      Series_ID[1].succ!
      dataconfig(keys) if keys.kind_of?(Hash)
    end

Public Instance methods

dataconfig(key, value=None)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 861
    def dataconfig(key, value=None)
      @chart_obj.dataconfig(@series, key, value)
    end
plot(*args)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 857
    def plot(*args)
      @chart_obj.plot(@series, *args)
    end


Class: Tk::Tcllib::Plotchart::PolarPlot

Class | Tk::Tcllib::Plotchart::PolarPlot
In: | tk/lib/tkextlib/tcllib/plotchart.rb
Parent: | TkCanvas

Methods

__destroy_hook__ dataconfig new plot

Included Modules

ChartMethod

Constants

TkCommandNames = [ 'canvas'.freeze, '::Plotchart::createPolarplot'.freeze

Public Class methods

new(*args)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 348
    def initialize(*args) # args := ([parent,] radius_data [, keys])
                          # radius_data := Array of [maximum_radius, stepsize]
      if args[0].kind_of?(Array)
        @radius_data = args.shift

        super(*args) # create canvas widget
      else
        parent = args.shift

        @radius_data = args.shift

        if parent.kind_of?(TkCanvas)
          @path = parent.path
        else
          super(parent, *args) # create canvas widget
        end
      end

      @chart = _create_chart
    end

Public Instance methods

__destroy_hook__()

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 376
    def __destroy_hook__
      Tk::Tcllib::Plotchart::PlotSeries::SeriesID_TBL.delete(@path)
    end
dataconfig(series, key, value=None)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 386
    def dataconfig(series, key, value=None)
      if key.kind_of?(Hash)
        tk_call_without_enc(@chart, 'dataconfig', series, *hash_kv(key, true))
      else
        tk_call_without_enc(@chart, 'dataconfig', series,
                            "-#{key}", _get_eval_enc_str(value))
      end
    end
plot(series, radius, angle)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 380
    def plot(series, radius, angle)
      tk_call_without_enc(@chart, 'plot', _get_eval_enc_str(series),
                          radius, angle)
      self
    end


Class: Tk::Tcllib::Plotchart::Stripchart

Class | Tk::Tcllib::Plotchart::Stripchart
In: | tk/lib/tkextlib/tcllib/plotchart.rb
Parent: | XYPlot

Constants

TkCommandNames = [ 'canvas'.freeze, '::Plotchart::createStripchart'.freeze


Class: Tk::Tcllib::Plotchart::Timechart

Class | Tk::Tcllib::Plotchart::Timechart
In: | tk/lib/tkextlib/tcllib/plotchart.rb
Parent: | TkCanvas

Methods

milestone new period vertline

Included Modules

ChartMethod

Constants

TkCommandNames = [ 'canvas'.freeze, '::Plotchart::createTimechart'.freeze

Public Class methods

new(*args)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 683
    def initialize(*args)
      # args := ([parent,] time_begin, time_end, items [, keys])
      # time_begin := String of time format (e.g. "1 january 2004")
      # time_end   := String of time format (e.g. "1 january 2004")
      # items := Expected/maximum number of items
      #          ( This determines the vertical spacing. )
      if args[0].kind_of?(String)
        @time_begin = args.shift
        @time_end   = args.shift
        @items      = args.shift

        super(*args) # create canvas widget
      else
        parent = args.shift

        @time_begin = args.shift
        @time_end   = args.shift
        @items      = args.shift

        if parent.kind_of?(TkCanvas)
          @path = parent.path
        else
          super(parent, *args) # create canvas widget
        end
      end

      @chart = _create_chart
    end

Public Instance methods

milestone(txt, time, col=None)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 724
    def milestone(txt, time, col=None)
      tk_call_without_enc(@chart, 'milestone', txt, time, col)
      self
    end
period(txt, time_begin, time_end, col=None)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 719
    def period(txt, time_begin, time_end, col=None)
      tk_call_without_enc(@chart, 'period', txt, time_begin, time_end, col)
      self
    end
vertline(txt, time)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 729
    def vertline(txt, time)
      tk_call_without_enc(@chart, 'vertline', txt, time)
      self
    end


Class: Tk::Tcllib::Plotchart::XYPlot

Class | Tk::Tcllib::Plotchart::XYPlot
In: | tk/lib/tkextlib/tcllib/plotchart.rb
Parent: | TkCanvas

Methods

__destroy_hook__ color_map contourbox contourfill contourlines dataconfig grid_cells new plot

Included Modules

ChartMethod

Constants

TkCommandNames = [ 'canvas'.freeze, '::Plotchart::createXYPlot'.freeze

Public Class methods

new(*args)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 236
    def initialize(*args) # args := ([parent,] xaxis, yaxis [, keys])
                          # xaxis := Array of [minimum, maximum, stepsize]
                          # yaxis := Array of [minimum, maximum, stepsize]
      if args[0].kind_of?(Array)
        @xaxis = args.shift
        @yaxis = args.shift

        super(*args) # create canvas widget
      else
        parent = args.shift

        @xaxis = args.shift
        @yaxis = args.shift

        if parent.kind_of?(TkCanvas)
          @path = parent.path
        else
          super(parent, *args) # create canvas widget
        end
      end

      @chart = _create_chart
    end

Public Instance methods

__destroy_hook__()

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 267
    def __destroy_hook__
      Tk::Tcllib::Plotchart::PlotSeries::SeriesID_TBL.delete(@path)
    end
color_map(colors)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 306
    def color_map(colors)
      colors = array2tk_list(colors) if colors.kind_of?(Array)

      tk_call_without_enc(@chart, 'colorMap', colors)
      self
    end
contourbox(xcrd, ycrd, vals, klasses=None)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 296
    def contourbox(xcrd, ycrd, vals, klasses=None)
      xcrd = array2tk_list(xcrd) if xcrd.kind_of?(Array)
      ycrd = array2tk_list(ycrd) if ycrd.kind_of?(Array)
      vals = array2tk_list(vals) if vals.kind_of?(Array)
      clss = array2tk_list(clss) if clss.kind_of?(Array)

      tk_call_without_enc(@chart, 'contourbox', xcrd, ycrd, vals, clss)
      self
    end
contourfill(xcrd, ycrd, vals, klasses=None)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 286
    def contourfill(xcrd, ycrd, vals, klasses=None)
      xcrd = array2tk_list(xcrd) if xcrd.kind_of?(Array)
      ycrd = array2tk_list(ycrd) if ycrd.kind_of?(Array)
      vals = array2tk_list(vals) if vals.kind_of?(Array)
      clss = array2tk_list(clss) if clss.kind_of?(Array)

      tk_call_without_enc(@chart, 'contourfill', xcrd, ycrd, vals, clss)
      self
    end
contourlines(xcrd, ycrd, vals, clss=None)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 276
    def contourlines(xcrd, ycrd, vals, clss=None)
      xcrd = array2tk_list(xcrd) if xcrd.kind_of?(Array)
      ycrd = array2tk_list(ycrd) if ycrd.kind_of?(Array)
      vals = array2tk_list(vals) if vals.kind_of?(Array)
      clss = array2tk_list(clss) if clss.kind_of?(Array)

      tk_call_without_enc(@chart, 'contourlines', xcrd, ycrd, vals, clss)
      self
    end
dataconfig(series, key, value=None)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 321
    def dataconfig(series, key, value=None)
      if key.kind_of?(Hash)
        tk_call_without_enc(@chart, 'dataconfig', series, *hash_kv(key, true))
      else
        tk_call_without_enc(@chart, 'dataconfig', series,
                            "-#{key}", _get_eval_enc_str(value))
      end
    end
grid_cells(xcrd, ycrd)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 313
    def grid_cells(xcrd, ycrd)
      xcrd = array2tk_list(xcrd) if xcrd.kind_of?(Array)
      ycrd = array2tk_list(ycrd) if ycrd.kind_of?(Array)

      tk_call_without_enc(@chart, 'grid', xcrd, ycrd)
      self
    end
plot(series, x, y)

[Source]

# File tk/lib/tkextlib/tcllib/plotchart.rb, line 271
    def plot(series, x, y)
      tk_call_without_enc(@chart, 'plot', _get_eval_enc_str(series), x, y)
      self
    end


Module: Tk::Tcllib::Style

Module | Tk::Tcllib::Style
In: | tk/lib/tkextlib/tcllib/style.rb

Methods

names names not_available package_name package_version use use

Constants

PACKAGE_NAME = 'style'.freeze

Public Class methods

names()

[Source]

# File tk/lib/tkextlib/tcllib/style.rb, line 31
    def self.names
      Tk::Tcllib::Style.not_available
    end
names()

[Source]

# File tk/lib/tkextlib/tcllib/style.rb, line 53
    def self.names
      tk_split_simplelist(tk_call('style::names'))
    end
not_available()

[Source]

# File tk/lib/tkextlib/tcllib/style.rb, line 27
    def self.not_available
      fail RuntimeError, "'tkextlib/tcllib/style' extension is not available on your current environment."
    end
package_name()

[Source]

# File tk/lib/tkextlib/tcllib/style.rb, line 15
    def self.package_name
      PACKAGE_NAME
    end
package_version()

[Source]

# File tk/lib/tkextlib/tcllib/style.rb, line 19
    def self.package_version
      begin
        TkPackage.require('style')
      rescue
        ''
      end
    end
use(style)

[Source]

# File tk/lib/tkextlib/tcllib/style.rb, line 35
    def self.use(style)
      Tk::Tcllib::Style.not_available
    end
use(style)

[Source]

# File tk/lib/tkextlib/tcllib/style.rb, line 57
    def self.use(style)
      tk_call('style::use', style)
    end


Class: Tk::Tcllib::Swaplist_Dialog

Class | Tk::Tcllib::Swaplist_Dialog
In: | tk/lib/tkextlib/tcllib/swaplist.rb
Parent: | TkWindow

Methods

cget configinfo configure display display new package_name package_version selected show show status value

Constants

PACKAGE_NAME | = | 'swaplist'.freeze
TkCommandNames | = | ['::swaplist::swaplist'.freeze].freeze
WidgetClassName | = | 'Swaplist'.freeze

Public Class methods

display(*args)

[Source]

# File tk/lib/tkextlib/tcllib/swaplist.rb, line 43
  def self.display(*args)
    self.show(*args)
  end
new(*args)

[Source]

# File tk/lib/tkextlib/tcllib/swaplist.rb, line 47
  def initialize(*args)
    # args = (parent=nil, complete_list=[], selected_list=[], keys=nil)
    keys = args.pop
    if keys.kind_of?(Hash)
      @selected_list = args.pop
      @complete_list = args.pop
      @keys = _symbolkey2str(keys)
      args.push(keys)
    else
      @selected_list = keys
      @complete_list = args.pop
      @keys = {}
    end

    @selected_list = [] unless @selected_list
    @complete_list = [] unless @complete_list

    @variable = TkVariable.new
    @status = nil

    super(*args)
  end
package_name()

[Source]

# File tk/lib/tkextlib/tcllib/swaplist.rb, line 18
    def self.package_name
      PACKAGE_NAME
    end
package_version()

[Source]

# File tk/lib/tkextlib/tcllib/swaplist.rb, line 22
    def self.package_version
      begin
        TkPackage.require('swaplist')
      rescue
        ''
      end
    end
show(*args)

[Source]

# File tk/lib/tkextlib/tcllib/swaplist.rb, line 38
  def self.show(*args)
    dialog = self.new(*args)
    dialog.show
    [dialog.status, dialog.value]
  end

Public Instance methods

cget(slot)

[Source]

# File tk/lib/tkextlib/tcllib/swaplist.rb, line 93
  def cget(slot)
    slot = slot.to_s
    if slot == 'complete_list'
      @complete_list
    elsif slot == 'selected_list'
      @selected_list
    else
      @keys[slot]
    end
  end
configinfo(slot = nil)

[Source]

# File tk/lib/tkextlib/tcllib/swaplist.rb, line 131
  def configinfo(slot = nil)
    if slot
      slot = slot.to_s
      if slot == 'complete_list'
        [ slot, nil, nil, nil, @complete_list ]
      elsif slot == 'selected_list'
        [ slot, nil, nil, nil, @selected_list ]
      else
        [ slot, nil, nil, nil, @keys[slot] ]
      end
    else
      @keys.collect{|k, v| [ k, nil, nil, nil, v ] }           \
      << [ 'complete_list', nil, nil, nil, @complete_list ]   \
      << [ 'selected_list', nil, nil, nil, @selected_list ]
    end
  end
configure(slot, value=None)

[Source]

# File tk/lib/tkextlib/tcllib/swaplist.rb, line 104
  def configure(slot, value=None)
    if slot.kind_of?(Hash)
      slot.each{|k, v| configure(k, v)}
    else
      slot = slot.to_s
      value = _symbolkey2str(value) if value.kind_of?(Hash)
      if value && value != None
        if slot == 'complete_list'
          @complete_list = value
        elsif slot == 'selected_list'
          @selected_list = value
        else
          @keys[slot] = value
        end
      else
        if slot == 'complete_list'
          @complete_list = []
        elsif slot == 'selected_list'
          @selected_list = []
        else
          @keys.delete(slot)
        end
      end
    end
    self
  end
display()

Alias for show

selected()

Alias for value

show()

[Source]

# File tk/lib/tkextlib/tcllib/swaplist.rb, line 75
  def show
    @variable.value = ''
    @status = bool(tk_call(self.class::TkCommandNames[0],
                           @path, @variable,
                           @complete_list, @selected_list,
                           *hash_kv(@keys)))
  end
status()

[Source]

# File tk/lib/tkextlib/tcllib/swaplist.rb, line 84
  def status
    @status
  end
value()

[Source]

# File tk/lib/tkextlib/tcllib/swaplist.rb, line 88
  def value
    @variable.list
  end


Class: Tk::Tcllib::Tablelist

Class | Tk::Tcllib::Tablelist
In: | tk/lib/tkextlib/tcllib/tablelist_core.rb
Parent: | TkWindow

Methods

activate activate_cell activatecell bbox bodypath bodytag cancel_editing cancelediting cellindex cellselection_anchor cellselection_clear cellselection_includes cellselection_set columncount columnindex containing containing_cell containing_column containingcell containingcolumn curcellselection curselection delete delete_columns delete_items deletecolumns deleteitems edit_cell editcell editwinpath entrypath fill_column fillcolumn finish_editing finishediting get get_attrib get_cells get_columns get_keys getcells getcolumns getkeys imagelabelpath index insert insert_columnlist insert_columns insert_list insertcolumnlist insertcolumns insertlist itemlistvar labelpath labels move move_column movecolumn nearest nearest_cell nearest_column nearestcell nearestcolumn package_name package_version reject_input rejectinput reset_sortinfo resetsortinfo scan_dragto scan_mark see see_cell see_column seecell seecolumn selection_anchor selection_clear selection_includes selection_set separatorpath separators set_attrib size sort sort_by_column sort_by_column_decreasing sort_by_column_increasing sort_decreasing sort_increasing sortcolumn sortorder toggle_visibility togglevisibility use_Tile? windowpath

Included Modules

Tk::Tcllib::TablelistItemConfig Scrollable

Constants

PACKAGE_NAME | = | 'Tablelist_tile'.freeze
PACKAGE_NAME | = | 'Tablelist'.freeze
TkCommandNames | = | ['::tablelist::tablelist'.freeze].freeze
WidgetClassName | = | 'Tablelist'.freeze
DEFAULT_sortByColumn_cmd | = | '::tablelist::sortByColumn'

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 19
      def self.package_name
        PACKAGE_NAME
      end
package_version()

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 23
      def self.package_version
        begin
          TkPackage.require(self.package_name)
        rescue
          ''
        end
      end
use_Tile?()

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 31
      def self.use_Tile?
        (Tk::Tcllib::Tablelist_usingTile)? true: false
      end

Public Instance methods

activate(index)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 231
  def activate(index)
    tk_send('activate', _to_idx(index))
    self
  end
activate_cell(index)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 236
  def activate_cell(index)
    tk_send('activatecell', _to_idx(index))
    self
  end
activatecell(index)

Alias for activate_cell

bbox(index)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 259
  def bbox(index)
    list(tk_send('bbox', _to_idx(index)))
  end
bodypath()

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 263
  def bodypath
    window(tk_send('bodypath'))
  end
bodytag()

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 267
  def bodytag
    TkBindTag.new_by_name(tk_send('bodytag'))
  end
cancel_editing()

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 271
  def cancel_editing
    tk_send('cancelediting')
    self
  end
cancelediting()

Alias for cancel_editing

cellindex(idx)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 277
  def cellindex(idx)
    _from_idx(tk_send('cellindex', _to_idx(idx)))
  end
cellselection_anchor(idx)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 281
  def cellselection_anchor(idx)
    tk_send('cellselection', 'anchor', _to_idx(idx))
    self
  end
cellselection_clear(first, last=nil)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 286
  def cellselection_clear(first, last=nil)
    if first.kind_of?(Array)
      tk_send('cellselection', 'clear', first.collect{|idx| _to_idx(idx)})
    else
      first = _to_idx(first)
      last = (last)? _to_idx(last): first
      tk_send('cellselection', 'clear', first, last)
    end
    self
  end
cellselection_includes(idx)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 297
  def cellselection_includes(idx)
    bool(tk_send('cellselection', 'includes', _to_idx(idx)))
  end
cellselection_set(first, last=nil)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 301
  def cellselection_set(first, last=nil)
    if first.kind_of?(Array)
      tk_send('cellselection', 'set', first.collect{|idx| _to_idx(idx)})
    else
      first = _to_idx(first)
      last = (last)? _to_idx(last): first
      tk_send('cellselection', 'set', first, last)
    end
    self
  end
columncount()

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 312
  def columncount
    number(tk_send('columncount'))
  end
columnindex(idx)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 316
  def columnindex(idx)
    number(tk_send('columnindex', _to_idx(idx)))
  end
containing(y)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 320
  def containing(y)
    idx = num_or_str(tk_send('containing', y))
    (idx.kind_of?(Fixnum) && idx < 0)?  nil: idx
  end
containing_cell(x, y)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 325
  def containing_cell(x, y)
    idx = _from_idx(tk_send('containingcell', x, y))
    if idx.kind_of?(Array)
      [
        ((idx[0].kind_of?(Fixnum) && idx[0] < 0)?  nil: idx[0]),
        ((idx[1].kind_of?(Fixnum) && idx[1] < 0)?  nil: idx[1])
      ]
    else
      idx
    end
  end
containing_column(x)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 338
  def containing_column(x)
    idx = num_or_str(tk_send('containingcolumn', x))
    (idx.kind_of?(Fixnum) && idx < 0)?  nil: idx
  end
containingcell(x, y)

Alias for containing_cell

containingcolumn(x)

Alias for containing_column

curcellselection()

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 344
  def curcellselection
    simplelist(tk_send('curcellselection')).collect!{|idx| _from_idx(idx)}
  end
curselection()

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 348
  def curselection
    list(tk_send('curselection'))
  end
delete(first, last=nil)

Alias for delete_items

delete_columns(first, last=nil)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 365
  def delete_columns(first, last=nil)
    if first.kind_of?(Array)
      tk_send('deletecolumns', first.collect{|idx| _to_idx(idx)})
    else
      first = _to_idx(first)
      last = (last)? _to_idx(last): first
      tk_send('deletecolumns', first, last)
    end
    self
  end
delete_items(first, last=nil)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 352
  def delete_items(first, last=nil)
    if first.kind_of?(Array)
      tk_send('delete', first.collect{|idx| _to_idx(idx)})
    else
      first = _to_idx(first)
      last = (last)? _to_idx(last): first
      tk_send('delete', first, last)
    end
    self
  end
deletecolumns(first, last=nil)

Alias for delete_columns

deleteitems(first, last=nil)

Alias for delete_items

edit_cell(idx)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 377
  def edit_cell(idx)
    tk_send('editcell', _to_idx(idx))
    self
  end
editcell(idx)

Alias for edit_cell

editwinpath()

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 383
  def editwinpath
    window(tk_send('editwinpath'))
  end
entrypath()

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 387
  def entrypath
    window(tk_send('entrypath'))
  end
fill_column(idx, txt)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 391
  def fill_column(idx, txt)
    tk_send('fillcolumn', _to_idx(idx), txt)
    self
  end
fillcolumn(idx, txt)

Alias for fill_column

finish_editing()

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 397
  def finish_editing
    tk_send('finishediting')
    self
  end
finishediting()

Alias for finish_editing

get(first, last=nil)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 403
  def get(first, last=nil)
    if first.kind_of?(Array)
      simplelist(tk_send('get', first.collect{|idx| _to_idx(idx)})).collect!{|elem| simplelist(elem) }
    else
      first = _to_idx(first)
      last = (last)? _to_idx(last): first
      simplelist(tk_send('get', first, last))
    end
  end
get_attrib(name=nil)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 242
  def get_attrib(name=nil)
    if name && name != None
      tk_send('attrib', name)
    else
      ret = []
      lst = simplelist(tk_send('attrib'))
      until lst.empty?
        ret << ( [lst.shift] << lst.shift )
      end
      ret
    end
  end
get_cells(first, last=nil)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 413
  def get_cells(first, last=nil)
    if first.kind_of?(Array)
      simplelist(tk_send('getcells', first.collect{|idx| _to_idx(idx)})).collect!{|elem| simplelist(elem) }
    else
      first = _to_idx(first)
      last = (last)? _to_idx(last): first
      simplelist(tk_send('getcells', first, last))
    end
  end
get_columns(first, last=nil)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 424
  def get_columns(first, last=nil)
    if first.kind_of?(Array)
      simplelist(tk_send('getcolumns', first.collect{|idx| _to_idx(idx)})).collect!{|elem| simplelist(elem) }
    else
      first = _to_idx(first)
      last = (last)? _to_idx(last): first
      simplelist(tk_send('getcolumns', first, last))
    end
  end
get_keys(first, last=nil)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 435
  def get_keys(first, last=nil)
    if first.kind_of?(Array)
      simplelist(tk_send('getkeys', first.collect{|idx| _to_idx(idx)})).collect!{|elem| simplelist(elem) }
    else
      first = _to_idx(first)
      last = (last)? _to_idx(last): first
      simplelist(tk_send('getkeys', first, last))
    end
  end
getcells(first, last=nil)

Alias for get_cells

getcolumns(first, last=nil)

Alias for get_columns

getkeys(first, last=nil)

Alias for get_keys

imagelabelpath(idx)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 446
  def imagelabelpath(idx)
    window(tk_send('imagelabelpath', _to_idx(idx)))
  end
index(idx)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 450
  def index(idx)
    number(tk_send('index', _to_idx(idx)))
  end
insert(idx, *items)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 454
  def insert(idx, *items)
    tk_send('insert', _to_idx(idx), *items)
    self
  end
insert_columnlist(idx, columnlist)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 459
  def insert_columnlist(idx, columnlist)
    tk_send('insertcolumnlist', _to_idx(idx), columnlist)
    self
  end
insert_columns(idx, *args)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 465
  def insert_columns(idx, *args)
    tk_send('insertcolums', _to_idx(idx), *args)
    self
  end
insert_list(idx, list)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 471
  def insert_list(idx, list)
    tk_send('insertlist', _to_idx(idx), list)
    self
  end
insertcolumnlist(idx, columnlist)

Alias for insert_columnlist

insertcolumns(idx, *args)

Alias for insert_columns

insertlist(idx, list)

Alias for insert_list

itemlistvar()

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 477
  def itemlistvar
    TkVarAccess.new(tk_send('itemlistvar'))
  end
labelpath(idx)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 481
  def labelpath(idx)
    window(tk_send('labelpath', _to_idx(idx)))
  end
labels()

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 485
  def labels
    simplelist(tk_send('labels'))
  end
move(src, target)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 489
  def move(src, target)
    tk_send('move', _to_idx(src), _to_idx(target))
    self
  end
move_column(src, target)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 494
  def move_column(src, target)
    tk_send('movecolumn', _to_idx(src), _to_idx(target))
    self
  end
movecolumn(src, target)

Alias for move_column

nearest(y)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 500
  def nearest(y)
    _from_idx(tk_send('nearest', y))
  end
nearest_cell(x, y)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 504
  def nearest_cell(x, y)
    _from_idx(tk_send('nearestcell', x, y))
  end
nearest_column(x)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 509
  def nearest_column(x)
    _from_idx(tk_send('nearestcolumn', x))
  end
nearestcell(x, y)

Alias for nearest_cell

nearestcolumn(x)

Alias for nearest_column

reject_input()

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 514
  def reject_input
    tk_send('rejectinput')
    self
  end
rejectinput()

Alias for reject_input

reset_sortinfo()

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 520
  def reset_sortinfo
    tk_send('resetsortinfo')
    self
  end
resetsortinfo()

Alias for reset_sortinfo

scan_dragto(x, y)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 531
  def scan_dragto(x, y)
    tk_send('scan', 'dragto', x, y)
    self
  end
scan_mark(x, y)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 526
  def scan_mark(x, y)
    tk_send('scan', 'mark', x, y)
    self
  end
see(idx)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 536
  def see(idx)
    tk_send('see', _to_idx(idx))
    self
  end
see_cell(idx)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 541
  def see_cell(idx)
    tk_send('seecell', _to_idx(idx))
    self
  end
see_column(idx)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 547
  def see_column(idx)
    tk_send('seecolumn', _to_idx(idx))
    self
  end
seecell(idx)

Alias for see_cell

seecolumn(idx)

Alias for see_column

selection_anchor(idx)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 553
  def selection_anchor(idx)
    tk_send('selection', 'anchor', _to_idx(idx))
    self
  end
selection_clear(first, last=nil)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 558
  def selection_clear(first, last=nil)
    if first.kind_of?(Array)
      tk_send('selection', 'clear', first.collect{|idx| _to_idx(idx)})
    else
      first = _to_idx(first)
      last = (last)? _to_idx(last): first
      tk_send('selection', 'clear', first, last)
    end
    self
  end
selection_includes(idx)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 569
  def selection_includes(idx)
    bool(tk_send('selection', 'includes', _to_idx(idx)))
  end
selection_set(first, last=nil)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 573
  def selection_set(first, last=nil)
    if first.kind_of?(Array)
      tk_send('selection', 'set', first.collect{|idx| _to_idx(idx)})
    else
      first = _to_idx(first)
      last = (last)? _to_idx(last): first
      tk_send('selection', 'set', first, last)
    end
    self
  end
separatorpath(idx=nil)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 584
  def separatorpath(idx=nil)
    if idx
      window(tk_send('separatorpath', _to_idx(idx)))
    else
      window(tk_send('separatorpath'))
    end
  end
separators()

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 592
  def separators
    simplelist(tk_send('separators')).collect!{|w| window(w)}
  end
set_attrib(*args)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 254
  def set_attrib(*args)
    tk_send('attrib', *(args.flatten))
    self
  end
size()

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 596
  def size
    number(tk_send('size'))
  end
sort(order=nil)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 600
  def sort(order=nil)
    if order
      order = order.to_s
      order = '-' << order if order[0] != ?-
      if order.length < 2
        order = nil
      end
    end
    if order
      tk_send('sort', order)
    else
      tk_send('sort')
    end
    self
  end
sort_by_column(idx, order=nil)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 626
  def sort_by_column(idx, order=nil)
    if order
      order = order.to_s
      order = '-' << order if order[0] != ?-
      if order.length < 2
        order = nil
      end
    end
    if order
      tk_send('sortbycolumn', _to_idx(idx), order)
    else
      tk_send('sortbycolumn', _to_idx(idx))
    end
    self
  end
sort_by_column_decreasing(idx)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 645
  def sort_by_column_decreasing(idx)
    tk_send('sortbycolumn', _to_idx(idx), '-decreasing')
    self
  end
sort_by_column_increasing(idx)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 641
  def sort_by_column_increasing(idx)
    tk_send('sortbycolumn', _to_idx(idx), '-increasing')
    self
  end
sort_decreasing()

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 619
  def sort_decreasing
    tk_send('sort', '-decreasing')
    self
  end
sort_increasing()

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 615
  def sort_increasing
    tk_send('sort', '-increasing')
    self
  end
sortcolumn()

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 650
  def sortcolumn
    idx = num_or_str(tk_send('sortcolum'))
    (idx.kind_of?(Fixnum) && idx < 0)?  nil: idx
  end
sortorder()

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 655
  def sortorder
    tk_send('sortorder')
  end
toggle_visibility(first, last=nil)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 659
  def toggle_visibility(first, last=nil)
    if first.kind_of?(Array)
      tk_send('togglevisibility', first.collect{|idx| _to_idx(idx)})
    else
      first = _to_idx(first)
      last = (last)? _to_idx(last): first
      tk_send('togglevisibility', first, last)
    end
    self
  end
togglevisibility(first, last=nil)

Alias for toggle_visibility

windowpath(idx)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 671
  def windowpath(idx)
    window(tk_send('windowpath', _to_idx(idx)))
  end


Module: Tk::Tcllib::TablelistItemConfig

Module | Tk::Tcllib::TablelistItemConfig
In: | tk/lib/tkextlib/tcllib/tablelist_core.rb

Methods

__item_cget_cmd __item_config_cmd cell_cget cell_configinfo cell_configure cellcget cellconfiginfo cellconfigure column_cget column_configinfo column_configure columncget columnconfiginfo columnconfigure current_cell_configinfo current_cellconfiginfo current_column_configinfo current_columnconfiginfo current_row_configinfo current_rowconfiginfo row_cget row_configinfo row_configure rowcget rowconfiginfo rowconfigure

Included Modules

TkItemConfigMethod

Public Instance methods

__item_cget_cmd(mixed_id)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 63
  def __item_cget_cmd(mixed_id)
    [self.path, mixed_id[0] + 'cget', _to_idx(mixed_id[1])]
  end
__item_config_cmd(mixed_id)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 66
  def __item_config_cmd(mixed_id)
    [self.path, mixed_id[0] + 'configure', _to_idx(mixed_id[1])]
  end
cell_cget(tagOrId, option)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 70
  def cell_cget(tagOrId, option)
    itemcget(['cell', tagOrId], option)
  end
cell_configinfo(tagOrId, slot=nil)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 76
  def cell_configinfo(tagOrId, slot=nil)
    itemconfiginfo(['cell', tagOrId], slot)
  end
cell_configure(tagOrId, slot, value=None)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 73
  def cell_configure(tagOrId, slot, value=None)
    itemconfigure(['cell', tagOrId], slot, value)
  end
cellcget(tagOrId, option)

Alias for cell_cget

cellconfiginfo(tagOrId, slot=nil)

Alias for cell_configinfo

cellconfigure(tagOrId, slot, value=None)

Alias for cell_configure

column_cget(tagOrId, option)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 87
  def column_cget(tagOrId, option)
    itemcget(['column', tagOrId], option)
  end
column_configinfo(tagOrId, slot=nil)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 93
  def column_configinfo(tagOrId, slot=nil)
    itemconfiginfo(['column', tagOrId], slot)
  end
column_configure(tagOrId, slot, value=None)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 90
  def column_configure(tagOrId, slot, value=None)
    itemconfigure(['column', tagOrId], slot, value)
  end
columncget(tagOrId, option)

Alias for column_cget

columnconfiginfo(tagOrId, slot=nil)

Alias for column_configinfo

columnconfigure(tagOrId, slot, value=None)

Alias for column_configure

current_cell_configinfo(tagOrId, slot=nil)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 79
  def current_cell_configinfo(tagOrId, slot=nil)
    current_itemconfiginfo(['cell', tagOrId], slot)
  end
current_cellconfiginfo(tagOrId, slot=nil)

Alias for current_cell_configinfo

current_column_configinfo(tagOrId, slot=nil)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 96
  def current_column_configinfo(tagOrId, slot=nil)
    current_itemconfiginfo(['column', tagOrId], slot)
  end
current_columnconfiginfo(tagOrId, slot=nil)

Alias for current_column_configinfo

current_row_configinfo(tagOrId, slot=nil)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 113
  def current_row_configinfo(tagOrId, slot=nil)
    current_itemconfiginfo(['row', tagOrId], slot)
  end
current_rowconfiginfo(tagOrId, slot=nil)

Alias for current_row_configinfo

row_cget(tagOrId, option)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 104
  def row_cget(tagOrId, option)
    itemcget(['row', tagOrId], option)
  end
row_configinfo(tagOrId, slot=nil)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 110
  def row_configinfo(tagOrId, slot=nil)
    itemconfiginfo(['row', tagOrId], slot)
  end
row_configure(tagOrId, slot, value=None)

[Source]

# File tk/lib/tkextlib/tcllib/tablelist_core.rb, line 107
  def row_configure(tagOrId, slot, value=None)
    itemconfigure(['row', tagOrId], slot, value)
  end
rowcget(tagOrId, option)

Alias for row_cget

rowconfiginfo(tagOrId, slot=nil)

Alias for row_configinfo

rowconfigure(tagOrId, slot, value=None)

Alias for row_configure


Module: Tk::Tcllib::Tkpiechart

Module | Tk::Tcllib::Tkpiechart
In: | tk/lib/tkextlib/tcllib/tkpiechart.rb

Methods

package_name package_version

Classes and Modules

Module Tk::Tcllib::Tkpiechart::ConfigMethod
Class Tk::Tcllib::Tkpiechart::BoxLabeler
Class Tk::Tcllib::Tkpiechart::Label
Class Tk::Tcllib::Tkpiechart::PeripheralLabeler
Class Tk::Tcllib::Tkpiechart::Pie
Class Tk::Tcllib::Tkpiechart::PieChartObj
Class Tk::Tcllib::Tkpiechart::Slice

Constants

PACKAGE_NAME = 'tkpiechart'.freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/tcllib/tkpiechart.rb, line 25
  def self.package_name
    PACKAGE_NAME
  end
package_version()

[Source]

# File tk/lib/tkextlib/tcllib/tkpiechart.rb, line 29
  def self.package_version
    begin
      TkPackage.require('tkpiechart')
    rescue
      ''
    end
  end


Class: Tk::Tcllib::Tkpiechart::BoxLabeler

Class | Tk::Tcllib::Tkpiechart::BoxLabeler
In: | tk/lib/tkextlib/tcllib/tkpiechart.rb
Parent: | TkcItem

Included Modules

ConfigMethod


Module: Tk::Tcllib::Tkpiechart::ConfigMethod

Module | Tk::Tcllib::Tkpiechart::ConfigMethod
In: | tk/lib/tkextlib/tcllib/tkpiechart.rb

Methods

__cget_cmd

Included Modules

TkConfigMethod

Public Instance methods

__cget_cmd()

[Source]

# File tk/lib/tkextlib/tcllib/tkpiechart.rb, line 45
    def __cget_cmd
      ['::switched::cget', self.tag]
    end


Class: Tk::Tcllib::Tkpiechart::Label

Class | Tk::Tcllib::Tkpiechart::Label
In: | tk/lib/tkextlib/tcllib/tkpiechart.rb
Parent: | TkcItem

Included Modules

ConfigMethod


Class: Tk::Tcllib::Tkpiechart::PeripheralLabeler

Class | Tk::Tcllib::Tkpiechart::PeripheralLabeler
In: | tk/lib/tkextlib/tcllib/tkpiechart.rb
Parent: | TkcItem

Included Modules

ConfigMethod


Class: Tk::Tcllib::Tkpiechart::Pie

Class | Tk::Tcllib::Tkpiechart::Pie
In: | tk/lib/tkextlib/tcllib/tkpiechart.rb
Parent: | TkcItem

Methods

_delete_slice _entry_slice canvas delete delete_slice new_slice selected_slices tag tag_key

Included Modules

ConfigMethod

Public Instance methods

_delete_slice(slice)

[Source]

# File tk/lib/tkextlib/tcllib/tkpiechart.rb, line 122
    def _delete_slice(slice)
      @slice_tbl.delete(slice.to_eval)
    end
_entry_slice(slice)

[Source]

# File tk/lib/tkextlib/tcllib/tkpiechart.rb, line 119
    def _entry_slice(slice)
      @slice_tbl[slice.to_eval] = slice
    end
canvas()

[Source]

# File tk/lib/tkextlib/tcllib/tkpiechart.rb, line 116
    def canvas
      @c
    end
delete()

[Source]

# File tk/lib/tkextlib/tcllib/tkpiechart.rb, line 126
    def delete
      tk_call_without_enc('::stooop::delete', @tag_key)
      CItemID_TBL[@path].delete(@id) if CItemID_TBL[@path]
      self
    end
delete_slice(slice)

[Source]

# File tk/lib/tkextlib/tcllib/tkpiechart.rb, line 136
    def delete_slice(slice)
      unless slice.kind_of?(Slice)
        unless (slice = @slice_tbl[slice])
          return tk_call_without_enc('pie::deleteSlice', @tag_key, slice)
        end
      end
      unless slice.kind_of?(Slice) && slice.pie == self
        fail ArgumentError, "argument is not a slice of self"
      end
      slice.delete
    end
new_slice(text=None)

[Source]

# File tk/lib/tkextlib/tcllib/tkpiechart.rb, line 132
    def new_slice(text=None)
      Slice.new(self, text)
    end
selected_slices()

[Source]

# File tk/lib/tkextlib/tcllib/tkpiechart.rb, line 148
    def selected_slices
      tk_split_simplelist(tk_call_without_enc('pie::selectedSlices',
                                              @tag_key)).collect{|slice|
        @slice_tbl[slice] || Slice.new(:no_create, self, slice)
      }
    end
tag()

[Source]

# File tk/lib/tkextlib/tcllib/tkpiechart.rb, line 113
    def tag
      @tag
    end
tag_key()

[Source]

# File tk/lib/tkextlib/tcllib/tkpiechart.rb, line 110
    def tag_key
      @tag_key
    end


Class: Tk::Tcllib::Tkpiechart::PieChartObj

Class | Tk::Tcllib::Tkpiechart::PieChartObj
In: | tk/lib/tkextlib/tcllib/tkpiechart.rb
Parent: | TkcItem

Included Modules

ConfigMethod


Class: Tk::Tcllib::Tkpiechart::Slice

Class | Tk::Tcllib::Tkpiechart::Slice
In: | tk/lib/tkextlib/tcllib/tkpiechart.rb
Parent: | TkcItem

Methods

delete label new pie size tag tag_key

Included Modules

ConfigMethod

Public Class methods

new(pie, *args)

[Source]

# File tk/lib/tkextlib/tcllib/tkpiechart.rb, line 167
    def initialize(pie, *args)
      unless pie.kind_of?(Pie) && pie != :no_create
        fail ArgumentError, "expects TkPiechart::Pie for 1st argument"
      end

      if pie == :no_create
        @pie, @tag_key = args
      else
        text = args[0] || None
        @pie = pie
        @tag_key = tk_call_without_enc('pie::newSlice', @pie.tag_key, text)
      end
      @parent = @c = @pie.canvas
      @path = @parent.path

      @pie._entry_slice(self)

      @id = "slices(#{@tag_key})"
      @tag = TkcNamedTag.new(@pie.canvas, @id)

      CItemID_TBL[@path] = {} unless CItemID_TBL[@path]
      CItemID_TBL[@path][@id] = self
    end

Public Instance methods

delete()

[Source]

# File tk/lib/tkextlib/tcllib/tkpiechart.rb, line 201
    def delete
      tk_call_without_enc('pie::deleteSlice', @pie.tag_key, @tag_key)
      CItemID_TBL[@path].delete(@id) if CItemID_TBL[@path]
      @pie._delete_slice(self)
      self
    end
label(text)

[Source]

# File tk/lib/tkextlib/tcllib/tkpiechart.rb, line 214
    def label(text)
      tk_call_without_enc('pie::labelSlice', @pie.tag_key, @tag_key, text)
      self
    end
pie()

[Source]

# File tk/lib/tkextlib/tcllib/tkpiechart.rb, line 197
    def pie
      @pie
    end
size(share, disp=None)

[Source]

# File tk/lib/tkextlib/tcllib/tkpiechart.rb, line 208
    def size(share, disp=None)
      tk_call_without_enc('pie::sizeSlice',
                          @pie.tag_key, @tag_key, share, disp)
      self
    end
tag()

[Source]

# File tk/lib/tkextlib/tcllib/tkpiechart.rb, line 194
    def tag
      @tag
    end
tag_key()

[Source]

# File tk/lib/tkextlib/tcllib/tkpiechart.rb, line 191
    def tag_key
      @tag_key
    end


Module: Tk::Tcllib::Tooltip

Module | Tk::Tcllib::Tooltip
In: | tk/lib/tkextlib/tcllib/tooltip.rb

Methods

clear clear_children clear_glob clear_widgets database_class database_classname delay delay= disable enable erase off on package_name package_version register

Constants

PACKAGE_NAME | = | 'tooltip'.freeze
WidgetClassName | = | 'Tooltip'.freeze

Public Class methods

clear(glob_path_pat = None)

[Source]

# File tk/lib/tkextlib/tcllib/tooltip.rb, line 44
  def self.clear(glob_path_pat = None)
    self.clear_glob(glob_path_pat)
  end
clear_children(*args)

[Source]

# File tk/lib/tkextlib/tcllib/tooltip.rb, line 56
  def self.clear_children(*args)
    self.clear_glob("{#{args.collect{|w| s = _get_eval_string(w); "#{s},#{s}.*"}.join(',')}}")
  end
clear_glob(glob_path_pat)

[Source]

# File tk/lib/tkextlib/tcllib/tooltip.rb, line 48
  def self.clear_glob(glob_path_pat)
    tk_call_without_enc('::tooltip::tooltip', 'clear', glob_path_pat)
  end
clear_widgets(*args)

[Source]

# File tk/lib/tkextlib/tcllib/tooltip.rb, line 52
  def self.clear_widgets(*args)
    self.clear_glob("{#{args.collect{|w| _get_eval_string(w)}.join(',')}}")
  end
database_class()

[Source]

# File tk/lib/tkextlib/tcllib/tooltip.rb, line 40
  def self.database_class
    WidgetClassNames[self::WidgetClassName]
  end
database_classname()

[Source]

# File tk/lib/tkextlib/tcllib/tooltip.rb, line 37
  def self.database_classname
    self::WidgetClassName
  end
delay(millisecs=None)

[Source]

# File tk/lib/tkextlib/tcllib/tooltip.rb, line 60
  def self.delay(millisecs=None)
    number(tk_call_without_enc('::tooltip::tooltip', 'delay', millisecs))
  end
delay=(millisecs)

[Source]

# File tk/lib/tkextlib/tcllib/tooltip.rb, line 63
  def self.delay=(millisecs)
    self.delay(millisecs)
  end
disable()

[Source]

# File tk/lib/tkextlib/tcllib/tooltip.rb, line 67
  def self.disable
    tk_call_without_enc('::tooltip::tooltip', 'disable')
    false
  end
enable()

[Source]

# File tk/lib/tkextlib/tcllib/tooltip.rb, line 75
  def self.enable
    tk_call_without_enc('::tooltip::tooltip', 'enable')
    true
  end
erase(widget)

[Source]

# File tk/lib/tkextlib/tcllib/tooltip.rb, line 92
  def self.erase(widget)
    tk_call_without_enc('::tooltip::tooltip', widget.path, '')
  end
off()

[Source]

# File tk/lib/tkextlib/tcllib/tooltip.rb, line 71
  def self.off
    self.disable
  end
on()

[Source]

# File tk/lib/tkextlib/tcllib/tooltip.rb, line 79
  def self.on
    self.enable
  end
package_name()

[Source]

# File tk/lib/tkextlib/tcllib/tooltip.rb, line 19
    def self.package_name
      PACKAGE_NAME
    end
package_version()

[Source]

# File tk/lib/tkextlib/tcllib/tooltip.rb, line 23
    def self.package_version
      begin
        TkPackage.require('tooltip')
      rescue
        ''
      end
    end
register(widget, msg, keys=nil)

[Source]

# File tk/lib/tkextlib/tcllib/tooltip.rb, line 83
  def self.register(widget, msg, keys=nil)
    if keys.kind_of?(Hash)
      args = hash_kv(keys) << msg
    else
      args = msg
    end
    tk_call_without_enc('::tooltip::tooltip', widget.path, *args)
  end


Module: Tk::Tcllib::Widget

Module | Tk::Tcllib::Widget
In: | tk/lib/tkextlib/tcllib/widget.rb tk/lib/tkextlib/tcllib/superframe.rb tk/lib/tkextlib/tcllib/scrollwin.rb tk/lib/tkextlib/tcllib/screenruler.rb tk/lib/tkextlib/tcllib/ruler.rb tk/lib/tkextlib/tcllib/panelframe.rb tk/lib/tkextlib/tcllib/dialog.rb

Methods

package_name package_version

Classes and Modules

Class Tk::Tcllib::Widget::Dialog
Class Tk::Tcllib::Widget::PanelFrame
Class Tk::Tcllib::Widget::Ruler
Class Tk::Tcllib::Widget::ScreenRuler
Class Tk::Tcllib::Widget::ScrolledWindow
Class Tk::Tcllib::Widget::SuperFrame

Constants

PACKAGE_NAME | = | 'widget'.freeze
Superframe | = | SuperlFrame
Scrolledwindow | = | ScrolledWindow
Screenruler | = | ScreenRuler
Panelframe | = | PanelFrame

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/tcllib/widget.rb, line 18
    def self.package_name
      PACKAGE_NAME
    end
package_version()

[Source]

# File tk/lib/tkextlib/tcllib/widget.rb, line 22
    def self.package_version
      begin
        TkPackage.require('widget')
      rescue
        ''
      end
    end


Class: Tk::Tcllib::Widget::Dialog

Class | Tk::Tcllib::Widget::Dialog
In: | tk/lib/tkextlib/tcllib/dialog.rb
Parent: | TkWindow

Methods

add cancel close display get_frame package_name package_version set_widget show withdraw

Constants

PACKAGE_NAME | = | 'widget::dialog'.freeze
TkCommandNames | = | ['::widget::dialog'.freeze].freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/tcllib/dialog.rb, line 19
      def self.package_name
        PACKAGE_NAME
      end
package_version()

[Source]

# File tk/lib/tkextlib/tcllib/dialog.rb, line 23
      def self.package_version
        begin
          TkPackage.require('widget::dialog')
        rescue
          ''
        end
      end

Public Instance methods

add(what, *args)

[Source]

# File tk/lib/tkextlib/tcllib/dialog.rb, line 52
  def add(what, *args)
    window(tk_send('add', *args))
  end
cancel()

[Source]

# File tk/lib/tkextlib/tcllib/dialog.rb, line 71
  def cancel
    tk_send('cancel')
    self
  end
close(reason = None)

[Source]

# File tk/lib/tkextlib/tcllib/dialog.rb, line 76
  def close(reason = None)
    tk_send('close', reason)
  end
display()

[Source]

# File tk/lib/tkextlib/tcllib/dialog.rb, line 65
  def display
    tk_send('display')
    self
  end
get_frame()

[Source]

# File tk/lib/tkextlib/tcllib/dialog.rb, line 56
  def get_frame
    window(tk_send('getframe'))
  end
set_widget(widget)

[Source]

# File tk/lib/tkextlib/tcllib/dialog.rb, line 60
  def set_widget(widget)
    tk_send('setwidget', widget)
    self
  end
show()

Alias for display

withdraw()

[Source]

# File tk/lib/tkextlib/tcllib/dialog.rb, line 80
  def withdraw
    tk_send('withdraw')
    self
  end


Class: Tk::Tcllib::Widget::PanelFrame

Class | Tk::Tcllib::Widget::PanelFrame
In: | tk/lib/tkextlib/tcllib/panelframe.rb
Parent: | TkWindow

Methods

add delete items package_name package_version remove remove_destroy set_widget

Constants

PACKAGE_NAME | = | 'widget::panelframe'.freeze
TkCommandNames | = | ['::widget::panelframe'.freeze].freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/tcllib/panelframe.rb, line 19
      def self.package_name
        PACKAGE_NAME
      end
package_version()

[Source]

# File tk/lib/tkextlib/tcllib/panelframe.rb, line 23
      def self.package_version
        begin
          TkPackage.require('widget::panelframe')
        rescue
          ''
        end
      end

Public Instance methods

add(what, *args)

[Source]

# File tk/lib/tkextlib/tcllib/panelframe.rb, line 48
  def add(what, *args)
    window(tk_send('add', *args))
  end
delete(*wins)

Alias for remove_destroy

items()

[Source]

# File tk/lib/tkextlib/tcllib/panelframe.rb, line 69
  def items
    simplelist(tk_send('items')).collect!{|w| window(w)}
  end
remove(*wins)

[Source]

# File tk/lib/tkextlib/tcllib/panelframe.rb, line 61
  def remove(*wins)
    tk_send('remove', *wins)
  end
remove_destroy(*wins)

[Source]

# File tk/lib/tkextlib/tcllib/panelframe.rb, line 64
  def remove_destroy(*wins)
    tk_send('remove', '-destroy', *wins)
  end
set_widget(widget)

def get_frame

  window(tk_send('getframe'))

end

[Source]

# File tk/lib/tkextlib/tcllib/panelframe.rb, line 56
  def set_widget(widget)
    tk_send('setwidget', widget)
    self
  end


Class: Tk::Tcllib::Widget::Ruler

Class | Tk::Tcllib::Widget::Ruler
In: | tk/lib/tkextlib/tcllib/ruler.rb
Parent: | TkWindow

Methods

package_name package_version redraw shade

Constants

PACKAGE_NAME | = | 'widget::ruler'.freeze
TkCommandNames | = | ['::widget::ruler'.freeze].freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/tcllib/ruler.rb, line 19
      def self.package_name
        PACKAGE_NAME
      end
package_version()

[Source]

# File tk/lib/tkextlib/tcllib/ruler.rb, line 23
      def self.package_version
        begin
          TkPackage.require('widget::ruler')
        rescue
          ''
        end
      end

Public Instance methods

redraw()

[Source]

# File tk/lib/tkextlib/tcllib/ruler.rb, line 57
  def redraw
    tk_send('redraw')
    self
  end
shade(org, dest, frac)

[Source]

# File tk/lib/tkextlib/tcllib/ruler.rb, line 62
  def shade(org, dest, frac)
    tk_send('shade', org, dest, frac)
  end


Class: Tk::Tcllib::Widget::ScreenRuler

Class | Tk::Tcllib::Widget::ScreenRuler
In: | tk/lib/tkextlib/tcllib/screenruler.rb
Parent: | TkWindow

Methods

display hide package_name package_version show

Constants

PACKAGE_NAME | = | 'widget::ruler'.freeze
TkCommandNames | = | ['::widget::screenruler'.freeze].freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/tcllib/screenruler.rb, line 19
      def self.package_name
        PACKAGE_NAME
      end
package_version()

[Source]

# File tk/lib/tkextlib/tcllib/screenruler.rb, line 23
      def self.package_version
        begin
          TkPackage.require('widget::screenruler')
        rescue
          ''
        end
      end

Public Instance methods

display()

[Source]

# File tk/lib/tkextlib/tcllib/screenruler.rb, line 58
  def display
    tk_send('display')
    self
  end
hide()

[Source]

# File tk/lib/tkextlib/tcllib/screenruler.rb, line 64
  def hide
    tk_send('hide')
    self
  end
show()

Alias for display


Class: Tk::Tcllib::Widget::ScrolledWindow

Class | Tk::Tcllib::Widget::ScrolledWindow
In: | tk/lib/tkextlib/tcllib/scrollwin.rb
Parent: | TkWindow

Methods

get_frame package_name package_version set_widget

Constants

PACKAGE_NAME | = | 'widget::scrolledwindow'.freeze
TkCommandNames | = | ['::widget::scrolledwindow'.freeze].freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/tcllib/scrollwin.rb, line 19
      def self.package_name
        PACKAGE_NAME
      end
package_version()

[Source]

# File tk/lib/tkextlib/tcllib/scrollwin.rb, line 23
      def self.package_version
        begin
          TkPackage.require('widget::scrolledwindow')
        rescue
          ''
        end
      end

Public Instance methods

get_frame()

[Source]

# File tk/lib/tkextlib/tcllib/scrollwin.rb, line 53
  def get_frame
    window(tk_send('getframe'))
  end
set_widget(widget)

[Source]

# File tk/lib/tkextlib/tcllib/scrollwin.rb, line 57
  def set_widget(widget)
    tk_send('setwidget', widget)
    self
  end


Class: Tk::Tcllib::Widget::SuperFrame

Class | Tk::Tcllib::Widget::SuperFrame
In: | tk/lib/tkextlib/tcllib/superframe.rb
Parent: | TkWindow

Methods

labelwidget package_name package_version

Constants

PACKAGE_NAME | = | 'widget::superframe'.freeze
TkCommandNames | = | ['::widget::superframe'.freeze].freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/tcllib/superframe.rb, line 19
      def self.package_name
        PACKAGE_NAME
      end
package_version()

[Source]

# File tk/lib/tkextlib/tcllib/superframe.rb, line 23
      def self.package_version
        begin
          TkPackage.require('widget::superframe')
        rescue
          ''
        end
      end

Public Instance methods

labelwidget()

[Source]

# File tk/lib/tkextlib/tcllib/superframe.rb, line 48
  def labelwidget
    window(tk_send('labelwidget'))
  end


Module: Tk::Tile

Module | Tk::Tile
In: | tk/lib/tkextlib/tile.rb tk/lib/tkextlib/tile/tsquare.rb tk/lib/tkextlib/tile/tseparator.rb tk/lib/tkextlib/tile/tscrollbar.rb tk/lib/tkextlib/tile/tscale.rb tk/lib/tkextlib/tile/treeview.rb tk/lib/tkextlib/tile/tradiobutton.rb tk/lib/tkextlib/tile/tprogressbar.rb tk/lib/tkextlib/tile/tpaned.rb tk/lib/tkextlib/tile/tnotebook.rb tk/lib/tkextlib/tile/tmenubutton.rb tk/lib/tkextlib/tile/tlabelframe.rb tk/lib/tkextlib/tile/tlabel.rb tk/lib/tkextlib/tile/tframe.rb tk/lib/tkextlib/tile/tentry.rb tk/lib/tkextlib/tile/tcombobox.rb tk/lib/tkextlib/tile/tcheckbutton.rb tk/lib/tkextlib/tile/tbutton.rb tk/lib/tkextlib/tile/style.rb tk/lib/tkextlib/tile/dialog.rb

Methods

__Import_Tile_Widgets__! load_images package_name package_version style

Classes and Modules

Module Tk::Tile::Font
Module Tk::Tile::KeyNav
Module Tk::Tile::ParseStyleLayout
Module Tk::Tile::Style
Module Tk::Tile::TileWidget
Module Tk::Tile::TreeviewConfig
Class Tk::Tile::Dialog
Class Tk::Tile::TButton
Class Tk::Tile::TCheckButton
Class Tk::Tile::TCombobox
Class Tk::Tile::TEntry
Class Tk::Tile::TFrame
Class Tk::Tile::TLabel
Class Tk::Tile::TLabelframe
Class Tk::Tile::TMenubutton
Class Tk::Tile::TNotebook
Class Tk::Tile::TPaned
Class Tk::Tile::TProgress
Class Tk::Tile::TProgressbar
Class Tk::Tile::TRadioButton
Class Tk::Tile::TScale
Class Tk::Tile::TScrollbar
Class Tk::Tile::TSeparator
Class Tk::Tile::TSquare
Class Tk::Tile::Treeview

Constants

USE_TILE_NAMESPACE | = | true
TILE_SPEC_VERSION_ID | = | 0
USE_TILE_NAMESPACE | = | true
TILE_SPEC_VERSION_ID | = | 5
USE_TILE_NAMESPACE | = | false
TILE_SPEC_VERSION_ID | = | 7
PACKAGE_NAME | = | 'tile'.freeze
Square | = | TSquare
Separator | = | TSeparator
Scrollbar | = | TScrollbar
Scale | = | TScale
Progress | = | TProgress
TRadiobutton | = | TRadioButton
RadioButton | = | TRadioButton
Radiobutton | = | TRadioButton
Progressbar | = | TProgressbar
Paned | = | TPaned
Notebook | = | TNotebook
Menubutton | = | TMenubutton
Labelframe | = | TLabelframe
Label | = | TLabel
Frame | = | TFrame
Entry | = | TEntry
Combobox | = | TCombobox
TCheckbutton | = | TCheckButton
CheckButton | = | TCheckButton
Checkbutton | = | TCheckButton
Button | = | TButton

Public Class methods

__Import_Tile_Widgets__!()

[Source]

# File tk/lib/tkextlib/tile.rb, line 63
    def self.__Import_Tile_Widgets__!
      Tk.tk_call('namespace', 'import', 'ttk::*')
    end
load_images(imgdir, pat=TkComm::None)

[Source]

# File tk/lib/tkextlib/tile.rb, line 67
    def self.load_images(imgdir, pat=TkComm::None)
      images = Hash[*TkComm.simplelist(Tk.tk_call('::tile::LoadImages',
                                                  imgdir, pat))]
      images.keys.each{|k|
        images[k] = TkPhotoImage.new(:imagename=>images[k],
                                     :without_creating=>true)
      }

      images
    end
package_name()

[Source]

# File tk/lib/tkextlib/tile.rb, line 51
    def self.package_name
      PACKAGE_NAME
    end
package_version()

[Source]

# File tk/lib/tkextlib/tile.rb, line 55
    def self.package_version
      begin
        TkPackage.require('tile')
      rescue
        ''
      end
    end
style(*args)

[Source]

# File tk/lib/tkextlib/tile.rb, line 78
    def self.style(*args)
      args.map!{|arg| TkComm._get_eval_string(arg)}.join('.')
    end


Class: Tk::Tile::Dialog

Class | Tk::Tile::Dialog
In: | tk/lib/tkextlib/tile/dialog.rb
Parent: | TkWindow

Methods

cget client_frame configinfo configure define_dialog_type display display new show show style

Constants

TkCommandNames = ['::ttk::dialog'.freeze].freeze

Public Class methods

define_dialog_type(name, keys)

[Source]

# File tk/lib/tkextlib/tile/dialog.rb, line 27
  def self.define_dialog_type(name, keys)
    Tk.tk_call('::ttk::dialog::define', name, keys)
    name
  end
display(*args)

[Source]

# File tk/lib/tkextlib/tile/dialog.rb, line 23
  def self.display(*args)
    self.show(*args)
  end
new(keys={})

[Source]

# File tk/lib/tkextlib/tile/dialog.rb, line 38
  def initialize(keys={})
    @keys = _symbolkey2str(keys)
    super(*args)
  end
show(*args)

[Source]

# File tk/lib/tkextlib/tile/dialog.rb, line 18
  def self.show(*args)
    dialog = self.new(*args)
    dialog.show
    [dialog.status, dialog.value]
  end
style(*args)

[Source]

# File tk/lib/tkextlib/tile/dialog.rb, line 32
  def self.style(*args)
    ['Dialog', *(args.map!{|a| _get_eval_string(a)})].join('.')
  end

Public Instance methods

cget(slot)

[Source]

# File tk/lib/tkextlib/tile/dialog.rb, line 57
  def cget(slot)
    @keys[slot]
  end
client_frame()

[Source]

# File tk/lib/tkextlib/tile/dialog.rb, line 53
  def client_frame
    window(tk_call_without_enc('::ttk::dialog::clientframe'))
  end
configinfo(slot = nil)

[Source]

# File tk/lib/tkextlib/tile/dialog.rb, line 76
  def configinfo(slot = nil)
    if slot
      slot = slot.to_s
      [ slot, nil, nil, nil, @keys[slot] ]
    else
      @keys.collect{|k, v| [ k, nil, nil, nil, v ] }
    end
  end
configure(slot, value=None)

[Source]

# File tk/lib/tkextlib/tile/dialog.rb, line 61
  def configure(slot, value=None)
    if slot.kind_of?(Hash)
      slot.each{|k, v| configure(k, v)}
    else
      slot = slot.to_s
      value = _symbolkey2str(value) if value.kind_of?(Hash)
      if value && value != None
        @keys[slot] = value
      else
        @keys.delete(slot)
      end
    end
    self
  end
display()

Alias for show

show()

[Source]

# File tk/lib/tkextlib/tile/dialog.rb, line 48
  def show
    tk_call(self.class::TkCommandNames[0], @path, *hash_kv(@keys))
  end


Module: Tk::Tile::Font

Module | Tk::Tile::Font
In: | tk/lib/tkextlib/tile.rb

Constants

Default | = | 'TkDefaultFont'
Text | = | 'TkTextFont'
Heading | = | 'TkHeadingFont'
Caption | = | 'TkCaptionFont'
Tooltip | = | 'TkTooltipFont'
Fixed | = | 'TkFixedFont'
Menu | = | 'TkMenuFont'
SmallCaption | = | 'TkSmallCaptionFont'
Icon | = | 'TkIconFont'


Module: Tk::Tile::KeyNav

Module | Tk::Tile::KeyNav
In: | tk/lib/tkextlib/tile.rb

Methods

defaultButton enableMnemonics

Public Class methods

defaultButton(w)

[Source]

# File tk/lib/tkextlib/tile.rb, line 86
      def self.defaultButton(w)
        Tk.tk_call('::keynav::defaultButton', w)
      end
enableMnemonics(w)

[Source]

# File tk/lib/tkextlib/tile.rb, line 83
      def self.enableMnemonics(w)
        Tk.tk_call('::keynav::enableMnemonics', w)
      end


Module: Tk::Tile::ParseStyleLayout

Module | Tk::Tile::ParseStyleLayout
In: | tk/lib/tkextlib/tile.rb


Module: Tk::Tile::Style

Module | Tk::Tile::Style
In: | tk/lib/tkextlib/tile/style.rb


Class: Tk::Tile::TButton

Class | Tk::Tile::TButton
In: | tk/lib/tkextlib/tile/tbutton.rb
Parent: | TkButton

Methods

style

Included Modules

Tk::Tile::TileWidget

Constants

TkCommandNames | = | ['::ttk::button'.freeze].freeze
TkCommandNames | = | ['::tbutton'.freeze].freeze
WidgetClassName | = | 'TButton'.freeze

Public Class methods

style(*args)

[Source]

# File tk/lib/tkextlib/tile/tbutton.rb, line 27
  def self.style(*args)
    [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
  end


Class: Tk::Tile::TCheckButton

Class | Tk::Tile::TCheckButton
In: | tk/lib/tkextlib/tile/tcheckbutton.rb
Parent: | TkCheckButton

Methods

style

Included Modules

Tk::Tile::TileWidget

Constants

TkCommandNames | = | ['::ttk::checkbutton'.freeze].freeze
TkCommandNames | = | ['::tcheckbutton'.freeze].freeze
WidgetClassName | = | 'TCheckbutton'.freeze

Public Class methods

style(*args)

[Source]

# File tk/lib/tkextlib/tile/tcheckbutton.rb, line 29
  def self.style(*args)
    [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
  end


Class: Tk::Tile::TCombobox

Class | Tk::Tile::TCombobox
In: | tk/lib/tkextlib/tile/tcombobox.rb
Parent: | Tk::Tile::TEntry

Methods

current current= identify set style

Included Modules

Tk::Tile::TileWidget

Constants

TkCommandNames | = | ['::ttk::combobox'.freeze].freeze
TkCommandNames | = | ['::tcombobox'.freeze].freeze
WidgetClassName | = | 'TCombobox'.freeze

Public Class methods

style(*args)

[Source]

# File tk/lib/tkextlib/tile/tcombobox.rb, line 37
  def self.style(*args)
    [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
  end

Public Instance methods

current()

[Source]

# File tk/lib/tkextlib/tile/tcombobox.rb, line 41
  def current
    number(tk_send_without_enc('current', idx))
  end
current=(idx)

[Source]

# File tk/lib/tkextlib/tile/tcombobox.rb, line 44
  def current=(idx)
    tk_send_without_enc('current', idx)
  end
identify(x, y)

[Source]

# File tk/lib/tkextlib/tile/tcombobox.rb, line 48
  def identify(x, y)
    tk_send_without_enc('identify', x, y)
  end
set(val)

[Source]

# File tk/lib/tkextlib/tile/tcombobox.rb, line 52
  def set(val)
    tk_send('set', val)
  end


Class: Tk::Tile::TEntry

Class | Tk::Tile::TEntry
In: | tk/lib/tkextlib/tile/tentry.rb
Parent: | TkEntry

Methods

style

Included Modules

Tk::Tile::TileWidget

Constants

TkCommandNames | = | ['::ttk::entry'.freeze].freeze
TkCommandNames | = | ['::tentry'.freeze].freeze
WidgetClassName | = | 'TEntry'.freeze

Public Class methods

style(*args)

[Source]

# File tk/lib/tkextlib/tile/tentry.rb, line 37
  def self.style(*args)
    [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
  end


Class: Tk::Tile::TFrame

Class | Tk::Tile::TFrame
In: | tk/lib/tkextlib/tile/tframe.rb
Parent: | TkFrame

Methods

style

Included Modules

Tk::Tile::TileWidget

Constants

TkCommandNames | = | ['::ttk::frame'.freeze].freeze
TkCommandNames | = | ['::tframe'.freeze].freeze
WidgetClassName | = | 'TFrame'.freeze

Public Class methods

style(*args)

[Source]

# File tk/lib/tkextlib/tile/tframe.rb, line 27
  def self.style(*args)
    [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
  end


Class: Tk::Tile::TLabel

Class | Tk::Tile::TLabel
In: | tk/lib/tkextlib/tile/tlabel.rb
Parent: | TkLabel

Methods

style

Included Modules

Tk::Tile::TileWidget

Constants

TkCommandNames | = | ['::ttk::label'.freeze].freeze
TkCommandNames | = | ['::tlabel'.freeze].freeze
WidgetClassName | = | 'TLabel'.freeze

Public Class methods

style(*args)

[Source]

# File tk/lib/tkextlib/tile/tlabel.rb, line 27
  def self.style(*args)
    [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
  end


Class: Tk::Tile::TLabelframe

Class | Tk::Tile::TLabelframe
In: | tk/lib/tkextlib/tile/tlabelframe.rb
Parent: | Tk::Tile::TFrame

Methods

style

Included Modules

Tk::Tile::TileWidget

Constants

TkCommandNames | = | ['::ttk::labelframe'.freeze].freeze
TkCommandNames | = | ['::tlabelframe'.freeze].freeze
WidgetClassName | = | 'TLabelframe'.freeze

Public Class methods

style(*args)

[Source]

# File tk/lib/tkextlib/tile/tlabelframe.rb, line 27
  def self.style(*args)
    [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
  end


Class: Tk::Tile::TMenubutton

Class | Tk::Tile::TMenubutton
In: | tk/lib/tkextlib/tile/tmenubutton.rb
Parent: | TkMenubutton

Methods

style

Included Modules

Tk::Tile::TileWidget

Constants

TkCommandNames | = | ['::ttk::menubutton'.freeze].freeze
TkCommandNames | = | ['::tmenubutton'.freeze].freeze
WidgetClassName | = | 'TMenubutton'.freeze

Public Class methods

style(*args)

[Source]

# File tk/lib/tkextlib/tile/tmenubutton.rb, line 27
  def self.style(*args)
    [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
  end


Class: Tk::Tile::TNotebook

Class | Tk::Tile::TNotebook
In: | tk/lib/tkextlib/tile/tnotebook.rb
Parent: | TkWindow

Methods

__item_methodcall_optkeys add enable_traversal forget index select style tabcget tabs

Included Modules

TkItemConfigMethod Tk::Tile::TileWidget

Constants

TkCommandNames | = | ['::ttk::notebook'.freeze].freeze
TkCommandNames | = | ['::tnotebook'.freeze].freeze
WidgetClassName | = | 'TNotebook'.freeze

External Aliases

itemconfigure | -> | tabconfigure
 | alias tabcget itemcget
itemconfiginfo | -> | tabconfiginfo
current_itemconfiginfo | -> | current_tabconfiginfo

Public Class methods

style(*args)

[Source]

# File tk/lib/tkextlib/tile/tnotebook.rb, line 60
  def self.style(*args)
    [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
  end

Public Instance methods

__item_methodcall_optkeys(

[Source]

# File tk/lib/tkextlib/tile/tnotebook.rb, line 35
  def __item_methodcall_optkeys  # { key=>method, ... }
    {}
  end
add(child, keys=nil)

[Source]

# File tk/lib/tkextlib/tile/tnotebook.rb, line 75
  def add(child, keys=nil)
    if keys && keys != None
      tk_send_without_enc('add', _epath(child), *hash_kv(keys))
    else
      tk_send_without_enc('add', _epath(child))
    end
    self
  end
enable_traversal()

[Source]

# File tk/lib/tkextlib/tile/tnotebook.rb, line 64
  def enable_traversal()
    if Tk::Tile::TILE_SPEC_VERSION_ID < 5
      tk_call_without_enc('::tile::enableNotebookTraversal', @path)
    elsif Tk::Tile::TILE_SPEC_VERSION_ID < 7
      tk_call_without_enc('::tile::notebook::enableTraversal', @path)
    else
      tk_call_without_enc('::ttk::notebook::enableTraversal', @path)
    end
    self
  end
forget(idx)

[Source]

# File tk/lib/tkextlib/tile/tnotebook.rb, line 84
  def forget(idx)
    tk_send('forget', idx)
    self
  end
index(idx)

[Source]

# File tk/lib/tkextlib/tile/tnotebook.rb, line 89
  def index(idx)
    number(tk_send('index', idx))
  end
select(idx)

[Source]

# File tk/lib/tkextlib/tile/tnotebook.rb, line 93
  def select(idx)
    tk_send('select', idx)
    self
  end
tabcget(tagOrId, option)

[Source]

# File tk/lib/tkextlib/tile/tnotebook.rb, line 45
  def tabcget(tagOrId, option)
    tabconfigure(tagOrId, option)[-1]
  end
tabs()

[Source]

# File tk/lib/tkextlib/tile/tnotebook.rb, line 98
  def tabs
    list(tk_send('tabs'))
  end


Class: Tk::Tile::TPaned

Class | Tk::Tile::TPaned
In: | tk/lib/tkextlib/tile/tpaned.rb
Parent: | TkWindow

Methods

add current_pane_configinfo current_paneconfiginfo forget identify insert pane_cget pane_config pane_configinfo pane_configure panecget paneconfiginfo paneconfigure sashpos style

Included Modules

Tk::Tile::TileWidget

Constants

TkCommandNames | = | ['::ttk::paned'.freeze].freeze
TkCommandNames | = | ['::tpaned'.freeze].freeze
WidgetClassName | = | 'TPaned'.freeze

Public Class methods

style(*args)

[Source]

# File tk/lib/tkextlib/tile/tpaned.rb, line 27
  def self.style(*args)
    [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
  end

Public Instance methods

add(win, keys)

[Source]

# File tk/lib/tkextlib/tile/tpaned.rb, line 31
  def add(win, keys)
    win = _epath(win)
    tk_send_without_enc('add', win, *hash_kv(keys))
    self
  end
current_pane_configinfo(win, key=nil)

Alias for current_paneconfiginfo

current_paneconfiginfo(win, key=nil)

[Source]

# File tk/lib/tkextlib/tile/tpaned.rb, line 159
  def current_paneconfiginfo(win, key=nil)
    if TkComm::GET_CONFIGINFO_AS_ARRAY
      if key
        conf = paneconfiginfo(win, key)
        {conf[0] => conf[4]}
      else
        ret = {}
        paneconfiginfo(win).each{|conf|
          ret[conf[0]] = conf[4] if conf.size > 2
        }
        ret
      end
    else # ! TkComm::GET_CONFIGINFO_AS_ARRAY
      ret = {}
      paneconfiginfo(win, key).each{|k, conf|
        ret[k] = conf[-1] if conf.kind_of?(Array)
      }
      ret
    end
  end
forget(pane)

[Source]

# File tk/lib/tkextlib/tile/tpaned.rb, line 37
  def forget(pane)
    pane = _epath(pane)
    tk_send_without_enc('forget', pane)
    self
  end
identify(x, y)

[Source]

# File tk/lib/tkextlib/tile/tpaned.rb, line 181
  def identify(x, y)
    list(tk_send_without_enc('identify', x, y))
  end
insert(pos, win, keys)

[Source]

# File tk/lib/tkextlib/tile/tpaned.rb, line 43
  def insert(pos, win, keys)
    win = _epath(win)
    tk_send_without_enc('insert', pos, win, *hash_kv(keys))
    self
  end
pane_cget(pane, slot)

Alias for panecget

pane_config(pane, key, value=nil)

Alias for paneconfigure

pane_configinfo(win)

Alias for paneconfiginfo

pane_configure(pane, key, value=nil)

Alias for paneconfigure

panecget(pane, slot)

[Source]

# File tk/lib/tkextlib/tile/tpaned.rb, line 49
  def panecget(pane, slot)
    pane = _epath(pane)
    tk_tcl2ruby(tk_send_without_enc('pane', pane, "-#{slot}"))
  end
paneconfiginfo(win)

[Source]

# File tk/lib/tkextlib/tile/tpaned.rb, line 75
  def paneconfiginfo(win)
    if TkComm::GET_CONFIGINFO_AS_ARRAY
      win = _epath(win)
      if key
        conf = tk_split_list(tk_send_without_enc('pane', win, "-#{key}"))
        conf[0] = conf[0][1..-1]
        if conf[0] == 'hide'
          conf[3] = bool(conf[3]) unless conf[3].empty?
          conf[4] = bool(conf[4]) unless conf[4].empty?
        end
        conf
      else
        tk_split_simplelist(tk_send_without_enc('pane',
                                                win)).collect{|conflist|
          conf = tk_split_simplelist(conflist)
          conf[0] = conf[0][1..-1]
          if conf[3]
            if conf[0] == 'hide'
              conf[3] = bool(conf[3]) unless conf[3].empty?
            elsif conf[3].index('{')
              conf[3] = tk_split_list(conf[3])
            else
              conf[3] = tk_tcl2ruby(conf[3])
            end
          end
          if conf[4]
            if conf[0] == 'hide'
              conf[4] = bool(conf[4]) unless conf[4].empty?
            elsif conf[4].index('{')
              conf[4] = tk_split_list(conf[4])
            else
              conf[4] = tk_tcl2ruby(conf[4])
            end
          end
          conf[1] = conf[1][1..-1] if conf.size == 2 # alias info
          conf
        }
      end
    else # ! TkComm::GET_CONFIGINFO_AS_ARRAY
      win = _epath(win)
      if key
        conf = tk_split_list(tk_send_without_enc('pane', win, "-#{key}"))
        key = conf.shift[1..-1]
        if key == 'hide'
          conf[2] = bool(conf[2]) unless conf[2].empty?
          conf[3] = bool(conf[3]) unless conf[3].empty?
        end
        { key => conf }
      else
        ret = {}
        tk_split_simplelist(tk_send_without_enc('pane',
                                                win)).each{|conflist|
          conf = tk_split_simplelist(conflist)
          key = conf.shift[1..-1]
          if key
            if key == 'hide'
              conf[2] = bool(conf[2]) unless conf[2].empty?
            elsif conf[2].index('{')
              conf[2] = tk_split_list(conf[2])
            else
              conf[2] = tk_tcl2ruby(conf[2])
            end
          end
          if conf[3]
            if key == 'hide'
              conf[3] = bool(conf[3]) unless conf[3].empty?
            elsif conf[3].index('{')
              conf[3] = tk_split_list(conf[3])
            else
              conf[3] = tk_tcl2ruby(conf[3])
            end
          end
          if conf.size == 1
            ret[key] = conf[0][1..-1]  # alias info
          else
            ret[key] = conf
          end
        }
        ret
      end
    end
  end
paneconfigure(pane, key, value=nil)

[Source]

# File tk/lib/tkextlib/tile/tpaned.rb, line 55
  def paneconfigure(pane, key, value=nil)
    pane = _epath(pane)
    if key.kind_of? Hash
      params = []
      key.each{|k, v|
        params.push("-#{k}")
        # params.push((v.kind_of?(TkObject))? v.epath: v)
        params.push(_epath(v))
      }
      tk_send_without_enc('pane', pane, *params)
    else
      # value = value.epath if value.kind_of?(TkObject)
      value = _epath(value)
      tk_send_without_enc('pane', pane, "-#{key}", value)
    end
    self
  end
sashpos(idx, newpos=None)

[Source]

# File tk/lib/tkextlib/tile/tpaned.rb, line 185
  def sashpos(idx, newpos=None)
    num_or_str(tk_send_without_enc('sashpos', idx, newpos))
  end


Class: Tk::Tile::TProgress

Class | Tk::Tile::TProgress
In: | tk/lib/tkextlib/tile/tscale.rb
Parent: | TScale

Methods

style

Included Modules

Tk::Tile::TileWidget

Constants

TkCommandNames | = | ['::ttk::progress'.freeze].freeze
TkCommandNames | = | ['::tprogress'.freeze].freeze
WidgetClassName | = | 'TProgress'.freeze

Public Class methods

style(*args)

[Source]

# File tk/lib/tkextlib/tile/tscale.rb, line 47
  def self.style(*args)
    [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
  end


Class: Tk::Tile::TProgressbar

Class | Tk::Tile::TProgressbar
In: | tk/lib/tkextlib/tile/tprogressbar.rb
Parent: | TkWindow

Methods

start step stop style

Included Modules

Tk::Tile::TileWidget

Constants

TkCommandNames | = | ['::ttk::progressbar'.freeze].freeze
TkCommandNames | = | ['::tprogressbar'.freeze].freeze
WidgetClassName | = | 'TProgressbar'.freeze

Public Class methods

style(*args)

[Source]

# File tk/lib/tkextlib/tile/tprogressbar.rb, line 27
  def self.style(*args)
    [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
  end

Public Instance methods

start(interval=None)

def step=(amount)

  tk_send_without_enc('step', amount)

end

[Source]

# File tk/lib/tkextlib/tile/tprogressbar.rb, line 38
  def start(interval=None)
    if Tk::Tile::TILE_SPEC_VERSION_ID < 5
      tk_call_without_enc('::tile::progressbar::start', @path, interval)
    else
      tk_send_without_enc('start', interval)
    end
  end
step(amount=None)

[Source]

# File tk/lib/tkextlib/tile/tprogressbar.rb, line 31
  def step(amount=None)
    tk_send_without_enc('step', amount).to_f
  end
stop(amount=None)

[Source]

# File tk/lib/tkextlib/tile/tprogressbar.rb, line 46
  def stop(amount=None)
    if Tk::Tile::TILE_SPEC_VERSION_ID < 5
      tk_call_without_enc('::tile::progressbar::stop', @path)
    else
      tk_send_without_enc('stop', amount)
    end
  end


Class: Tk::Tile::TRadioButton

Class | Tk::Tile::TRadioButton
In: | tk/lib/tkextlib/tile/tradiobutton.rb
Parent: | TkRadioButton

Methods

style

Included Modules

Tk::Tile::TileWidget

Constants

TkCommandNames | = | ['::ttk::radiobutton'.freeze].freeze
TkCommandNames | = | ['::tradiobutton'.freeze].freeze
WidgetClassName | = | 'TRadiobutton'.freeze

Public Class methods

style(*args)

[Source]

# File tk/lib/tkextlib/tile/tradiobutton.rb, line 29
  def self.style(*args)
    [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
  end


Class: Tk::Tile::TScale

Class | Tk::Tile::TScale
In: | tk/lib/tkextlib/tile/tscale.rb
Parent: | TkScale

Methods

style

Included Modules

Tk::Tile::TileWidget

Constants

TkCommandNames | = | ['::ttk::scale'.freeze].freeze
TkCommandNames | = | ['::tscale'.freeze].freeze
WidgetClassName | = | 'TScale'.freeze

Public Class methods

style(*args)

[Source]

# File tk/lib/tkextlib/tile/tscale.rb, line 31
  def self.style(*args)
    [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
  end


Class: Tk::Tile::TScrollbar

Class | Tk::Tile::TScrollbar
In: | tk/lib/tkextlib/tile/tscrollbar.rb
Parent: | TkScrollbar

Methods

style

Included Modules

Tk::Tile::TileWidget

Constants

TkCommandNames | = | ['::ttk::scrollbar'.freeze].freeze
TkCommandNames | = | ['::tscrollbar'.freeze].freeze
WidgetClassName | = | 'TScrollbar'.freeze

Public Class methods

style(*args)

[Source]

# File tk/lib/tkextlib/tile/tscrollbar.rb, line 27
  def self.style(*args)
    [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
  end


Class: Tk::Tile::TSeparator

Class | Tk::Tile::TSeparator
In: | tk/lib/tkextlib/tile/tseparator.rb
Parent: | TkWindow

Methods

style

Included Modules

Tk::Tile::TileWidget

Constants

TkCommandNames | = | ['::ttk::separator'.freeze].freeze
TkCommandNames | = | ['::tseparator'.freeze].freeze
WidgetClassName | = | 'TSeparator'.freeze

Public Class methods

style(*args)

[Source]

# File tk/lib/tkextlib/tile/tseparator.rb, line 27
  def self.style(*args)
    [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
  end


Class: Tk::Tile::TSquare

Class | Tk::Tile::TSquare
In: | tk/lib/tkextlib/tile/tsquare.rb
Parent: | TkWindow

Methods

style

Included Modules

Tk::Tile::TileWidget

Constants

TkCommandNames | = | ['::ttk::square'.freeze].freeze
TkCommandNames | = | ['::tsquare'.freeze].freeze
WidgetClassName | = | 'TSquare'.freeze

Public Class methods

style(*args)

[Source]

# File tk/lib/tkextlib/tile/tsquare.rb, line 27
  def self.style(*args)
    [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
  end


Module: Tk::Tile::TileWidget

Module | Tk::Tile::TileWidget
In: | tk/lib/tkextlib/tile.rb

Methods

instate state

Included Modules

Tk::Tile::ParseStyleLayout

Public Instance methods

instate(state, script=nil, &b)

[Source]

# File tk/lib/tkextlib/tile.rb, line 140
      def instate(state, script=nil, &b)
        if script
          tk_send('instate', state, script)
        elsif b
          tk_send('instate', state, Proc.new(&b))
        else
          bool(tk_send('instate', state))
        end
      end
state(state=nil)

[Source]

# File tk/lib/tkextlib/tile.rb, line 150
      def state(state=nil)
        if state
          tk_send('state', state)
        else
          list(tk_send('state'))
        end
      end


Class: Tk::Tile::Treeview

Class | Tk::Tile::Treeview
In: | tk/lib/tkextlib/tile/treeview.rb
Parent: | TkWindow

Methods

children delete detach exist? focus_item get get_directory identify index insert instate move next parent prev see selection selection_add selection_get selection_remove selection_set selection_toggle set set_children state style tagid

Included Modules

Tk::Tile::TileWidget Scrollable Tk::Tile::TreeviewConfig

Constants

TkCommandNames | = | ['::ttk::treeview'.freeze].freeze
TkCommandNames | = | ['::treeview'.freeze].freeze
WidgetClassName | = | 'Treeview'.freeze

Public Class methods

style(*args)

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 149
  def self.style(*args)
    [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
  end

Public Instance methods

children(item)

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 161
  def children(item)
    simplelist(tk_send_without_enc('children', item))
  end
delete(*items)

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 170
  def delete(*items)
    tk_send_without_enc('delete', array2tk_list(items.flatten, true))
    self
  end
detach(*items)

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 175
  def detach(*items)
    tk_send_without_enc('detach', array2tk_list(items.flatten, true))
    self
  end
exist?(item)

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 180
  def exist?(item)
    bool(tk_send_without_enc('exists', _get_eval_enc_str(item)))
  end
focus_item(item = None)

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 184
  def focus_item(item = None)
    tk_send('focus', item)
  end
get(item, col)

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 273
  def get(item, col)
    tk_send('set', item, col)
  end
get_directory(item)

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 262
  def get_directory(item)
    # tile-0.7+
    ret = []
    lst = simplelist(tk_send('set', item))
    until lst.empty?
      col = lst.shift
      val = lst.shift
      ret << [col, val]
    end
    ret
  end
identify(x, y)

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 188
  def identify(x, y)
    ret = simplelist(tk_send('identify', x, y))
    case ret[0]
    when 'heading', 'separator', 'cell'
      ret[-1] = num_or_str(ret[-1])
    end
  end
index(item)

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 196
  def index(item)
    number(tk_send('index', item))
  end
insert(parent, idx, keys={})

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 200
  def insert(parent, idx, keys={})
    keys = _symbolkey2str(keys)
    id = keys.delete('id')
    if id
      tk_send('insert', parent, idx, '-id', id, *hash_kv(keys))
    else
      tk_send('insert', parent, idx, *hash_kv(keys))
    end
    self
  end
instate(spec, cmd=Proc.new)

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 211
  def instate(spec, cmd=Proc.new)
    tk_send('instate', spec, cmd)
  end
move(item, parent, idx)

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 218
  def move(item, parent, idx)
    tk_send('move', item, parent, idx)
    self
  end
next(item)

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 223
  def next(item)
    tk_send('next', item)
  end
parent(item)

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 227
  def parent(item)
    tk_send('parent', item)
  end
prev(item)

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 231
  def prev(item)
    tk_send('prev', item)
  end
see(item)

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 235
  def see(item)
    tk_send('see', item)
    self
  end
selection()

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 240
  def selection
    simplelist(tk_send('selection'))
  end
selection_add(*items)

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 245
  def selection_add(*items)
    tk_send('selection', 'add', array2tk_list(items.flatten, true))
    self
  end
selection_get()

Alias for selection

selection_remove(*items)

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 249
  def selection_remove(*items)
    tk_send('selection', 'remove', array2tk_list(items.flatten, true))
    self
  end
selection_set(*items)

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 253
  def selection_set(*items)
    tk_send('selection', 'set', array2tk_list(items.flatten, true))
    self
  end
selection_toggle(*items)

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 257
  def selection_toggle(*items)
    tk_send('selection', 'toggle', array2tk_list(items.flatten, true))
    self
  end
set(item, col, value)

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 276
  def set(item, col, value)
    tk_send('set', item, col, value)
    self
  end
set_children(item, *items)

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 164
  def set_children(item, *items)
    tk_send_without_enc('children', item,
                        array2tk_list(items.flatten, true))
    self
  end
state(spec=None)

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 214
  def state(spec=None)
    tk_send('state', spec)
  end
tagid(id)

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 153
  def tagid(id)
    if id.kind_of?(Array)
      [id[0], _get_eval_string(id[1])]
    else
      _get_eval_string(id)
    end
  end


Module: Tk::Tile::TreeviewConfig

Module | Tk::Tile::TreeviewConfig
In: | tk/lib/tkextlib/tile/treeview.rb

Methods

column_cget column_configinfo column_configure columncget columnconfiginfo columnconfigure current_column_configinfo current_columnconfiginfo current_heading_configinfo current_headingconfiginfo current_itemconfiginfo heading_cget heading_configinfo heading_configure headingcget headingconfiginfo headingconfigure itemcget itemconfiginfo itemconfigure

Included Modules

TkItemConfigMethod

External Aliases

itemcget | -> | __itemcget
itemconfigure | -> | __itemconfigure
itemconfiginfo | -> | __itemconfiginfo
current_itemconfiginfo | -> | __current_itemconfiginfo

Public Instance methods

column_cget(tagOrId, option)

Alias for columncget

column_configinfo(tagOrId, slot=nil)

Alias for columnconfiginfo

column_configure(tagOrId, slot, value=None)

Alias for columnconfigure

columncget(tagOrId, option)

Treeview Column

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 97
      def columncget(tagOrId, option)
        __itemcget([:column, tagOrId], option)
      end
columnconfiginfo(tagOrId, slot=nil)

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 103
      def columnconfiginfo(tagOrId, slot=nil)
        __itemconfiginfo([:column, tagOrId], slot)
      end
columnconfigure(tagOrId, slot, value=None)

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 100
      def columnconfigure(tagOrId, slot, value=None)
        __itemconfigure([:column, tagOrId], slot, value)
      end
current_column_configinfo(tagOrId, slot=nil)

Alias for current_columnconfiginfo

current_columnconfiginfo(tagOrId, slot=nil)

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 106
      def current_columnconfiginfo(tagOrId, slot=nil)
        __current_itemconfiginfo([:column, tagOrId], slot)
      end
current_heading_configinfo(tagOrId, slot=nil)

Alias for current_headingconfiginfo

current_headingconfiginfo(tagOrId, slot=nil)

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 124
      def current_headingconfiginfo(tagOrId, slot=nil)
        __current_itemconfiginfo([:heading, tagOrId], slot)
      end
current_itemconfiginfo(tagOrId, slot=nil)

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 92
      def current_itemconfiginfo(tagOrId, slot=nil)
        __current_itemconfiginfo([:item, tagOrId], slot)
      end
heading_cget(tagOrId, option)

Alias for headingcget

heading_configinfo(tagOrId, slot=nil)

Alias for headingconfiginfo

heading_configure(tagOrId, slot, value=None)

Alias for headingconfigure

headingcget(tagOrId, option)

Treeview Heading

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 115
      def headingcget(tagOrId, option)
        __itemcget([:heading, tagOrId], option)
      end
headingconfiginfo(tagOrId, slot=nil)

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 121
      def headingconfiginfo(tagOrId, slot=nil)
        __itemconfiginfo([:heading, tagOrId], slot)
      end
headingconfigure(tagOrId, slot, value=None)

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 118
      def headingconfigure(tagOrId, slot, value=None)
        __itemconfigure([:heading, tagOrId], slot, value)
      end
itemcget(tagOrId, option)

Treeview Item

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 83
      def itemcget(tagOrId, option)
        __itemcget([:item, tagOrId], option)
      end
itemconfiginfo(tagOrId, slot=nil)

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 89
      def itemconfiginfo(tagOrId, slot=nil)
        __itemconfiginfo([:item, tagOrId], slot)
      end
itemconfigure(tagOrId, slot, value=None)

[Source]

# File tk/lib/tkextlib/tile/treeview.rb, line 86
      def itemconfigure(tagOrId, slot, value=None)
        __itemconfigure([:item, tagOrId], slot, value)
      end


Module: Tk::TkDND

Module | Tk::TkDND
In: | tk/lib/tkextlib/tkDND.rb tk/lib/tkextlib/tkDND/tkdnd.rb tk/lib/tkextlib/tkDND/shape.rb

Methods

package_name package_version

Classes and Modules

Module Tk::TkDND::DND
Module Tk::TkDND::Shape
Class Tk::TkDND::DND_Subst

Constants

PACKAGE_NAME = 'tkdnd'.freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/tkDND/tkdnd.rb, line 19
    def self.package_name
      PACKAGE_NAME
    end
package_version()

[Source]

# File tk/lib/tkextlib/tkDND/tkdnd.rb, line 23
    def self.package_version
      begin
        TkPackage.require('tkdnd')
      rescue
        ''
      end
    end


Module: Tk::TkDND::DND

Module | Tk::TkDND::DND
In: | tk/lib/tkextlib/tkDND/tkdnd.rb

Methods

dnd_bindsource dnd_bindsource_info dnd_bindtarget dnd_bindtarget_info dnd_clearsource dnd_cleartarget dnd_drag version

Public Class methods

version()

[Source]

# File tk/lib/tkextlib/tkDND/tkdnd.rb, line 65
      def self.version
        begin
          TkPackage.require('tkdnd')
        rescue
          ''
        end
      end

Public Instance methods

dnd_bindsource(type, *args)

def dnd_bindsource(type, cmd=Proc.new, prior=None)

  tk_call('dnd', 'bindsource', @path, type, cmd, prior)
  self

end

[Source]

# File tk/lib/tkextlib/tkDND/tkdnd.rb, line 135
      def dnd_bindsource(type, *args)
        # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
        if TkComm._callback_entry?(args[0]) || !block_given?
          cmd = args.shift
        else
          cmd = Proc.new
        end

        args = [None] if args.empty

        tk_call('dnd', 'bindsource', @path, type, cmd, *args)
        self
      end
dnd_bindsource_info(type=nil)

[Source]

# File tk/lib/tkextlib/tkDND/tkdnd.rb, line 123
      def dnd_bindsource_info(type=nil)
        if type
          procedure(tk_call('dnd', 'bindsource', @path, type))
        else
          simplelist(tk_call('dnd', 'bindsource', @path))
        end
      end
dnd_bindtarget(type, event, *args)

def dnd_bindtarget(type, event, cmd=Proc.new, prior=50, *args)

  event = tk_event_sequence(event)
  if prior.kind_of?(Numeric)
    tk_call('dnd', 'bindtarget', @path, type, event,
            install_bind_for_event_class(DND_Subst, cmd, *args),
            prior)
  else
    tk_call('dnd', 'bindtarget', @path, type, event,
            install_bind_for_event_class(DND_Subst, cmd, prior, *args))
  end
  self

end

[Source]

# File tk/lib/tkextlib/tkDND/tkdnd.rb, line 95
      def dnd_bindtarget(type, event, *args)
        # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
        if TkComm._callback_entry?(args[0]) || !block_given?
          cmd = args.shift
        else
          cmd = Proc.new
        end

        prior = 50
        prior = args.shift unless args.empty?

        event = tk_event_sequence(event)
        if prior.kind_of?(Numeric)
          tk_call('dnd', 'bindtarget', @path, type, event,
                  install_bind_for_event_class(DND_Subst, cmd, *args),
                  prior)
        else
          tk_call('dnd', 'bindtarget', @path, type, event,
                  install_bind_for_event_class(DND_Subst, cmd, prior, *args))
        end
        self
      end
dnd_bindtarget_info(type=nil, event=nil)

[Source]

# File tk/lib/tkextlib/tkDND/tkdnd.rb, line 73
      def dnd_bindtarget_info(type=nil, event=nil)
        if event
          procedure(tk_call('dnd', 'bindtarget', @path, type, event))
        elsif type
          procedure(tk_call('dnd', 'bindtarget', @path, type))
        else
          simplelist(tk_call('dnd', 'bindtarget', @path))
        end
      end
dnd_clearsource()

[Source]

# File tk/lib/tkextlib/tkDND/tkdnd.rb, line 149
      def dnd_clearsource()
        tk_call('dnd', 'clearsource', @path)
        self
      end
dnd_cleartarget()

[Source]

# File tk/lib/tkextlib/tkDND/tkdnd.rb, line 118
      def dnd_cleartarget
        tk_call('dnd', 'cleartarget', @path)
        self
      end
dnd_drag(keys=nil)

[Source]

# File tk/lib/tkextlib/tkDND/tkdnd.rb, line 154
      def dnd_drag(keys=nil)
        tk_call('dnd', 'drag', @path, *hash_kv(keys))
        self
      end


Class: Tk::TkDND::DND_Subst

Class | Tk::TkDND::DND_Subst
In: | tk/lib/tkextlib/tkDND/tkdnd.rb
Parent: | TkUtil::CallbackSubst

Constants

KEY_TBL | = | [ [ ?a, ?l, :actions ], [ ?A, ?s, :action ], [ ?b, ?L, :codes ], [ ?c, ?s, :code ], [ ?d, ?l, :descriptions ], [ ?D, ?l, :data ], [ ?L, ?l, :source_types ], [ ?m, ?l, :modifiers ], [ ?t, ?l, :types ], [ ?T, ?s, :type ], [ ?W, ?w, :widget ], [ ?x, ?n, :x ], [ ?X, ?n, :x_root ], [ ?y, ?n, :y ], [ ?Y, ?n, :y_root ], nil
PROC_TBL | = | [ [ ?n, TkComm.method(:num_or_str) ], [ ?s, TkComm.method(:string) ], [ ?l, TkComm.method(:list) ], [ ?L, TkComm.method(:simplelist) ], [ ?w, TkComm.method(:window) ], nil


Module: Tk::TkDND::Shape

Module | Tk::TkDND::Shape
In: | tk/lib/tkextlib/tkDND/shape.rb

Methods

package_name package_patchlevel package_version shape_bounds shape_get shape_offset shape_set shape_update version

Constants

PACKAGE_NAME = 'shape'.freeze

External Aliases

package_version | -> | shape_version
package_patchlevel | -> | shape_patchlevel
version | -> | xshape_version

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/tkDND/shape.rb, line 23
      def self.package_name
        PACKAGE_NAME
      end
package_patchlevel()

[Source]

# File tk/lib/tkextlib/tkDND/shape.rb, line 41
      def self.package_patchlevel
        Tk.tk_call('set', 'shape_patchlevel')
      end
package_version()

[Source]

# File tk/lib/tkextlib/tkDND/shape.rb, line 36
      def self.package_version
        Tk.tk_call('set', 'shape_version')
      end
version()

[Source]

# File tk/lib/tkextlib/tkDND/shape.rb, line 46
      def self.version
        tk_call('shape', 'version')
      end

Public Instance methods

shape_bounds(kind=nil)

[Source]

# File tk/lib/tkextlib/tkDND/shape.rb, line 53
      def shape_bounds(kind=nil)
        if kind
          ret = tk_call('shape', 'bounds', @path, "-#{kind}")
        else
          ret = tk_call('shape', 'bounds', @path)
        end
        if ret == ""
          nil
        else
          list(ret)
        end
      end
shape_get(kind=nil)

[Source]

# File tk/lib/tkextlib/tkDND/shape.rb, line 66
      def shape_get(kind=nil)
        if kind
          list(tk_call('shape', 'get', @path, "-#{kind}"))
        else
          list(tk_call('shape', 'get', @path))
        end
      end
shape_offset(x, y, kind=nil)

[Source]

# File tk/lib/tkextlib/tkDND/shape.rb, line 74
      def shape_offset(x, y, kind=nil)
        if kind
          tk_call('shape', 'get', @path, "-#{kind}", x, y)
        else
          tk_call('shape', 'get', @path, x, y)
        end
        self
      end
shape_set(*args)

[Source]

# File tk/lib/tkextlib/tkDND/shape.rb, line 108
      def shape_set(*args) # ?kind? ?offset <x> <y>? srckind ?arg ...?
        tk_call('shape', 'set', @path, *(_parse_shapespec_param(args)))
        self
      end
shape_update(op, *args)

[Source]

# File tk/lib/tkextlib/tkDND/shape.rb, line 113
      def shape_update(op, *args) # ?kind? ?offset <x> <y>? srckind ?arg ...?
        tk_call('shape', 'update', @path, op, *(_parse_shapespec_param(args)))
        self
      end


Class: Tk::TkTable

Class | Tk::TkTable
In: | tk/lib/tkextlib/tktable/tktable.rb
Parent: | TkWindow

Methods

__destroy_hook__ __validation_class_list activate bbox border_dragto border_mark border_mark_col border_mark_row clear_all clear_cache clear_sizes clear_tags col_index curselection curselection= curvalue curvalue= delete_active delete_cols delete_rows get get_area height height_list hidden? hidden_list icursor icursor_set index insert_active insert_cols insert_rows package_name package_version reread row_index scan_dragto scan_mark see selection_anchor selection_clear selection_clear_all selection_include? selection_present selection_set set set_col set_height set_row set_spans set_width span span_list spans tag_cell tag_col tag_col_reset tag_delete tag_exist? tag_include? tag_lower tag_names tag_raise tag_reset tag_row tag_row_reset tagid tagid2obj validate width width_list window_delete window_move window_names

Included Modules

Scrollable Tk::TkTable::ConfigMethod Tk::ValidateConfigure

Classes and Modules

Module Tk::TkTable::ConfigMethod
Class Tk::TkTable::BrowseCommand
Class Tk::TkTable::CellCommand
Class Tk::TkTable::CellTag
Class Tk::TkTable::NamedCellTag
Class Tk::TkTable::SelectionCommand
Class Tk::TkTable::ValidateCommand

Constants

PACKAGE_NAME | = | 'Tktable'.freeze
TkCommandNames | = | ['table'.freeze].freeze
WidgetClassName | = | 'Table'.freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 21
    def self.package_name
      PACKAGE_NAME
    end
package_version()

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 25
    def self.package_version
      begin
        TkPackage.require('Tktable')
      rescue
        ''
      end
    end

Public Instance methods

__destroy_hook__()

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 222
  def __destroy_hook__
    Tk::TkTable::CelTag::CellTagID_TBL.delete(@path)
  end
__validation_class_list()

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 369
  def __validation_class_list
    super() <<
      BrowseCommand << CellCommand << SelectionCommand << ValidateCommand
  end
activate(idx)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 381
  def activate(idx)
    tk_send('activate', tagid(idx))
  end
bbox(idx)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 385
  def bbox(idx)
    list(tk_send('bbox', tagid(idx)))
  end
border_dragto(x, y)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 398
  def border_dragto(x, y)
    tk_send('border', 'dragto', x, y)
  end
border_mark(x, y)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 389
  def border_mark(x, y)
    simplelist(tk_send('border', 'mark', x, y))
  end
border_mark_col(x, y)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 395
  def border_mark_col(x, y)
    tk_send('border', 'mark', x, y, 'col')
  end
border_mark_row(x, y)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 392
  def border_mark_row(x, y)
    tk_send('border', 'mark', x, y, 'row')
  end
clear_all(first=None, last=None)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 414
  def clear_all(first=None, last=None)
    tk_send('clear', 'all', tagid(first), tagid(last))
    self
  end
clear_cache(first=None, last=None)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 402
  def clear_cache(first=None, last=None)
    tk_send('clear', 'cache', tagid(first), tagid(last))
    self
  end
clear_sizes(first=None, last=None)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 406
  def clear_sizes(first=None, last=None)
    tk_send('clear', 'sizes', tagid(first), tagid(last))
    self
  end
clear_tags(first=None, last=None)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 410
  def clear_tags(first=None, last=None)
    tk_send('clear', 'tags', tagid(first), tagid(last))
    self
  end
col_index(idx)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 512
  def col_index(idx)
    number(tk_send('index', tagid(idx), 'col'))
  end
curselection()

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 419
  def curselection
    simplelist(tk_send('curselection'))
  end
curselection=(val)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 422
  def curselection=(val)
    tk_send('curselection', val)
    val
  end
curvalue()

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 427
  def curvalue
    tk_tcl2ruby(tk_send('curvalue'), true, false)
  end
curvalue=(val)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 430
  def curvalue=(val)
    tk_send('curvalue', val)
    val
  end
delete_active(idx1, idx2=None)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 435
  def delete_active(idx1, idx2=None)
    tk_send('delete', 'active', tagid(idx1), tagid(idx2))
    self
  end
delete_cols(*args)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 439
  def delete_cols(*args) # ?switches_array?, index, ?count?
    params = []
    if args[0].kind_of?(Array)
      switches = args.shift
      switches.each{|k| params << "-#{k}"}
    end
    params << '--'
    params << tagid(args.shift)
    params.concat(args)
    tk_send('delete', 'cols', *params)
    self
  end
delete_rows(*args)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 451
  def delete_rows(*args) # ?switches_array?, index, ?count?
    params = []
    if args[0].kind_of?(Array)
      switches = args.shift
      switches.each{|k| params << "-#{k}"}
    end
    params << '--'
    params << tagid(args.shift)
    params.concat(args)
    tk_send('delete', 'rows', *params)
    self
  end
get(idx)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 464
  def get(idx)
    tk_tcl2ruby(tk_send('get', tagid(idx)), true, false)
  end
get_area(idx1, idx2)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 467
  def get_area(idx1, idx2)
    simplelist(tk_send('get', tagid(idx1), tagid(idx2))).collect{|v|
      tk_tcl2ruby(v, true, false)
    }
  end
height(row)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 476
  def height(row)
    number(tk_send('height', row))
  end
height_list()

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 473
  def height_list
    list(tk_send('height'))
  end
hidden?(idx, *args)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 487
  def hidden?(idx, *args)
    if args.empty?
      if (ret = tk_send('hidden', tagid(idx))) == ''
        false
      else
        ret
      end
    else
      bool(tk_send('hidden', tagid(idx), *(args.collect{|i| tagid(i)})))
    end
  end
hidden_list()

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 484
  def hidden_list
    simplelist(tk_send('hidden'))
  end
icursor()

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 499
  def icursor
    number(tk_send('icursor'))
  end
icursor_set(idx)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 502
  def icursor_set(idx)
    number(tk_send('icursor', tagid(idx)))
  end
index(idx)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 506
  def index(idx)
    tk_send('index', tagid(idx))
  end
insert_active(idx, val)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 516
  def insert_active(idx, val)
    tk_send('insert', 'active', tagid(idx), val)
    self
  end
insert_cols(*args)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 520
  def insert_cols(*args) # ?switches_array?, index, ?count?
    params = []
    if args[0].kind_of?(Array)
      switches = args.shift
      switches.each{|k| params << "-#{k}"}
    end
    params << '--'
    params.concat(args)
    params << tagid(args.shift)
    tk_send('insert', 'cols', *params)
    self
  end
insert_rows(*args)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 532
  def insert_rows(*args) # ?switches_array?, index, ?count?
    params = []
    if args[0].kind_of?(Array)
      switches = args.shift
      switches.each{|k| params << "-#{k}"}
    end
    params << '--'
    params << tagid(args.shift)
    params.concat(args)
    tk_send('insert', 'rows', *params)
    self
  end
reread()

def postscript(*args)

  tk_send('postscript', *args)

end

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 549
  def reread
    tk_send('reread')
    self
  end
row_index(idx)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 509
  def row_index(idx)
    number(tk_send('index', tagid(idx), 'row'))
  end
scan_dragto(x, y)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 558
  def scan_dragto(x, y)
    tk_send('scan', 'dragto', x, y)
    self
  end
scan_mark(x, y)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 554
  def scan_mark(x, y)
    tk_send('scan', 'mark', x, y)
    self
  end
see(idx)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 563
  def see(idx)
    tk_send('see', tagid(idx))
    self
  end
selection_anchor(idx)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 568
  def selection_anchor(idx)
    tk_send('selection', 'anchor', tagid(idx))
    self
  end
selection_clear(first, last=None)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 572
  def selection_clear(first, last=None)
    tk_send('selection', 'clear', tagid(first), tagid(last))
    self
  end
selection_clear_all()

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 576
  def selection_clear_all
    selection_clear('all')
  end
selection_include?(idx)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 579
  def selection_include?(idx)
    bool(tk_send('selection', 'includes', tagid(idx)))
  end
selection_present()

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 582
  def selection_present
    bool(tk_send('selection', 'present'))
  end
selection_set(first, last=None)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 585
  def selection_set(first, last=None)
    tk_send('selection', 'set', tagid(first), tagid(last))
    self
  end
set(*pairs)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 590
  def set(*pairs) # idx, val, idx, val, ...
    args = []
    0.step(pairs.size-1, 2){|i|
      args << tagid(pairs[i])
      args << pairs[i+1]
    }
    tk_send('set', *args)
    self
  end
set_col(*pairs)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 608
  def set_col(*pairs) # idx, val, idx, val, ...
    args = []
    0.step(pairs.size-1, 2){|i|
      args << tagid(pairs[i])
      args << pairs[i+1]
    }
    tk_send('set', 'col', *args)
    self
  end
set_height(*pairs)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 479
  def set_height(*pairs)
    tk_send('height', *(pairs.flatten))
    self
  end
set_row(*pairs)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 599
  def set_row(*pairs) # idx, val, idx, val, ...
    args = []
    0.step(pairs.size-1, 2){|i|
      args << tagid(pairs[i])
      args << pairs[i+1]
    }
    tk_send('set', 'row', *args)
    self
  end
set_spans(*pairs)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 686
  def set_spans(*pairs)
    # idx, val, idx, val, ...
    args = []
    0.step(pairs.size-1, 2){|i|
      args << tagid(pairs[i])
      val = pairs[i+1]
      if val.kind_of?(Array)
        args << val.join(',')
      else
        args << val
      end
    }
    tk_send('spans', *args)
    self
  end
set_width(*pairs)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 823
  def set_width(*pairs)
    tk_send('width', *(pairs.flatten))
    self
  end
span(idx)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 680
  def span(idx)
    lst = simplelist(tk_send('spans', tagid(idx)))
    idx = lst[0]
    rows, cols = lst[1].split(',').map!{|n| Integer(n)}
    [idx [rows, cols]]
  end
span_list()

Alias for spans

spans()

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 671
  def spans
    simplelist(tk_send('spans')).collect{|inf|
      lst = simplelist(inf)
      idx = lst[0]
      rows, cols = lst[1].split(',').map!{|n| Integer(n)}
      [idx [rows, cols]]
    }
  end
tag_cell(tag, *cells)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 760
  def tag_cell(tag, *cells)
    tk_send('tag', 'cell', tagid(tag), *(cells.collect{|idx| tagid(idx)}))
    self
  end
tag_col(tag, *cols)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 768
  def tag_col(tag, *cols)
    tk_send('tag', 'col', tagid(tag), *cols)
    self
  end
tag_col_reset(*cols)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 772
  def tag_col_reset(*cols)
    tk_send('tag', 'col', '', *cols)
    self
  end
tag_delete(tag)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 776
  def tag_delete(tag)
    tk_send('tag', 'delete', tagid(tag))
    if Tk::TkTable::CellTag::CellTagID_TBL[@path]
      if tag.kind_of? Tk::TkTable::CellTag
        Tk::TkTable::CellTag::CellTagID_TBL[@path].delete(tag.id)
      else
        Tk::TkTable::CellTag::CellTagID_TBL[@path].delete(tag)
      end
    end
    self
  end
tag_exist?(tag)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 787
  def tag_exist?(tag)
    bool(tk_send('tag', 'exists', tagid(tag)))
  end
tag_include?(tag, idx)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 790
  def tag_include?(tag, idx)
    bool(tk_send('tag', 'includes', tagid(tag), tagid(idx)))
  end
tag_lower(tag, target=None)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 793
  def tag_lower(tag, target=None)
    tk_send('tag', 'lower', tagid(tag), tagid(target))
    self
  end
tag_names(pat=None)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 797
  def tag_names(pat=None)
    simplelist(tk_send('tag', 'names', pat)).collect{|tag| tagid2obj(tag)}
  end
tag_raise(tag, target=None)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 800
  def tag_raise(tag, target=None)
    tk_send('tag', 'raise', tagid(tag), tagid(target))
    self
  end
tag_reset(*cells)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 764
  def tag_reset(*cells)
    tk_send('tag', 'cell', '', *(cells.collect{|idx| tagid(idx)}))
    self
  end
tag_row(tag, *rows)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 804
  def tag_row(tag, *rows)
    tk_send('tag', 'row', tagid(tag), *rows)
    self
  end
tag_row_reset(*rows)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 808
  def tag_row_reset(*rows)
    tk_send('tag', 'row', '', *rows)
    self
  end
tagid(tag)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 733
  def tagid(tag)
    if tag.kind_of?(Tk::TkTable::CellTag)
      tag.id
    elsif tag.kind_of?(Array)
      if tag[0].kind_of?(Integer) && tag[1].kind_of?(Integer)
        # [row, col]
        tag.join(',')
      else
        tag
      end
    else
      tag
    end
  end
tagid2obj(tagid)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 748
  def tagid2obj(tagid)
    if Tk::TkTable::CellTag::CellTagID_TBL.key?(@path)
      if Tk::TkTable::CellTag::CellTagID_TBL[@path].key?(tagid)
        Tk::TkTable::CellTag::CellTagID_TBL[@path][tagid]
      else
        tagid
      end
    else
      tagid
    end
  end
validate(idx)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 813
  def validate(idx)
    bool(tk_send('validate', tagid(idx)))
  end
width(row)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 820
  def width(row)
    number(tk_send('width', row))
  end
width_list()

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 817
  def width_list
    list(tk_send('width'))
  end
window_delete(*args)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 828
  def window_delete(*args)
    tk_send('window', 'delete', *(args.collect{|idx| tagid(idx)}))
    self
  end
window_move(from_idx, to_idx)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 832
  def window_move(from_idx, to_idx)
    tk_send('window', 'move', tagid(from_idx), tagid(to_idx))
    self
  end
window_names(pat=None)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 836
  def window_names(pat=None)
    simplelist(tk_send('window', 'names', pat))
  end


Class: Tk::TkTable::BrowseCommand

Class | Tk::TkTable::BrowseCommand
In: | tk/lib/tkextlib/tktable/tktable.rb
Parent: | TkValidateCommand

Methods

_config_keys

Classes and Modules

Class Tk::TkTable::BrowseCommand::ValidateArgs

Public Class methods

_config_keys()

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 268
    def self._config_keys
      ['browsecommand', 'browsecmd']
    end


Class: Tk::TkTable::BrowseCommand::ValidateArgs

Class | Tk::TkTable::BrowseCommand::ValidateArgs
In: | tk/lib/tkextlib/tktable/tktable.rb
Parent: | TkUtil::CallbackSubst

Methods

ret_val

Constants

KEY_TBL | = | [ [ ?c, ?n, :column ], [ ?C, ?s, :index ], [ ?i, ?x, :cursor ], [ ?r, ?n, :row ], [ ?s, ?s, :last_index ], [ ?S, ?s, :new_index ], [ ?W, ?w, :widget ], nil
PROC_TBL | = | [ [ ?n, TkComm.method(:number) ], [ ?x, TkComm.method(:num_or_str) ], [ ?s, TkComm.method(:string) ], [ ?w, TkComm.method(:window) ], nil

Public Class methods

ret_val(val)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 263
      def self.ret_val(val)
        val
      end


Class: Tk::TkTable::CellCommand

Class | Tk::TkTable::CellCommand
In: | tk/lib/tkextlib/tktable/tktable.rb
Parent: | TkValidateCommand

Methods

_config_keys

Classes and Modules

Class Tk::TkTable::CellCommand::ValidateArgs

Public Class methods

_config_keys()

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 301
    def self._config_keys
      ['command']
    end


Class: Tk::TkTable::CellCommand::ValidateArgs

Class | Tk::TkTable::CellCommand::ValidateArgs
In: | tk/lib/tkextlib/tktable/tktable.rb
Parent: | TkUtil::CallbackSubst

Methods

ret_val

Constants

KEY_TBL | = | [ [ ?c, ?n, :column ], [ ?C, ?s, :index ], [ ?i, ?m, :rw_mode ], [ ?r, ?n, :row ], [ ?s, ?v, :value ], [ ?W, ?w, :widget ], nil
PROC_TBL | = | [ [ ?n, TkComm.method(:number) ], [ ?s, TkComm.method(:string) ], [ ?w, TkComm.method(:window) ], [ ?m, proc{|val| (val == '0')? (:r) : (:w)} ], [ ?v, proc{|val| TkComm.tk_tcl2ruby(val, true, false)} ], nil

Public Class methods

ret_val(val)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 296
      def self.ret_val(val)
        TkComm._get_eval_string(val)
      end


Class: Tk::TkTable::CellTag

Class | Tk::TkTable::CellTag
In: | tk/lib/tkextlib/tktable/tktable.rb
Parent: | TkObject

Methods

add_cell add_col add_row cget configinfo configure current_configinfo delete destroy exist? id id2obj include? lower new raise

Included Modules

TkTreatTagFont

Constants

CellTagID_TBL | = | TkCore::INTERP.create_table
CellTag_ID | = | ['tktbl:celltag'.freeze, '00000'.taint].freeze

Public Class methods

id2obj(table, id)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 125
  def self.id2obj(table, id)
    tpath = table.path
    return id unless CellTagID_TBL[tpath]
    CellTagID_TBL[tpath][id]? CellTagID_TBL[tpath][id] : id
  end
new(parent, keys=nil)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 131
  def initialize(parent, keys=nil)
    @parent = @t = parent
    @tpath - parent.path
    @path = @id = CellTag_ID.join(TkCore::INTERP._ip_id_)
    CellTagID_TBL[@tpath] = {} unless CellTagID_TBL[@tpath]
    CellTagID_TBL[@tpath][@id] = self
    CellTag_ID[1].succ!
    configure(keys) if keys
  end

Public Instance methods

add_cell(*args)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 159
  def add_cell(*args)
    @t.tag_cell(@id, *args)
  end
add_col(*args)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 162
  def add_col(*args)
    @t.tag_col(@id, *args)
  end
add_row(*args)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 165
  def add_row(*args)
    @t.tag_row(@id, *args)
  end
cget(key)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 176
  def cget(key)
    @t.tag_cget(@id, key)
  end
configinfo(key=nil)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 182
  def configinfo(key=nil)
    @t.tag_configinfo(@id, key)
  end
configure(key, val=None)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 179
  def configure(key, val=None)
    @t.tag_configure(@id, key, val)
  end
current_configinfo(key=nil)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 185
  def current_configinfo(key=nil)
    @t.current_tag_configinfo(@id, key)
  end
delete()

Alias for destroy

destroy()

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 145
  def destroy
    tk_call(@tpath, 'tag', 'delete', @id)
    CellTagID_TBL[@tpath].delete(@id) if CellTagID_TBL[@tpath]
    self
  end
exist?()

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 152
  def exist?
    @t.tag_exist?(@id)
  end
id()

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 141
  def id
    @id
  end
include?(idx)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 155
  def include?(idx)
    @t.tag_include?(@id, idx)
  end
lower(target=None)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 172
  def lower(target=None)
    @t.tag_lower(@id, target)
  end
raise(target=None)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 169
  def raise(target=None)
    @t.tag_raise(@id, target)
  end


Module: Tk::TkTable::ConfigMethod

Module | Tk::TkTable::ConfigMethod
In: | tk/lib/tkextlib/tktable/tktable.rb

Methods

current_tag_configinfo current_window_configinfo tag_cget tag_configinfo tag_configure window_cget window_configinfo window_configure

Included Modules

TkItemConfigMethod

Public Instance methods

current_tag_configinfo(tagOrId, slot=nil)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 86
  def current_tag_configinfo(tagOrId, slot=nil)
    current_itemconfiginfo(['tag', tagid(tagOrId)], slot)
  end
current_window_configinfo(tagOrId, slot=nil)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 107
  def current_window_configinfo(tagOrId, slot=nil)
    current_itemconfiginfo(['window', tagid(tagOrId)], slot)
  end
tag_cget(tagOrId, option)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 77
  def tag_cget(tagOrId, option)
    itemcget(['tag', tagid(tagOrId)], option)
  end
tag_configinfo(tagOrId, slot=nil)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 83
  def tag_configinfo(tagOrId, slot=nil)
    itemconfiginfo(['tag', tagid(tagOrId)], slot)
  end
tag_configure(tagOrId, slot, value=None)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 80
  def tag_configure(tagOrId, slot, value=None)
    itemconfigure(['tag', tagid(tagOrId)], slot, value)
  end
window_cget(tagOrId, option)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 90
  def window_cget(tagOrId, option)
    itemcget(['window', tagid(tagOrId)], option)
  end
window_configinfo(tagOrId, slot=nil)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 104
  def window_configinfo(tagOrId, slot=nil)
    itemconfiginfo(['window', tagid(tagOrId)], slot)
  end
window_configure(tagOrId, slot, value=None)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 93
  def window_configure(tagOrId, slot, value=None)
    if slot == :window || slot == 'window'
      value = _epath(value)
    elsif slot.kind_of?(Hash)
      if slot.key?(:window) || slot.key?('window')
        slot = _symbolkey2str(slot)
        slot['window'] = _epath(slot['window'])
      end
    end
    itemconfigure(['window', tagid(tagOrId)], slot, value)
  end


Class: Tk::TkTable::NamedCellTag

Class | Tk::TkTable::NamedCellTag
In: | tk/lib/tkextlib/tktable/tktable.rb
Parent: | Tk::TkTable::CellTag

Methods

new new

Public Class methods

new(parent, name, keys=nil)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 191
  def self.new(parent, name, keys=nil)
    if CellTagID_TBL[parent.path] && CellTagID_TBL[parent.path][name]
      cell = CellTagID_TBL[parent.path][name]
      cell.configure(keys) if keys
      return cell
    else
      super(parent, name, keys)
    end
  end
new(parent, name, keys=nil)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 201
  def initialize(parent, name, keys=nil)
    @parent = @t = parent
    @tpath - parent.path
    @path = @id = name
    CellTagID_TBL[@tpath] = {} unless CellTagID_TBL[@tpath]
    CellTagID_TBL[@tpath][@id] = self
    configure(keys) if keys
  end


Class: Tk::TkTable::SelectionCommand

Class | Tk::TkTable::SelectionCommand
In: | tk/lib/tkextlib/tktable/tktable.rb
Parent: | TkValidateCommand

Methods

_config_keys

Classes and Modules

Class Tk::TkTable::SelectionCommand::ValidateArgs

Public Class methods

_config_keys()

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 332
    def self._config_keys
      ['selectioncommand', 'selcmd']
    end


Class: Tk::TkTable::SelectionCommand::ValidateArgs

Class | Tk::TkTable::SelectionCommand::ValidateArgs
In: | tk/lib/tkextlib/tktable/tktable.rb
Parent: | TkUtil::CallbackSubst

Methods

ret_val

Constants

KEY_TBL | = | [ [ ?c, ?n, :sel_columns ], [ ?C, ?s, :sel_area ], [ ?i, ?n, :total ], [ ?r, ?n, :sel_rows ], [ ?s, ?s, :value ], [ ?W, ?w, :widget ], nil
PROC_TBL | = | [ [ ?n, TkComm.method(:number) ], [ ?s, TkComm.method(:string) ], [ ?w, TkComm.method(:window) ], nil

Public Class methods

ret_val(val)

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 327
      def self.ret_val(val)
        val.to_s
      end


Class: Tk::TkTable::ValidateCommand

Class | Tk::TkTable::ValidateCommand
In: | tk/lib/tkextlib/tktable/tktable.rb
Parent: | TkValidateCommand

Methods

_config_keys

Classes and Modules

Class Tk::TkTable::ValidateCommand::ValidateArgs

Public Class methods

_config_keys()

[Source]

# File tk/lib/tkextlib/tktable/tktable.rb, line 362
    def self._config_keys
      ['vcmd', 'validatecommand']
    end


Class: Tk::TkTable::ValidateCommand::ValidateArgs

Class | Tk::TkTable::ValidateCommand::ValidateArgs
In: | tk/lib/tkextlib/tktable/tktable.rb
Parent: | TkUtil::CallbackSubst

Constants

KEY_TBL | = | [ [ ?c, ?n, :column ], [ ?C, ?s, :index ], [ ?i, ?x, :cursor ], [ ?r, ?n, :row ], [ ?s, ?v, :current_value ], [ ?S, ?v, :new_value ], [ ?W, ?w, :widget ], nil
PROC_TBL | = | [ [ ?n, TkComm.method(:number) ], [ ?x, TkComm.method(:num_or_str) ], [ ?s, TkComm.method(:string) ], [ ?w, TkComm.method(:window) ], [ ?v, proc{|val| TkComm.tk_tcl2ruby(val, true, false)} ], nil


Module: Tk::TkTrans

Module | Tk::TkTrans
In: | tk/lib/tkextlib/tktrans/tktrans.rb

Methods

package_name package_version

Constants

PACKAGE_NAME = 'tktrans'.freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/tktrans/tktrans.rb, line 18
    def self.package_name
      PACKAGE_NAME
    end
package_version()

[Source]

# File tk/lib/tkextlib/tktrans/tktrans.rb, line 22
    def self.package_version
      begin
        TkPackage.require('tktrans')
      rescue
        ''
      end
    end


Class: Tk::TreeCtrl

Class | Tk::TreeCtrl
In: | tk/lib/tkextlib/treectrl/tktreectrl.rb
Parent: | TkWindow

Methods

image_tint loupe package_name package_version text_layout

Classes and Modules

Module Tk::TreeCtrl::ConfigMethod
Class Tk::TreeCtrl::NotifyEvent

Constants

BindTag_FileList | = | TkBindTag.new_by_name('TreeCtrlFileList')
PACKAGE_NAME | = | 'treectrl'.freeze
HasColumnCreateCommand | = | (TkPackage.vcompare(self.package_version, '1.1') >= 0)

Public Class methods

image_tint(img, color, alpha)

[Source]

# File tk/lib/tkextlib/treectrl/tktreectrl.rb, line 61
    def self.image_tint(img, color, alpha)
      Tk.tk_call_without_enc('imagetint', img, color, alpha)
    end
loupe(img, x, y, w, h, zoom)

[Source]

# File tk/lib/tkextlib/treectrl/tktreectrl.rb, line 47
    def self.loupe(img, x, y, w, h, zoom)
      # NOTE: platform == 'unix' only

      # img  => TkPhotoImage
      # x, y => screen coords
      # w, h => magnifier width and height
      # zoom => zooming rate
      Tk.tk_call_without_enc('loupe', img, x, y, w, h, zoom)
    end
package_name()

[Source]

# File tk/lib/tkextlib/treectrl/tktreectrl.rb, line 23
    def self.package_name
      PACKAGE_NAME
    end
package_version()

[Source]

# File tk/lib/tkextlib/treectrl/tktreectrl.rb, line 27
    def self.package_version
      begin
        TkPackage.require('treectrl')
      rescue
        ''
      end
    end
text_layout(font, text, keys={})

[Source]

# File tk/lib/tkextlib/treectrl/tktreectrl.rb, line 57
    def self.text_layout(font, text, keys={})
      TkComm.list(Tk.tk_call_without_enc('textlayout', font, text, keys))
    end


Module: Tk::TreeCtrl::ConfigMethod

Module | Tk::TreeCtrl::ConfigMethod
In: | tk/lib/tkextlib/treectrl/tktreectrl.rb


Class: Tk::TreeCtrl::NotifyEvent

Class | Tk::TreeCtrl::NotifyEvent
In: | tk/lib/tkextlib/treectrl/tktreectrl.rb
Parent: | TkUtil::CallbackSubst

Constants

KEY_TBL | = | [ [ ?c, ?n, :item_num ], [ ?d, ?s, :detail ], [ ?D, ?l, :items ], [ ?e, ?e, :event ], [ ?I, ?n, :id ], [ ?l, ?n, :lower_bound ], [ ?p, ?n, :active_id ], [ ?P, ?e, :pattern ], [ ?S, ?l, :sel_items ], [ ?T, ?w, :widget ], [ ?u, ?n, :upper_bound ], [ ?W, ?o, :object ], [ ??, ?x, :parm_info ], nil | [ <’%’ subst-key char>, <proc type char>, <instance var (accessor) name>]
PROC_TBL | = | [ [ ?n, TkComm.method(:num_or_str) ], [ ?s, TkComm.method(:string) ], [ ?l, TkComm.method(:list) ], [ ?w, TkComm.method(:window) ], [ ?e, proc{|val| case val | [ <proc type char>, <proc/method to convert tcl-str to ruby-obj>]


Class: Tk::UTF8_String

Class | Tk::UTF8_String
In: | tk/lib/tk/encodedstr.rb
Parent: | EncodedString

Methods

new to_backslash to_backslash_sequence

Constants

Encoding = 'utf-8'.freeze

Public Class methods

new(str)

[Source]

# File tk/lib/tk/encodedstr.rb, line 98
    def self.new(str)
      super(self.subst_utf_backslash(str))
    end

Public Instance methods

to_backslash()

Alias for to_backslash_sequence

to_backslash_sequence()

[Source]

# File tk/lib/tk/encodedstr.rb, line 102
    def to_backslash_sequence
      Tk::EncodedString.utf_to_backslash_sequence(self)
    end


Module: Tk::ValidateConfigure

Module | Tk::ValidateConfigure
In: | tk/lib/tk/validation.rb

Methods

__conv_vcmd_on_hash_kv __def_validcmd __get_validate_key2class __validation_class_list __validcmd_call configure

Public Class methods

__def_validcmd(scope, klass, keys=nil)

[Source]

# File tk/lib/tk/validation.rb, line 8
    def self.__def_validcmd(scope, klass, keys=nil)
      keys = klass._config_keys unless keys
      keys.each{|key|
        eval("def #{key}(*args, &b)
                 __validcmd_call(#{klass.name}, '#{key}', *args, &b)
              end", scope)
      }
    end

Public Instance methods

__conv_vcmd_on_hash_kv(keys)

[Source]

# File tk/lib/tk/validation.rb, line 46
    def __conv_vcmd_on_hash_kv(keys)
      key2class = __get_validate_key2class

      keys = _symbolkey2str(keys)
      key2class.each{|key, klass|
        if keys[key].kind_of?(Array)
          cmd, *args = keys[key]
          keys[key] = klass.new(cmd, args.join(' '))
        # elsif keys[key].kind_of?(Proc) ||  keys[key].kind_of?(Method)
        elsif TkComm._callback_entry?(keys[key])
          keys[key] = klass.new(keys[key])
        end
      }
      keys
    end
__get_validate_key2class()

[Source]

# File tk/lib/tk/validation.rb, line 36
    def __get_validate_key2class
      k2c = {}
      __validation_class_list.each{|klass|
        klass._config_keys.each{|key|
          k2c[key.to_s] = klass
        }
      }
      k2c
    end
__validation_class_list()

[Source]

# File tk/lib/tk/validation.rb, line 31
    def __validation_class_list
      # maybe need to override
      []
    end
__validcmd_call(klass, key, *args, &b)

[Source]

# File tk/lib/tk/validation.rb, line 17
    def __validcmd_call(klass, key, *args, &b)
      return cget(key) if args.empty? && !b

      cmd = (b)? proc(&b) : args.shift

      if cmd.kind_of?(klass)
        configure(key, cmd)
      elsif !args.empty?
        configure(key, [cmd, args])
      else
        configure(key, cmd)
      end
    end
configure(slot, value=TkComm::None)

[Source]

# File tk/lib/tk/validation.rb, line 67
    def configure(slot, value=TkComm::None)
      if slot.kind_of?(Hash)
        super(__conv_vcmd_on_hash_kv(slot))
      else
        super(__conv_vcmd_on_hash_kv(slot=>value))
      end
      self
    end


Module: Tk::Vu

Module | Tk::Vu
In: | tk/lib/tkextlib/vu.rb tk/lib/tkextlib/vu/spinbox.rb tk/lib/tkextlib/vu/pie.rb tk/lib/tkextlib/vu/dial.rb tk/lib/tkextlib/vu/charts.rb tk/lib/tkextlib/vu/bargraph.rb

Methods

package_name package_version

Classes and Modules

Module Tk::Vu::ChartsConfig
Module Tk::Vu::PieSliceConfigMethod
Class Tk::Vu::Bargraph
Class Tk::Vu::Dial
Class Tk::Vu::NamedPieSlice
Class Tk::Vu::Pie
Class Tk::Vu::PieSlice
Class Tk::Vu::TkcBarchart
Class Tk::Vu::TkcSticker
Class Tk::Vu::TkcStripchart

Constants

PACKAGE_NAME | = | 'vu'.freeze
Spinbox | = | TkSpinbox

Public Class methods

package_name()

[Source]

# File tk/lib/tkextlib/vu.rb, line 24
    def self.package_name
      PACKAGE_NAME
    end
package_version()

[Source]

# File tk/lib/tkextlib/vu.rb, line 28
    def self.package_version
      begin
        TkPackage.require('vu')
      rescue
        ''
      end
    end


Class: Tk::Vu::Bargraph

Class | Tk::Vu::Bargraph
In: | tk/lib/tkextlib/vu/bargraph.rb
Parent: | TkWindow

Methods

get set

Constants

TkCommandNames | = | ['::vu::bargraph'.freeze].freeze
WidgetClassName | = | 'Bargraph'.freeze

Public Instance methods

get()

[Source]

# File tk/lib/tkextlib/vu/bargraph.rb, line 58
  def get()
    num_or_str(tk_call_without_enc(@path, 'get'))
  end
set(val = None)

[Source]

# File tk/lib/tkextlib/vu/bargraph.rb, line 53
  def set(val = None)
    tk_call_without_enc(@path, 'set', val)
    self
  end


Module: Tk::Vu::ChartsConfig

Module | Tk::Vu::ChartsConfig
In: | tk/lib/tkextlib/vu/charts.rb

Included Modules

TkItemConfigOptkeys


Class: Tk::Vu::Dial

Class | Tk::Vu::Dial
In: | tk/lib/tkextlib/vu/dial.rb
Parent: | TkWindow

define module/class

Methods

constrain coords get get_label get_tag identify set set_label set_label_constrain set_tag set_tag_constrain

Constants

TkCommandNames | = | ['::vu::dial'.freeze].freeze
WidgetClassName | = | 'Dial'.freeze

Public Instance methods

constrain(val = None)

[Source]

# File tk/lib/tkextlib/vu/dial.rb, line 42
  def constrain(val = None)
    num_or_str(tk_call(@path, 'constrain', val))
  end
coords(val = nil)

[Source]

# File tk/lib/tkextlib/vu/dial.rb, line 33
  def coords(val = nil)
    if val
      tk_split_list(tk_send_without_enc('coords'))
    else
      tk_send_without_enc('coords', val)
      self
    end
  end
get(*args)

[Source]

# File tk/lib/tkextlib/vu/dial.rb, line 46
  def get(*args)
    num_or_str(tk_call(@path, 'get', *args))
  end
get_label(val=nil)

[Source]

# File tk/lib/tkextlib/vu/dial.rb, line 54
  def get_label(val=nil)
    if val
      tk_call(@path, 'label', val)
    else
      ret = []
      lst = simplelist(tk_call(@path, 'label'))
      while lst.size > 0
        ret << ([num_or_str(lst.shift)] << lst.shift)
      end
    end
  end
get_tag(val=nil)

[Source]

# File tk/lib/tkextlib/vu/dial.rb, line 76
  def get_tag(val=nil)
    if val
      tk_call(@path, 'tag', val)
    else
      ret = []
      lst = simplelist(tk_call(@path, 'tag'))
      while lst.size > 0
        ret << ([num_or_str(lst.shift)] << lst.shift)
      end
    end
  end
identify(x, y)

[Source]

# File tk/lib/tkextlib/vu/dial.rb, line 50
  def identify(x, y)
    tk_call(@path, 'identify', x, y)
  end
set(val = None)

[Source]

# File tk/lib/tkextlib/vu/dial.rb, line 98
  def set(val = None)
    tk_call_without_enc(@path, 'set', val)
    self
  end
set_label(val, str, *args)

[Source]

# File tk/lib/tkextlib/vu/dial.rb, line 66
  def set_label(val, str, *args)
    tk_call(@path, 'label', val, str, *args)
    self
  end
set_label_constrain(val, str, *args)

[Source]

# File tk/lib/tkextlib/vu/dial.rb, line 71
  def set_label_constrain(val, str, *args)
    tk_call(@path, 'label', '-constrain', val, str, *args)
    self
  end
set_tag(val, str, *args)

[Source]

# File tk/lib/tkextlib/vu/dial.rb, line 88
  def set_tag(val, str, *args)
    tk_call(@path, 'tag', val, str, *args)
    self
  end
set_tag_constrain(val, str, *args)

[Source]

# File tk/lib/tkextlib/vu/dial.rb, line 93
  def set_tag_constrain(val, str, *args)
    tk_call(@path, 'tag', '-constrain', val, str, *args)
    self
  end


Class: Tk::Vu::NamedPieSlice

Class | Tk::Vu::NamedPieSlice
In: | tk/lib/tkextlib/vu/pie.rb
Parent: | PieSlice

Methods

new new

Public Class methods

new(parent, name, *args)

[Source]

# File tk/lib/tkextlib/vu/pie.rb, line 211
  def self.new(parent, name, *args)
    if SliceID_TBL[parent.path] && SliceID_TBL[parent.path][name]
      return SliceID_TBL[parent.path][name]
    else
      super(parent, name, *args)
    end
  end
new(parent, name, *args)

[Source]

# File tk/lib/tkextlib/vu/pie.rb, line 219
  def initialize(parent, name, *args)
    unless parent.kind_of?(Tk::Vu::Pie)
      fail ArgumentError, "expect a Tk::Vu::Pie instance for 1st argument"
    end
    @parent = @pie = parent
    @ppath = parent.path
    @path = @id = name.to_s
    SliceID_TBL[@ppath] = {} unless SliceID_TBL[@ppath]
    SliceID_TBL[@ppath][@id] = self

    if args[-1].kind_of?(Hash)
      keys = args.unshift
    end
    @pie.set(@id, *args)
    configure(keys)
  end


Class: Tk::Vu::Pie

Class | Tk::Vu::Pie
In: | tk/lib/tkextlib/vu/pie.rb
Parent: | TkWindow

Methods

__destroy_hook__ create delete explode explode_value lower names order raise set set_value set_values slice_value slices sum_value swap tagid value

Included Modules

Tk::Vu::PieSliceConfigMethod

Constants

TkCommandNames | = | ['::vu::pie'.freeze].freeze
WidgetClassName | = | 'Pie'.freeze

Public Instance methods

__destroy_hook__()

[Source]

# File tk/lib/tkextlib/vu/pie.rb, line 42
  def __destroy_hook__
    Tk::Vu::PieSlice::SliceID_TBL.delete(@path)
  end
create(slice, *args)

Alias for set

delete(*glob_pats)

[Source]

# File tk/lib/tkextlib/vu/pie.rb, line 61
  def delete(*glob_pats)
    tk_call(@path, 'delete', *glob_pats)
    self
  end
explode(slice, *args)

[Source]

# File tk/lib/tkextlib/vu/pie.rb, line 66
  def explode(slice, *args)
    tk_call(@path, 'explode', slice, *args)
    self
  end
explode_value(slice)

[Source]

# File tk/lib/tkextlib/vu/pie.rb, line 71
  def explode_value(slice)
    num_or_str(tk_call(@path, 'explode', slice))
  end
lower(slice, below=None)

[Source]

# File tk/lib/tkextlib/vu/pie.rb, line 75
  def lower(slice, below=None)
    tk_call(@path, 'lower', slice, below)
    self
  end
names(*glob_pats)

[Source]

# File tk/lib/tkextlib/vu/pie.rb, line 80
  def names(*glob_pats)
    simplelist(tk_call(@path, 'names', *glob_pats))
  end
order(*args)

[Source]

# File tk/lib/tkextlib/vu/pie.rb, line 85
  def order(*args)
    tk_call(@path, 'order', *args)
    self
  end
raise(slice, above=None)

[Source]

# File tk/lib/tkextlib/vu/pie.rb, line 90
  def raise(slice, above=None)
    tk_call(@path, 'raise', slice, above)
    self
  end
set(slice, *args)

[Source]

# File tk/lib/tkextlib/vu/pie.rb, line 100
  def set(slice, *args)
    num_or_str(tk_call(@path, 'set', slice, *args))
  end
set_value(slice, *args)

Alias for set

set_values(slice, *args)

Alias for set

slice_value(slice)

[Source]

# File tk/lib/tkextlib/vu/pie.rb, line 107
  def slice_value(slice)
    num_or_str(tk_call(@path, 'set', slice))
  end
slices(*glob_pats)

Alias for names

sum_value(val = None)

Alias for value

swap(slice1, slice2)

[Source]

# File tk/lib/tkextlib/vu/pie.rb, line 95
  def swap(slice1, slice2)
    tk_call(@path, 'swap', slice1, slice2)
    self
  end
tagid(tag)

[Source]

# File tk/lib/tkextlib/vu/pie.rb, line 50
  def tagid(tag)
    if tag.kind_of?(Tk::Vu::PieSlice)
      tag.id
    else
      # tag
      _get_eval_string(tag)
    end
  end
value(val = None)

[Source]

# File tk/lib/tkextlib/vu/pie.rb, line 111
  def value(val = None)
    num_or_str(tk_call_without_enc(@path, 'value'))
  end


Class: Tk::Vu::PieSlice

Class | Tk::Vu::PieSlice
In: | tk/lib/tkextlib/vu/pie.rb
Parent: | TkObject

Methods

[] []= cget configinfo configure current_configinfo delete explode explode_value id id2obj lower new raise set set_value value

Constants

SliceID_TBL | = | TkCore::INTERP.create_table
Pie_Slice_ID | = | ['vu:pie'.freeze, '00000'.taint].freeze

Public Class methods

id2obj(pie, id)

[Source]

# File tk/lib/tkextlib/vu/pie.rb, line 122
  def self.id2obj(pie, id)
    pie_path = pie.path
    return id unless SliceID_TBL[pie_path]
    SliceID_TBL[pie_path][id]? SliceID_TBL[pie_path][id]: id
  end
new(parent, *args)

[Source]

# File tk/lib/tkextlib/vu/pie.rb, line 128
  def initialize(parent, *args)
    unless parent.kind_of?(Tk::Vu::Pie)
      fail ArgumentError, "expect a Tk::Vu::Pie instance for 1st argument"
    end
    @parent = @pie = parent
    @ppath = parent.path
    @path = @id = Pie_Slice_ID.join(TkCore::INTERP._ip_id_)
    SliceID_TBL[@ppath] = {} unless SliceID_TBL[@ppath]
    SliceID_TBL[@ppath][@id] = self
    Pie_Slice_ID[1].succ!

    if args[-1].kind_of?(Hash)
      keys = args.unshift
    end
    @pie.set(@id, *args)
    configure(keys)
  end

Public Instance methods

[](key)

[Source]

# File tk/lib/tkextlib/vu/pie.rb, line 150
  def [](key)
    cget key
  end
[]=(key,val)

[Source]

# File tk/lib/tkextlib/vu/pie.rb, line 154
  def []=(key,val)
    configure key, val
    val
  end
cget(slot)

[Source]

# File tk/lib/tkextlib/vu/pie.rb, line 159
  def cget(slot)
    @pie.itemcget(@id, slot)
  end
configinfo(*args)

[Source]

# File tk/lib/tkextlib/vu/pie.rb, line 168
  def configinfo(*args)
    @pie.itemconfiginfo(@id, *args)
  end
configure(*args)

[Source]

# File tk/lib/tkextlib/vu/pie.rb, line 163
  def configure(*args)
    @pie.itemconfigure(@id, *args)
    self
  end
current_configinfo(*args)

[Source]

# File tk/lib/tkextlib/vu/pie.rb, line 172
  def current_configinfo(*args)
    @pie.current_itemconfiginfo(@id, *args)
  end
delete()

[Source]

# File tk/lib/tkextlib/vu/pie.rb, line 176
  def delete
    @pie.delete(@id)
  end
explode(value)

[Source]

# File tk/lib/tkextlib/vu/pie.rb, line 180
  def explode(value)
    @pie.explode(@id, value)
    self
  end
explode_value()

[Source]

# File tk/lib/tkextlib/vu/pie.rb, line 185
  def explode_value
    @pie.explode_value(@id)
  end
id()

[Source]

# File tk/lib/tkextlib/vu/pie.rb, line 146
  def id
    @id
  end
lower(other=None)

[Source]

# File tk/lib/tkextlib/vu/pie.rb, line 189
  def lower(other=None)
    @pie.lower(@id, other)
    self
  end
raise(other=None)

[Source]

# File tk/lib/tkextlib/vu/pie.rb, line 194
  def raise(other=None)
    @pie.raise(@id, other)
    self
  end
set(value)

[Source]

# File tk/lib/tkextlib/vu/pie.rb, line 199
  def set(value)
    @pie.set(@id, value)
    self
  end
set_value(value)

Alias for set

value()

[Source]

# File tk/lib/tkextlib/vu/pie.rb, line 205
  def value
    @pie.set(@id)
  end


Module: Tk::Vu::PieSliceConfigMethod

Module | Tk::Vu::PieSliceConfigMethod
In: | tk/lib/tkextlib/vu/pie.rb

Included Modules

TkItemConfigMethod


Class: Tk::Vu::TkcBarchart

Class | Tk::Vu::TkcBarchart
In: | tk/lib/tkextlib/vu/charts.rb
Parent: | TkcItem

Included Modules

ChartsConfig

Constants

CItemTypeName = 'barchart'.freeze


Class: Tk::Vu::TkcSticker

Class | Tk::Vu::TkcSticker
In: | tk/lib/tkextlib/vu/charts.rb
Parent: | TkcItem

Included Modules

ChartsConfig

Constants

CItemTypeName = 'sticker'.freeze


Class: Tk::Vu::TkcStripchart

Class | Tk::Vu::TkcStripchart
In: | tk/lib/tkextlib/vu/charts.rb
Parent: | TkcItem

Included Modules

ChartsConfig

Constants

CItemTypeName = 'stripchart'.freeze


Class: Tk::Winico

Class | Tk::Winico
In: | tk/lib/tkextlib/winico/winico.rb
Parent: | TkObject

Methods

_config_keys delete destroy icon_info id id2obj info info new new_from_file new_from_resource package_name package_version set_window

Classes and Modules

Class Tk::Winico::Winico_callback

Constants

PACKAGE_NAME | = | 'winico'.freeze
WinicoID_TBL | = | TkCore::INTERP.create_table

Public Class methods

_config_keys()

[Source]

# File tk/lib/tkextlib/winico/winico.rb, line 145
    def self._config_keys
      ['callback']
    end
icon_info(id)

[Source]

# File tk/lib/tkextlib/winico/winico.rb, line 49
  def self.icon_info(id)
    simplelist(Tk.tk_call('winico', 'info', id)).collect{|inf|
      h = Hash[*list(inf)]
      h.keys.each{|k| h[k[1..-1]] = h.delete(k)}
    }
  end
id2obj(id)

[Source]

# File tk/lib/tkextlib/winico/winico.rb, line 39
  def self.id2obj(id)
    (WinicoID_TBL.key?(id))? WinicoID_TBL[id] : id
  end
info()

[Source]

# File tk/lib/tkextlib/winico/winico.rb, line 43
  def self.info
    simplelist(Tk.tk_call('winico', 'info')).collect{|id|
      Tk::Winico.id2obj(id)
    }
  end
new(file_name, resource_name=nil, winico_id=nil)

[Source]

# File tk/lib/tkextlib/winico/winico.rb, line 66
  def initialize(file_name, resource_name=nil, winico_id=nil)
    if resource_name
      # from resource
      if file_name
        @id = Tk.tk_call('winico', 'load', resource_name, file_name)
      else
        @id = Tk.tk_call('winico', 'load', resource_name)
      end
    elsif file_name
      # from .ico file
      @id = Tk.tk_call('winico', 'createfrom', file_name)
    elsif winico_id
      @id = winico_id
    else
      fail ArgumentError,
           "must be given proper information from where loading icons"
    end
    @path = @id
    WinicoID_TBL[@id] = self
  end
new_from_file(file_name)

[Source]

# File tk/lib/tkextlib/winico/winico.rb, line 58
  def self.new_from_file(file_name)
    self.new(file_name)
  end
new_from_resource(resource_name, file_name = nil)

[Source]

# File tk/lib/tkextlib/winico/winico.rb, line 62
  def self.new_from_resource(resource_name, file_name = nil)
    self.new(file_name, resource_name)
  end
package_name()

[Source]

# File tk/lib/tkextlib/winico/winico.rb, line 21
    def self.package_name
      PACKAGE_NAME
    end
package_version()

[Source]

# File tk/lib/tkextlib/winico/winico.rb, line 25
    def self.package_version
      begin
        TkPackage.require('winico')
      rescue
        ''
      end
    end

Public Instance methods

delete()

[Source]

# File tk/lib/tkextlib/winico/winico.rb, line 97
  def delete
    tk_call('winico', 'delete', @id)
    WinicoID_TBL.delete(@id)
    self
  end
destroy()

Alias for delete

id()

[Source]

# File tk/lib/tkextlib/winico/winico.rb, line 87
  def id
    @id
  end
info()

[Source]

# File tk/lib/tkextlib/winico/winico.rb, line 104
  def info
    Tk::Winico.icon_info(@id)
  end
set_window(win_id, *opts)

[Source]

# File tk/lib/tkextlib/winico/winico.rb, line 91
  def set_window(win_id, *opts) # opts := ?'big'|'small'?, ?pos?
    # NOTE:: the window, which is denoted by win_id, MUST BE MAPPED.
    #        If not, then this may fail or crash.
    tk_call('winico', 'setwindow', win_id, @id, *opts)
  end


Class: Tk::Winico::Winico_callback

Class | Tk::Winico::Winico_callback
In: | tk/lib/tkextlib/winico/winico.rb
Parent: | TkValidateCommand

Methods

ret_val

Classes and Modules

Class Tk::Winico::Winico_callback::ValidateArgs

Public Class methods

ret_val(val)

[Source]

# File tk/lib/tkextlib/winico/winico.rb, line 140
      def self.ret_val(val)
        val
      end


Class: Tk::Winico::Winico_callback::ValidateArgs

Class | Tk::Winico::Winico_callback::ValidateArgs
In: | tk/lib/tkextlib/winico/winico.rb
Parent: | TkUtil::CallbackSubst

Constants

KEY_TBL | = | [ [ ?m, ?s, :message ], [ ?i, ?x, :icon ], [ ?x, ?n, :x ], [ ?y, ?n, :y ], [ ?X, ?n, :last_x ], [ ?Y, ?n, :last_y ], [ ?t, ?n, :tickcount ], [ ?w, ?n, :icon_idnum ], [ ?l, ?n, :msg_idnum ], nil
PROC_TBL | = | [ [ ?n, TkComm.method(:number) ], [ ?s, TkComm.method(:string) ], [ ?x, proc{|id| if Tk::Winico::WinicoID_TBL.key?(id)


Module: Tk::Wm

Module | Tk::Wm
In: | tk/lib/tk/wm.rb

Methods

aspect attributes client colormapwindows deiconify focusmodel frame geometry group iconbitmap iconify iconmask iconname iconphoto iconphoto_default iconposition iconwindow maxsize minsize overrideredirect positionfrom protocol protocols resizable sizefrom stackorder stackorder_isabove stackorder_isbelow state title transient withdraw wm_command wm_grid

Included Modules

TkComm

Constants

TkCommandNames | = | ['wm'.freeze].freeze
TOPLEVEL_METHODCALL_OPTKEYS | = | {}

Public Instance methods

aspect(*args)

[Source]

# File tk/lib/tk/wm.rb, line 14
    def aspect(*args)
      if args.length == 0
        list(tk_call_without_enc('wm', 'aspect', path))
      else
        args = args[0] if args.length == 1 && args[0].kind_of?(Array)
        tk_call('wm', 'aspect', path, *args)
        self
      end
    end
attributes(slot=nil,value=None)

[Source]

# File tk/lib/tk/wm.rb, line 25
    def attributes(slot=nil,value=None)
      if slot == nil
        lst = tk_split_list(tk_call('wm', 'attributes', path))
        info = {}
        while key = lst.shift
          info[key[1..-1]] = lst.shift
        end
        info
      elsif slot.kind_of? Hash
        tk_call('wm', 'attributes', path, *hash_kv(slot))
        self
      elsif value == None
        tk_call('wm', 'attributes', path, "-#{slot}")
      else
        tk_call('wm', 'attributes', path, "-#{slot}", value)
        self
      end
    end
client(name=None)

[Source]

# File tk/lib/tk/wm.rb, line 45
    def client(name=None)
      if name == None
        tk_call('wm', 'client', path)
      else
        name = '' if name == nil
        tk_call('wm', 'client', path, name)
        self
      end
    end
colormapwindows(*args)

[Source]

# File tk/lib/tk/wm.rb, line 56
    def colormapwindows(*args)
      if args.size == 0
        list(tk_call_without_enc('wm', 'colormapwindows', path))
      else
        args = args[0] if args.length == 1 && args[0].kind_of?(Array)
        tk_call_without_enc('wm', 'colormapwindows', path, *args)
        self
      end
    end
deiconify(ex = true)

[Source]

# File tk/lib/tk/wm.rb, line 78
    def deiconify(ex = true)
      if ex
        tk_call_without_enc('wm', 'deiconify', path)
      else
        self.iconify
      end
      self
    end
focusmodel(mode = nil)

[Source]

# File tk/lib/tk/wm.rb, line 87
    def focusmodel(mode = nil)
      if mode
        tk_call_without_enc('wm', 'focusmodel', path, mode)
        self
      else
        tk_call_without_enc('wm', 'focusmodel', path)
      end
    end
frame()

[Source]

# File tk/lib/tk/wm.rb, line 97
    def frame
      tk_call_without_enc('wm', 'frame', path)
    end
geometry(geom=nil)

[Source]

# File tk/lib/tk/wm.rb, line 101
    def geometry(geom=nil)
      if geom
        tk_call_without_enc('wm', 'geometry', path, geom)
        self
      else
        tk_call_without_enc('wm', 'geometry', path)
      end
    end
group(leader = nil)

[Source]

# File tk/lib/tk/wm.rb, line 122
    def group(leader = nil)
      if leader
        tk_call('wm', 'group', path, leader)
        self
      else
        window(tk_call('wm', 'group', path))
      end
    end
iconbitmap(bmp=nil)

[Source]

# File tk/lib/tk/wm.rb, line 132
    def iconbitmap(bmp=nil)
      if bmp
        tk_call_without_enc('wm', 'iconbitmap', path, bmp)
        self
      else
        image_obj(tk_call_without_enc('wm', 'iconbitmap', path))
      end
    end
iconify(ex = true)

[Source]

# File tk/lib/tk/wm.rb, line 161
    def iconify(ex = true)
      if ex
        tk_call_without_enc('wm', 'iconify', path)
      else
        self.deiconify
      end
      self
    end
iconmask(bmp=nil)

[Source]

# File tk/lib/tk/wm.rb, line 170
    def iconmask(bmp=nil)
      if bmp
        tk_call_without_enc('wm', 'iconmask', path, bmp)
        self
      else
        image_obj(tk_call_without_enc('wm', 'iconmask', path))
      end
    end
iconname(name=nil)

[Source]

# File tk/lib/tk/wm.rb, line 180
    def iconname(name=nil)
      if name
        tk_call('wm', 'iconname', path, name)
        self
      else
        tk_call('wm', 'iconname', path)
      end
    end
iconphoto(*imgs)

[Source]

# File tk/lib/tk/wm.rb, line 142
    def iconphoto(*imgs)
      if imgs.empty?
        @wm_iconphoto = nil unless defined? @wm_iconphoto
        return @wm_iconphoto
      end

      imgs = imgs[0] if imgs.length == 1 && imgs[0].kind_of?(Array)
      tk_call_without_enc('wm', 'iconphoto', path, *imgs)
      @wm_iconphoto = imgs
      self
    end
iconphoto_default(*imgs)

[Source]

# File tk/lib/tk/wm.rb, line 155
    def iconphoto_default(*imgs)
      imgs = imgs[0] if imgs.length == 1 && imgs[0].kind_of?(Array)
      tk_call_without_enc('wm', 'iconphoto', path, '-default', *imgs)
      self
    end
iconposition(*args)

[Source]

# File tk/lib/tk/wm.rb, line 190
    def iconposition(*args)
      if args.size == 0
        list(tk_call_without_enc('wm', 'iconposition', path))
      else
        args = args[0] if args.length == 1 && args[0].kind_of?(Array)
        tk_call_without_enc('wm', 'iconposition', path, *args)
        self
      end
    end
iconwindow(win = nil)

[Source]

# File tk/lib/tk/wm.rb, line 201
    def iconwindow(win = nil)
      if win
        tk_call_without_enc('wm', 'iconwindow', path, win)
        self
      else
        w = tk_call_without_enc('wm', 'iconwindow', path)
        (w == '')? nil: window(w)
      end
    end
maxsize(*args)

[Source]

# File tk/lib/tk/wm.rb, line 212
    def maxsize(*args)
      if args.size == 0
        list(tk_call_without_enc('wm', 'maxsize', path))
      else
        args = args[0] if args.length == 1 && args[0].kind_of?(Array)
        tk_call_without_enc('wm', 'maxsize', path, *args)
        self
      end
    end
minsize(*args)

[Source]

# File tk/lib/tk/wm.rb, line 223
    def minsize(*args)
      if args.size == 0
        list(tk_call_without_enc('wm', 'minsize', path))
      else
        args = args[0] if args.length == 1 && args[0].kind_of?(Array)
        tk_call_without_enc('wm', 'minsize', path, *args)
        self
      end
    end
overrideredirect(mode=None)

[Source]

# File tk/lib/tk/wm.rb, line 234
    def overrideredirect(mode=None)
      if mode == None
        bool(tk_call_without_enc('wm', 'overrideredirect', path))
      else
        tk_call_without_enc('wm', 'overrideredirect', path, mode)
        self
      end
    end
positionfrom(who=None)

[Source]

# File tk/lib/tk/wm.rb, line 244
    def positionfrom(who=None)
      if who == None
        r = tk_call_without_enc('wm', 'positionfrom', path)
        (r == "")? nil: r
      else
        tk_call_without_enc('wm', 'positionfrom', path, who)
        self
      end
    end
protocol(name=nil, cmd=nil, &b)

[Source]

# File tk/lib/tk/wm.rb, line 255
    def protocol(name=nil, cmd=nil, &b)
      if cmd
        tk_call_without_enc('wm', 'protocol', path, name, cmd)
        self
      elsif b
        tk_call_without_enc('wm', 'protocol', path, name, proc(&b))
        self
      elsif name
        result = tk_call_without_enc('wm', 'protocol', path, name)
        (result == "")? nil : tk_tcl2ruby(result)
      else
        tk_split_simplelist(tk_call_without_enc('wm', 'protocol', path))
      end
    end
protocols(kv=nil)

[Source]

# File tk/lib/tk/wm.rb, line 270
    def protocols(kv=nil)
      unless kv
        ret = {}
        self.protocol.each{|name|
          ret[name] = self.protocol(name)
        }
        return ret
      end

      unless kv.kind_of?(Hash)
        fail ArgumentError, 'expect a hash of protocol=>command'
      end
      kv.each{|k, v| self.protocol(k, v)}
      self
    end
resizable(*args)

[Source]

# File tk/lib/tk/wm.rb, line 287
    def resizable(*args)
      if args.length == 0
        list(tk_call_without_enc('wm', 'resizable', path)).collect{|e| bool(e)}
      else
        args = args[0] if args.length == 1 && args[0].kind_of?(Array)
        tk_call_without_enc('wm', 'resizable', path, *args)
        self
      end
    end
sizefrom(who=None)

[Source]

# File tk/lib/tk/wm.rb, line 298
    def sizefrom(who=None)
      if who == None
        r = tk_call_without_enc('wm', 'sizefrom', path)
        (r == "")? nil: r
      else
        tk_call_without_enc('wm', 'sizefrom', path, who)
        self
      end
    end
stackorder()

[Source]

# File tk/lib/tk/wm.rb, line 309
    def stackorder
      list(tk_call('wm', 'stackorder', path))
    end
stackorder_isabove(win)

[Source]

# File tk/lib/tk/wm.rb, line 313
    def stackorder_isabove(win)
      bool(tk_call('wm', 'stackorder', path, 'isabove', win))
    end
stackorder_isbelow(win)

[Source]

# File tk/lib/tk/wm.rb, line 317
    def stackorder_isbelow(win)
      bool(tk_call('wm', 'stackorder', path, 'isbelow', win))
    end
state(st=nil)

[Source]

# File tk/lib/tk/wm.rb, line 321
    def state(st=nil)
      if st
        tk_call_without_enc('wm', 'state', path, st)
        self
      else
        tk_call_without_enc('wm', 'state', path)
      end
    end
title(str=nil)

[Source]

# File tk/lib/tk/wm.rb, line 331
    def title(str=nil)
      if str
        tk_call('wm', 'title', path, str)
        self
      else
        tk_call('wm', 'title', path)
      end
    end
transient(master=nil)

[Source]

# File tk/lib/tk/wm.rb, line 341
    def transient(master=nil)
      if master
        tk_call_without_enc('wm', 'transient', path, master)
        self
      else
        window(tk_call_without_enc('wm', 'transient', path))
      end
    end
withdraw(ex = true)

[Source]

# File tk/lib/tk/wm.rb, line 351
    def withdraw(ex = true)
      if ex
        tk_call_without_enc('wm', 'withdraw', path)
      else
        self.deiconify
      end
      self
    end
wm_command(value=nil)

[Source]

# File tk/lib/tk/wm.rb, line 67
    def wm_command(value=nil)
      if value
        tk_call('wm', 'command', path, value)
        self
      else
        #procedure(tk_call('wm', 'command', path))
        tk_call('wm', 'command', path)
      end
    end
wm_grid(*args)

[Source]

# File tk/lib/tk/wm.rb, line 111
    def wm_grid(*args)
      if args.size == 0
        list(tk_call_without_enc('wm', 'grid', path))
      else
        args = args[0] if args.length == 1 && args[0].kind_of?(Array)
        tk_call_without_enc('wm', 'grid', path, *args)
        self
      end
    end


Module: Tk::X_Scrollable

Module | Tk::X_Scrollable
In: | tk/lib/tk/scrollable.rb

Methods

xscrollbar xscrollcommand xview xview_moveto xview_scroll

Public Instance methods

xscrollbar(bar=nil)

[Source]

# File tk/lib/tk/scrollable.rb, line 29
    def xscrollbar(bar=nil)
      if bar
        @xscrollbar = bar
        @xscrollbar.orient 'horizontal'
        self.xscrollcommand {|*arg| @xscrollbar.set(*arg)}
        @xscrollbar.command {|*arg| self.xview(*arg)}
        Tk.update  # avoid scrollbar trouble
      end
      @xscrollbar
    end
xscrollcommand(cmd=Proc.new)

[Source]

# File tk/lib/tk/scrollable.rb, line 8
    def xscrollcommand(cmd=Proc.new)
      configure_cmd 'xscrollcommand', cmd
      # Tk.update  # avoid scrollbar trouble
      self
    end
xview(*index)

[Source]

# File tk/lib/tk/scrollable.rb, line 14
    def xview(*index)
      if index.size == 0
        list(tk_send_without_enc('xview'))
      else
        tk_send_without_enc('xview', *index)
        self
      end
    end
xview_moveto(*index)

[Source]

# File tk/lib/tk/scrollable.rb, line 22
    def xview_moveto(*index)
      xview('moveto', *index)
    end
xview_scroll(*index)

[Source]

# File tk/lib/tk/scrollable.rb, line 25
    def xview_scroll(*index)
      xview('scroll', *index)
    end


Module: Tk::Y_Scrollable

Module | Tk::Y_Scrollable
In: | tk/lib/tk/scrollable.rb

Methods

yscrollbar yscrollcommand yview yview_moveto yview_scroll

Public Instance methods

yscrollbar(bar=nil)

[Source]

# File tk/lib/tk/scrollable.rb, line 63
    def yscrollbar(bar=nil)
      if bar
        @yscrollbar = bar
        @yscrollbar.orient 'vertical'
        self.yscrollcommand {|*arg| @yscrollbar.set(*arg)}
        @yscrollbar.command {|*arg| self.yview(*arg)}
        Tk.update  # avoid scrollbar trouble
      end
      @yscrollbar
    end
yscrollcommand(cmd=Proc.new)

[Source]

# File tk/lib/tk/scrollable.rb, line 42
    def yscrollcommand(cmd=Proc.new)
      configure_cmd 'yscrollcommand', cmd
      # Tk.update  # avoid scrollbar trouble
      self
    end
yview(*index)

[Source]

# File tk/lib/tk/scrollable.rb, line 48
    def yview(*index)
      if index.size == 0
        list(tk_send_without_enc('yview'))
      else
        tk_send_without_enc('yview', *index)
        self
      end
    end
yview_moveto(*index)

[Source]

# File tk/lib/tk/scrollable.rb, line 56
    def yview_moveto(*index)
      yview('moveto', *index)
    end
yview_scroll(*index)

[Source]

# File tk/lib/tk/scrollable.rb, line 59
    def yview_scroll(*index)
      yview('scroll', *index)
    end


Module: TkBgError

Module | TkBgError
In: | tk/lib/tk/bgerror.rb

Methods

bgerror set_default set_handler show tkerror

Constants

TkCommandNames = ['bgerror'.freeze].freeze

Public Instance methods

bgerror(message)

[Source]

# File tk/lib/tk/bgerror.rb, line 12
  def bgerror(message)
    tk_call('bgerror', message)
  end
set_default()

[Source]

# File tk/lib/tk/bgerror.rb, line 22
  def set_default
    begin
      tk_call('rename', 'bgerror', '')
    rescue RuntimeError
    end
  end
set_handler(hdlr = Proc.new)

[Source]

# File tk/lib/tk/bgerror.rb, line 19
  def set_handler(hdlr = Proc.new) #==> handler :: proc{|msg| ...body... }
    tk_call('proc', 'bgerror', 'msg', install_cmd(hdlr) + ' $msg')
  end
show(message)

Alias for bgerror

tkerror(message)

Alias for bgerror


Module: TkBindCore

Module | TkBindCore
In: | tk/lib/tk.rb

Methods

bind bind_append bind_remove bindinfo

Public Instance methods

bind(context, *args)

def bind(context, cmd=Proc.new, *args)

  Tk.bind(self, context, cmd, *args)

end

[Source]

# File tk/lib/tk.rb, line 2346
  def bind(context, *args)
    # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    Tk.bind(self, context, cmd, *args)
  end
bind_append(context, *args)

def bind_append(context, cmd=Proc.new, *args)

  Tk.bind_append(self, context, cmd, *args)

end

[Source]

# File tk/lib/tk.rb, line 2359
  def bind_append(context, *args)
    # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    Tk.bind_append(self, context, cmd, *args)
  end
bind_remove(context)

[Source]

# File tk/lib/tk.rb, line 2369
  def bind_remove(context)
    Tk.bind_remove(self, context)
  end
bindinfo(context=nil)

[Source]

# File tk/lib/tk.rb, line 2373
  def bindinfo(context=nil)
    Tk.bindinfo(self, context)
  end


Class: TkBindTag

Class | TkBindTag
In: | tk/lib/tk/bindtag.rb
Parent: | Object

Methods

id2obj inspect name new new_by_name to_eval

Included Modules

TkBindCore

Constants

BTagID_TBL | = | TkCore::INTERP.create_table | BTagID_TBL = {}
Tk_BINDTAG_ID | = | ["btag".freeze, "00000".taint].freeze
ALL | = | self.new_by_name('all')

Public Class methods

id2obj(id)

[Source]

# File tk/lib/tk/bindtag.rb, line 15
  def TkBindTag.id2obj(id)
    BTagID_TBL[id]? BTagID_TBL[id]: id
  end
new(*args, &b)

[Source]

# File tk/lib/tk/bindtag.rb, line 30
  def initialize(*args, &b)
    # @id = Tk_BINDTAG_ID.join('')
    @id = Tk_BINDTAG_ID.join(TkCore::INTERP._ip_id_)
    Tk_BINDTAG_ID[1].succ!
    BTagID_TBL[@id] = self
    bind(*args, &b) if args != []
  end
new_by_name(name, *args, &b)

[Source]

# File tk/lib/tk/bindtag.rb, line 19
  def TkBindTag.new_by_name(name, *args, &b)
    return BTagID_TBL[name] if BTagID_TBL[name]
    self.new.instance_eval{
      BTagID_TBL.delete @id
      @id = name
      BTagID_TBL[@id] = self
      bind(*args, &b) if args != []
      self
    }
  end

Public Instance methods

inspect()

[Source]

# File tk/lib/tk/bindtag.rb, line 48
  def inspect
    #Kernel.format "#<TkBindTag: %s>", @id
    '#<TkBindTag: ' + @id + '>'
  end
name()

[Source]

# File tk/lib/tk/bindtag.rb, line 40
  def name
    @id
  end
to_eval()

[Source]

# File tk/lib/tk/bindtag.rb, line 44
  def to_eval
    @id
  end


Class: TkBindTagAll

Class | TkBindTagAll
In: | tk/lib/tk/bindtag.rb
Parent: | TkBindTag

Methods

new

Public Class methods

new(*args, &b)

[Source]

# File tk/lib/tk/bindtag.rb, line 56
  def TkBindTagAll.new(*args, &b)
    $stderr.puts "Warning: TkBindTagALL is obsolete. Use TkBindTag::ALL\n"

    TkBindTag::ALL.bind(*args, &b) if args != []
    TkBindTag::ALL
  end


Class: TkBitmapImage

Class | TkBitmapImage
In: | tk/lib/tk/image.rb
Parent: | TkImage

Methods

new

Public Class methods

new(*args)

[Source]

# File tk/lib/tk/image.rb, line 104
  def initialize(*args)
    @type = 'bitmap'
    super(*args)
  end


Class: TkButton

Class | TkButton
In: | tk/lib/tk/button.rb
Parent: | TkLabel

Methods

flash invoke

Constants

TkCommandNames | = | ['button'.freeze].freeze
WidgetClassName | = | 'Button'.freeze

Public Instance methods

flash()

[Source]

# File tk/lib/tk/button.rb, line 23
  def flash
    tk_send_without_enc('flash')
    self
  end
invoke()

def create_self(keys)

  if keys and keys != None
    tk_call_without_enc('button', @path, *hash_kv(keys, true))
  else
    tk_call_without_enc('button', @path)
  end

end private :create_self

[Source]

# File tk/lib/tk/button.rb, line 20
  def invoke
    _fromUTF8(tk_send_without_enc('invoke'))
  end


Class: TkCallbackEntry

Class | TkCallbackEntry
In: | tk/tkutil.c
Parent: | TkKernel

Methods

inspect

Public Class methods

inspect()

/

[Source]

/*************************************/

static VALUE
tk_cbe_inspect(self)
    VALUE self;
{
    return rb_str_new2("TkCallbackEntry");
}


Class: TkCanvas

Class | TkCanvas
In: | tk/lib/tkextlib/blt/eps.rb tk/lib/tk/canvas.rb
Parent: | Object

Methods

__destroy_hook__ addtag addtag_above addtag_all addtag_below addtag_closest addtag_enclosed addtag_overlapping addtag_withtag bbox canvasx canvasy coords create dchars delete deltag dtag find find_above find_all find_below find_closest find_enclosed find_overlapping find_withtag gettags icursor index insert itembind itembind_append itembind_remove itembindinfo itemfocus itemtype lower move postscript raise remove scale scan_dragto scan_mark select select_adjust select_clear select_from select_item select_to

Included Modules

TkCanvasItemConfig Scrollable

Constants

TkCommandNames | = | ['canvas'.freeze].freeze
WidgetClassName | = | 'Canvas'.freeze

External Aliases

__item_strval_optkeys | -> | __BLT_EPS_item_strval_optkeys
__item_boolval_optkeys | -> | __BLT_EPS_item_boolval_optkeys

Public Instance methods

__destroy_hook__()

[Source]

# File tk/lib/tk/canvas.rb, line 51
  def __destroy_hook__
    TkcItem::CItemID_TBL.delete(@path)
  end
addtag(tag, mode, *args)

[Source]

# File tk/lib/tk/canvas.rb, line 90
  def addtag(tag, mode, *args)
    mode = mode.to_s
    if args[0] && mode =~ /^(above|below|with(tag)?)$/
      args[0] = tagid(args[0])
    end
    tk_send_without_enc('addtag', tagid(tag), mode, *args)
    self
  end
addtag_above(tagOrId, target)

[Source]

# File tk/lib/tk/canvas.rb, line 98
  def addtag_above(tagOrId, target)
    addtag(tagOrId, 'above', tagid(target))
  end
addtag_all(tagOrId)

[Source]

# File tk/lib/tk/canvas.rb, line 101
  def addtag_all(tagOrId)
    addtag(tagOrId, 'all')
  end
addtag_below(tagOrId, target)

[Source]

# File tk/lib/tk/canvas.rb, line 104
  def addtag_below(tagOrId, target)
    addtag(tagOrId, 'below', tagid(target))
  end
addtag_closest(tagOrId, x, y, halo=None, start=None)

[Source]

# File tk/lib/tk/canvas.rb, line 107
  def addtag_closest(tagOrId, x, y, halo=None, start=None)
    addtag(tagOrId, 'closest', x, y, halo, start)
  end
addtag_enclosed(tagOrId, x1, y1, x2, y2)

[Source]

# File tk/lib/tk/canvas.rb, line 110
  def addtag_enclosed(tagOrId, x1, y1, x2, y2)
    addtag(tagOrId, 'enclosed', x1, y1, x2, y2)
  end
addtag_overlapping(tagOrId, x1, y1, x2, y2)

[Source]

# File tk/lib/tk/canvas.rb, line 113
  def addtag_overlapping(tagOrId, x1, y1, x2, y2)
    addtag(tagOrId, 'overlapping', x1, y1, x2, y2)
  end
addtag_withtag(tagOrId, tag)

[Source]

# File tk/lib/tk/canvas.rb, line 116
  def addtag_withtag(tagOrId, tag)
    addtag(tagOrId, 'withtag', tagid(tag))
  end
bbox(tagOrId, *tags)

[Source]

# File tk/lib/tk/canvas.rb, line 120
  def bbox(tagOrId, *tags)
    list(tk_send_without_enc('bbox', tagid(tagOrId),
                             *tags.collect{|t| tagid(t)}))
  end
canvasx(screen_x, *args)

[Source]

# File tk/lib/tk/canvas.rb, line 164
  def canvasx(screen_x, *args)
    #tk_tcl2ruby(tk_send_without_enc('canvasx', screen_x, *args))
    number(tk_send_without_enc('canvasx', screen_x, *args))
  end
canvasy(screen_y, *args)

[Source]

# File tk/lib/tk/canvas.rb, line 168
  def canvasy(screen_y, *args)
    #tk_tcl2ruby(tk_send_without_enc('canvasy', screen_y, *args))
    number(tk_send_without_enc('canvasy', screen_y, *args))
  end
coords(tag, *args)

[Source]

# File tk/lib/tk/canvas.rb, line 173
  def coords(tag, *args)
    if args == []
      tk_split_list(tk_send_without_enc('coords', tagid(tag)))
    else
      tk_send_without_enc('coords', tagid(tag), *(args.flatten))
      self
    end
  end
create(type, *args)

create a canvas item without creating a TkcItem object

[Source]

# File tk/lib/tk/canvas.rb, line 85
  def create(type, *args)
    type.create(self, *args)
  end
dchars(tag, first, last=None)

[Source]

# File tk/lib/tk/canvas.rb, line 182
  def dchars(tag, first, last=None)
    tk_send_without_enc('dchars', tagid(tag),
                        _get_eval_enc_str(first), _get_eval_enc_str(last))
    self
  end
delete(*args)

[Source]

# File tk/lib/tk/canvas.rb, line 188
  def delete(*args)
    if TkcItem::CItemID_TBL[self.path]
      args.each{|tag|
        find('withtag', tag).each{|item|
          if item.kind_of?(TkcItem)
            TkcItem::CItemID_TBL[self.path].delete(item.id)
          end
        }
      }
    end
    tk_send_without_enc('delete', *args.collect{|t| tagid(t)})
    self
  end
deltag(tag, tag_to_del=None)

Alias for dtag

dtag(tag, tag_to_del=None)

[Source]

# File tk/lib/tk/canvas.rb, line 203
  def dtag(tag, tag_to_del=None)
    tk_send_without_enc('dtag', tagid(tag), tagid(tag_to_del))
    self
  end
find(mode, *args)

[Source]

# File tk/lib/tk/canvas.rb, line 209
  def find(mode, *args)
    list(tk_send_without_enc('find', mode, *args)).collect!{|id|
      TkcItem.id2obj(self, id)
    }
  end
find_above(target)

[Source]

# File tk/lib/tk/canvas.rb, line 214
  def find_above(target)
    find('above', tagid(target))
  end
find_all()

[Source]

# File tk/lib/tk/canvas.rb, line 217
  def find_all
    find('all')
  end
find_below(target)

[Source]

# File tk/lib/tk/canvas.rb, line 220
  def find_below(target)
    find('below', tagid(target))
  end
find_closest(x, y, halo=None, start=None)

[Source]

# File tk/lib/tk/canvas.rb, line 223
  def find_closest(x, y, halo=None, start=None)
    find('closest', x, y, halo, start)
  end
find_enclosed(x1, y1, x2, y2)

[Source]

# File tk/lib/tk/canvas.rb, line 226
  def find_enclosed(x1, y1, x2, y2)
    find('enclosed', x1, y1, x2, y2)
  end
find_overlapping(x1, y1, x2, y2)

[Source]

# File tk/lib/tk/canvas.rb, line 229
  def find_overlapping(x1, y1, x2, y2)
    find('overlapping', x1, y1, x2, y2)
  end
find_withtag(tag)

[Source]

# File tk/lib/tk/canvas.rb, line 232
  def find_withtag(tag)
    find('withtag', tag)
  end
gettags(tagOrId)

[Source]

# File tk/lib/tk/canvas.rb, line 250
  def gettags(tagOrId)
    list(tk_send_without_enc('gettags', tagid(tagOrId))).collect{|tag|
      TkcTag.id2obj(self, tag)
    }
  end
icursor(tagOrId, index)

[Source]

# File tk/lib/tk/canvas.rb, line 256
  def icursor(tagOrId, index)
    tk_send_without_enc('icursor', tagid(tagOrId), index)
    self
  end
index(tagOrId, idx)

[Source]

# File tk/lib/tk/canvas.rb, line 261
  def index(tagOrId, idx)
    number(tk_send_without_enc('index', tagid(tagOrId), idx))
  end
insert(tagOrId, index, string)

[Source]

# File tk/lib/tk/canvas.rb, line 265
  def insert(tagOrId, index, string)
    tk_send_without_enc('insert', tagid(tagOrId), index,
                        _get_eval_enc_str(string))
    self
  end
itembind(tag, context, *args)

def itembind(tag, context, cmd=Proc.new, *args)

  _bind([path, "bind", tagid(tag)], context, cmd, *args)
  self

end

[Source]

# File tk/lib/tk/canvas.rb, line 129
  def itembind(tag, context, *args)
    # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    _bind([path, "bind", tagid(tag)], context, cmd, *args)
    self
  end
itembind_append(tag, context, *args)

def itembind_append(tag, context, cmd=Proc.new, *args)

  _bind_append([path, "bind", tagid(tag)], context, cmd, *args)
  self

end

[Source]

# File tk/lib/tk/canvas.rb, line 144
  def itembind_append(tag, context, *args)
    # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    _bind_append([path, "bind", tagid(tag)], context, cmd, *args)
    self
  end
itembind_remove(tag, context)

[Source]

# File tk/lib/tk/canvas.rb, line 155
  def itembind_remove(tag, context)
    _bind_remove([path, "bind", tagid(tag)], context)
    self
  end
itembindinfo(tag, context=nil)

[Source]

# File tk/lib/tk/canvas.rb, line 160
  def itembindinfo(tag, context=nil)
    _bindinfo([path, "bind", tagid(tag)], context)
  end
itemfocus(tagOrId=nil)

[Source]

# File tk/lib/tk/canvas.rb, line 236
  def itemfocus(tagOrId=nil)
    if tagOrId
      tk_send_without_enc('focus', tagid(tagOrId))
      self
    else
      ret = tk_send_without_enc('focus')
      if ret == ""
        nil
      else
        TkcItem.id2obj(self, ret)
      end
    end
  end
itemtype(tag)

[Source]

# File tk/lib/tk/canvas.rb, line 571
  def itemtype(tag)
    TkcItem.type2class(tk_send('type', tagid(tag)))
  end
lower(tag, below=nil)

[Source]

# File tk/lib/tk/canvas.rb, line 510
  def lower(tag, below=nil)
    if below
      tk_send_without_enc('lower', tagid(tag), tagid(below))
    else
      tk_send_without_enc('lower', tagid(tag))
    end
    self
  end
move(tag, x, y)

[Source]

# File tk/lib/tk/canvas.rb, line 519
  def move(tag, x, y)
    tk_send_without_enc('move', tagid(tag), x, y)
    self
  end
postscript(keys)

[Source]

# File tk/lib/tk/canvas.rb, line 524
  def postscript(keys)
    tk_send("postscript", *hash_kv(keys))
  end
raise(tag, above=nil)

[Source]

# File tk/lib/tk/canvas.rb, line 528
  def raise(tag, above=nil)
    if above
      tk_send_without_enc('raise', tagid(tag), tagid(above))
    else
      tk_send_without_enc('raise', tagid(tag))
    end
    self
  end
remove(*args)

Alias for delete

scale(tag, x, y, xs, ys)

[Source]

# File tk/lib/tk/canvas.rb, line 537
  def scale(tag, x, y, xs, ys)
    tk_send_without_enc('scale', tagid(tag), x, y, xs, ys)
    self
  end
scan_dragto(x, y)

[Source]

# File tk/lib/tk/canvas.rb, line 546
  def scan_dragto(x, y)
    tk_send_without_enc('scan', 'dragto', x, y)
    self
  end
scan_mark(x, y)

[Source]

# File tk/lib/tk/canvas.rb, line 542
  def scan_mark(x, y)
    tk_send_without_enc('scan', 'mark', x, y)
    self
  end
select(mode, *args)

[Source]

# File tk/lib/tk/canvas.rb, line 551
  def select(mode, *args)
    r = tk_send_without_enc('select', mode, *args)
    (mode == 'item')? TkcItem.id2obj(self, r): self
  end
select_adjust(tagOrId, index)

[Source]

# File tk/lib/tk/canvas.rb, line 555
  def select_adjust(tagOrId, index)
    select('adjust', tagid(tagOrId), index)
  end
select_clear()

[Source]

# File tk/lib/tk/canvas.rb, line 558
  def select_clear
    select('clear')
  end
select_from(tagOrId, index)

[Source]

# File tk/lib/tk/canvas.rb, line 561
  def select_from(tagOrId, index)
    select('from', tagid(tagOrId), index)
  end
select_item()

[Source]

# File tk/lib/tk/canvas.rb, line 564
  def select_item
    select('item')
  end
select_to(tagOrId, index)

[Source]

# File tk/lib/tk/canvas.rb, line 567
  def select_to(tagOrId, index)
    select('to', tagid(tagOrId), index)
  end


Module: TkCanvasItemConfig

Module | TkCanvasItemConfig
In: | tk/lib/tk/canvas.rb

Included Modules

TkItemConfigMethod


Class: TkCheckButton

Class | TkCheckButton
In: | tk/lib/tk/checkbutton.rb
Parent: | TkRadioButton

Methods

toggle

Constants

TkCommandNames | = | ['checkbutton'.freeze].freeze
WidgetClassName | = | 'Checkbutton'.freeze

Public Instance methods

toggle()

def create_self(keys)

  if keys and keys != None
    tk_call_without_enc('checkbutton', @path, *hash_kv(keys, true))
  else
    tk_call_without_enc('checkbutton', @path)
  end

end private :create_self

[Source]

# File tk/lib/tk/checkbutton.rb, line 20
  def toggle
    tk_send_without_enc('toggle')
    self
  end


Module: TkClipboard

Module | TkClipboard
In: | tk/lib/tk/clipboard.rb

Methods

append append append_on_display clear clear clear_on_display get get get_on_display set set set_on_display

Included Modules

Tk

Constants

TkCommandNames = ['clipboard'.freeze].freeze

Public Class methods

append(data, keys=nil)

[Source]

# File tk/lib/tk/clipboard.rb, line 47
  def self.append(data, keys=nil)
    args = ['clipboard', 'append']
    args.concat(hash_kv(keys))
    args.concat(['--', data])
    tk_call(*args)
  end
append_on_display(win, data, keys=nil)

[Source]

# File tk/lib/tk/clipboard.rb, line 53
  def self.append_on_display(win, data, keys=nil)
    args = ['clipboard', 'append', '-displayof', win]
    args.concat(hash_kv(keys))
    args.concat(['--', data])
    tk_call(*args)
  end
clear(win=nil)

[Source]

# File tk/lib/tk/clipboard.rb, line 12
  def self.clear(win=nil)
    if win
      tk_call_without_enc('clipboard', 'clear', '-displayof', win)
    else
      tk_call_without_enc('clipboard', 'clear')
    end
  end
clear_on_display(win)

[Source]

# File tk/lib/tk/clipboard.rb, line 19
  def self.clear_on_display(win)
    tk_call_without_enc('clipboard', 'clear', '-displayof', win)
  end
get(type=nil)

[Source]

# File tk/lib/tk/clipboard.rb, line 23
  def self.get(type=nil)
    if type
      tk_call_without_enc('clipboard', 'get', '-type', type)
    else
      tk_call_without_enc('clipboard', 'get')
    end
  end
get_on_display(win, type=nil)

[Source]

# File tk/lib/tk/clipboard.rb, line 30
  def self.get_on_display(win, type=nil)
    if type
      tk_call_without_enc('clipboard', 'get', '-displayof', win, '-type', type)
    else
      tk_call_without_enc('clipboard', 'get', '-displayof', win)
    end
  end
set(data, keys=nil)

[Source]

# File tk/lib/tk/clipboard.rb, line 38
  def self.set(data, keys=nil)
    clear
    append(data, keys)
  end
set_on_display(win, data, keys=nil)

[Source]

# File tk/lib/tk/clipboard.rb, line 42
  def self.set_on_display(win, data, keys=nil)
    clear(win)
    append_on_display(win, data, keys)
  end

Public Instance methods

append(data, keys=nil)

[Source]

# File tk/lib/tk/clipboard.rb, line 71
  def append(data, keys=nil)
    TkClipboard.append_on_display(self, data, keys)
    self
  end
clear()

[Source]

# File tk/lib/tk/clipboard.rb, line 60
  def clear
    TkClipboard.clear_on_display(self)
    self
  end
get(type=nil)

[Source]

# File tk/lib/tk/clipboard.rb, line 64
  def get(type=nil)
    TkClipboard.get_on_display(self, type)
  end
set(data, keys=nil)

[Source]

# File tk/lib/tk/clipboard.rb, line 67
  def set(data, keys=nil)
    TkClipboard.set_on_display(self, data, keys)
    self
  end


Module: TkComm

Module | TkComm
In: | tk/lib/tk.rb

define TkComm module (step 2: event binding)

Methods

_at bind bind_all bind_append bind_append_all bind_remove bind_remove_all bindinfo bindinfo_all image_obj install_cmd subst uninstall_cmd

Included Modules

TkUtil TkEvent

Classes and Modules

Module TkComm::Tk_CMDTBL
Module TkComm::Tk_WINDOWS

Constants

WidgetClassNames = {}.taint
TkExtlibAutoloadModule = [].taint
Tk_IDs = ["00000".taint, "00000".taint].freeze # [0]-cmdid, [1]-winid Tk_CMDTBL = {} Tk_WINDOWS = {}
Tk_CMDTBL = Object.new for backward compatibility
Tk_WINDOWS = Object.new
GET_CONFIGINFO_AS_ARRAY = true GET_CONFIGINFO_AS_ARRAY = false => returns a Hash { opt =>val, … }
                          true  => returns an Array [[opt,val], ... ]

val is a list which includes resource info.

GET_CONFIGINFOwoRES_AS_ARRAY = true for configinfo without resource info; list of [opt, value] pair
          false => returns a Hash { opt=>val, ... }
          true  => returns an Array [[opt,val], ... ]
USE_TCLs_LIST_FUNCTIONS = true

Public Instance methods

_at(x,y=nil)

[Source]

# File tk/lib/tk.rb, line 182
  def _at(x,y=nil)
    if y
      "@#{Integer(x)},#{Integer(y)}"
    else
      "@#{Integer(x)}"
    end
  end
bind(tagOrClass, context, *args)

def bind(tagOrClass, context, cmd=Proc.new, *args)

  _bind(["bind", tagOrClass], context, cmd, *args)
  tagOrClass

end

[Source]

# File tk/lib/tk.rb, line 979
  def bind(tagOrClass, context, *args)
    # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    _bind(["bind", tagOrClass], context, cmd, *args)
    tagOrClass
  end
bind_all(context, *args)

def bind_all(context, cmd=Proc.new, *args)

  _bind(['bind', 'all'], context, cmd, *args)
  TkBindTag::ALL

end

[Source]

# File tk/lib/tk.rb, line 1018
  def bind_all(context, *args)
    # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    _bind(['bind', 'all'], context, cmd, *args)
    TkBindTag::ALL
  end
bind_append(tagOrClass, context, *args)

def bind_append(tagOrClass, context, cmd=Proc.new, *args)

  _bind_append(["bind", tagOrClass], context, cmd, *args)
  tagOrClass

end

[Source]

# File tk/lib/tk.rb, line 994
  def bind_append(tagOrClass, context, *args)
    # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    _bind_append(["bind", tagOrClass], context, cmd, *args)
    tagOrClass
  end
bind_append_all(context, *args)

def bind_append_all(context, cmd=Proc.new, *args)

  _bind_append(['bind', 'all'], context, cmd, *args)
  TkBindTag::ALL

end

[Source]

# File tk/lib/tk.rb, line 1033
  def bind_append_all(context, *args)
    # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    _bind_append(['bind', 'all'], context, cmd, *args)
    TkBindTag::ALL
  end
bind_remove(tagOrClass, context)

[Source]

# File tk/lib/tk.rb, line 1005
  def bind_remove(tagOrClass, context)
    _bind_remove(['bind', tagOrClass], context)
    tagOrClass
  end
bind_remove_all(context)

[Source]

# File tk/lib/tk.rb, line 1044
  def bind_remove_all(context)
    _bind_remove(['bind', 'all'], context)
    TkBindTag::ALL
  end
bindinfo(tagOrClass, context=nil)

[Source]

# File tk/lib/tk.rb, line 1010
  def bindinfo(tagOrClass, context=nil)
    _bindinfo(['bind', tagOrClass], context)
  end
bindinfo_all(context=nil)

[Source]

# File tk/lib/tk.rb, line 1049
  def bindinfo_all(context=nil)
    _bindinfo(['bind', 'all'], context)
  end
image_obj(val)

[Source]

# File tk/lib/tk.rb, line 596
  def image_obj(val)
    if val =~ /^i(_\d+_)?\d+$/
      TkImage::Tk_IMGTBL[val]? TkImage::Tk_IMGTBL[val] : val
    else
      val
    end
  end
install_cmd(cmd)

[Source]

# File tk/lib/tk.rb, line 784
  def install_cmd(cmd)
    return '' if cmd == ''
    id = _next_cmd_id
    #Tk_CMDTBL[id] = cmd
    if cmd.kind_of?(TkCallbackEntry)
      TkCore::INTERP.tk_cmd_tbl[id] = cmd
    else
      TkCore::INTERP.tk_cmd_tbl[id] = TkCore::INTERP.get_cb_entry(cmd)
    end
    @cmdtbl = [] unless defined? @cmdtbl
    @cmdtbl.taint unless @cmdtbl.tainted?
    @cmdtbl.push id
    #return Kernel.format("rb_out %s", id);
    return 'rb_out' + TkCore::INTERP._ip_id_ + ' ' + id
  end
subst(str, *opts)

[Source]

# File tk/lib/tk.rb, line 618
  def subst(str, *opts)
    # opts := :nobackslashes | :nocommands | novariables
    tk_call('subst',
            *(opts.collect{|opt|
                opt = opt.to_s
                (opt[0] == ?-)? opt: '-' << opt
              } << str))
  end
uninstall_cmd(id)

[Source]

# File tk/lib/tk.rb, line 799
  def uninstall_cmd(id)
    id = $1 if /rb_out\S* (c(_\d+_)?\d+)/ =~ id
    #Tk_CMDTBL.delete(id)
    TkCore::INTERP.tk_cmd_tbl.delete(id)
  end


Module: TkComm::Tk_CMDTBL

Module | TkComm::Tk_CMDTBL
In: |

Methods

method_missing

Public Class methods

method_missing(id, *args)

[Source]

# File tk/lib/tk.rb, line 43
  def Tk_CMDTBL.method_missing(id, *args)
    TkCore::INTERP.tk_cmd_tbl.__send__(id, *args)
  end


Module: TkComm::Tk_WINDOWS

Module | TkComm::Tk_WINDOWS
In: |

Methods

method_missing

Public Class methods

method_missing(id, *args)

[Source]

# File tk/lib/tk.rb, line 48
  def Tk_WINDOWS.method_missing(id, *args)
    TkCore::INTERP.tk_windows.__send__(id, *args)
  end


Module: TkComposite

Module | TkComposite
In: | tk/lib/tk/composite.rb

Methods

cget configinfo configure delegate delegate_alias epath new option_methods

Included Modules

Tk

Public Class methods

new(parent=nil, *args)

[Source]

# File tk/lib/tk/composite.rb, line 10
  def initialize(parent=nil, *args)
    @delegates = {}
    @option_methods = {}
    @option_setting = {}

    if parent.kind_of? Hash
      keys = _symbolkey2str(parent)
      parent = keys.delete('parent')
      @frame = TkFrame.new(parent)
      @path = @epath = @frame.path
      initialize_composite(keys)
    else
      @frame = TkFrame.new(parent)
      @path = @epath = @frame.path
      initialize_composite(*args)
    end
  end

Public Instance methods

cget(slot)

[Source]

# File tk/lib/tk/composite.rb, line 71
  def cget(slot)
    slot = slot.to_s

    if @option_methods.include?(slot)
      if @option_methods[slot][:cget]
        return self.__send__(@option_methods[slot][:cget])
      else
        if @option_setting[slot]
          return @option_setting[slot]
        else
          return ''
        end
      end
    end

    tbl = @delegates[slot]
    tbl = @delegates['DEFAULT'] unless tbl

    begin
      if tbl
        opt, wins = tbl[-1]
        opt = slot if opt == 'DEFAULT'
        if wins && wins[-1]
          return wins[-1].cget(opt)
        end
      end
    rescue
    end

    super(slot)
  end
configinfo(slot = nil)

[Source]

# File tk/lib/tk/composite.rb, line 140
  def configinfo(slot = nil)
    if TkComm::GET_CONFIGINFO_AS_ARRAY
      if slot
        slot = slot.to_s
        if @option_methods.include?(slot)
          if @option_methods[slot][:info]
            return self.__send__(@option_methods[slot][:info])
          else
            return [slot, '', '', '', self.cget(slot)]
          end
        end

        tbl = @delegates[slot]
        tbl = @delegates['DEFAULT'] unless tbl

        begin
          if tbl
            if tbl.length == 1
              opt, wins = tbl[0]
              if slot == opt || opt == 'DEFAULT'
                return wins[-1].configinfo(slot)
              else
                info = wins[-1].configinfo(opt)
                info[0] = slot
                return info
              end
            else
              opt, wins = tbl[-1]
              return [slot, '', '', '', wins[-1].cget(opt)]
            end
          end
        rescue
        end

        super(slot)

      else # slot == nil
        info_list = super(slot)

        tbl = @delegates['DEFAULT']
        if tbl
          wins = tbl[0][1]
          if wins && wins[-1]
            wins[-1].configinfo.each{|info|
              slot = info[0]
              info_list.delete_if{|i| i[0] == slot} << info
            }
          end
        end

        @delegates.each{|slot, tbl|
          next if slot == 'DEFAULT'
          if tbl.length == 1
            opt, wins = tbl[0]
            next unless wins && wins[-1]
            if slot == opt
              info_list.delete_if{|i| i[0] == slot} <<
                wins[-1].configinfo(slot)
            else
              info = wins[-1].configinfo(opt)
              info[0] = slot
              info_list.delete_if{|i| i[0] == slot} << info
            end
          else
            opt, wins = tbl[-1]
            info_list.delete_if{|i| i[0] == slot} <<
              [slot, '', '', '', wins[-1].cget(opt)]
          end
        }

        @option_methods.each{|slot, m|
          if m[:info]
            info = self.__send__(m[:info])
          else
            info = [slot, '', '', '', self.cget(slot)]
          end
          info_list.delete_if{|i| i[0] == slot} << info
        }

        info_list
      end

    else # ! TkComm::GET_CONFIGINFO_AS_ARRAY
      if slot
        slot = slot.to_s
        if @option_methods.include?(slot)
          if @option_methods[slot][:info]
            return self.__send__(@option_methods[slot][:info])
          else
            return {slot => ['', '', '', self.cget(slot)]}
          end
        end

        tbl = @delegates[slot]
        tbl = @delegates['DEFAULT'] unless tbl

        begin
          if tbl
            if tbl.length == 1
              opt, wins = tbl[0]
              if slot == opt || opt == 'DEFAULT'
                return wins[-1].configinfo(slot)
              else
                return {slot => wins[-1].configinfo(opt)[opt]}
              end
            else
              opt, wins = tbl[-1]
              return {slot => ['', '', '', wins[-1].cget(opt)]}
            end
          end
        rescue
        end

        super(slot)

      else # slot == nil
        info_list = super(slot)

        tbl = @delegates['DEFAULT']
        if tbl
          wins = tbl[0][1]
          info_list.update(wins[-1].configinfo) if wins && wins[-1]
        end

        @delegates.each{|slot, tbl|
          next if slot == 'DEFAULT'
          if tbl.length == 1
            opt, wins = tbl[0]
            next unless wins && wins[-1]
            if slot == opt
              info_list.update(wins[-1].configinfo(slot))
            else
              info_list.update({slot => wins[-1].configinfo(opt)[opt]})
            end
          else
            opt, wins = tbl[-1]
            info_list.update({slot => ['', '', '', wins[-1].cget(opt)]})
          end
        }

        @option_methods.each{|slot, m|
          if m[:info]
            info = self.__send__(m[:info])
          else
            info = {slot => ['', '', '', self.cget(slot)]}
          end
          info_list.update(info)
        }

        info_list
      end
    end
  end
configure(slot, value=None)

[Source]

# File tk/lib/tk/composite.rb, line 103
  def configure(slot, value=None)
    if slot.kind_of? Hash
      slot.each{|slot,value| configure slot, value}
      return self
    end

    slot = slot.to_s

    if @option_methods.include?(slot)
      unless @option_methods[slot][:cget]
        if value.kind_of?(Symbol)
          @option_setting[slot] = value.to_s
        else
          @option_setting[slot] = value
        end
      end
      return self.__send__(@option_methods[slot][:set], value)
    end

    tbl = @delegates[slot]
    tbl = @delegates['DEFAULT'] unless tbl

    begin
      if tbl
        last = nil
        tbl.each{|opt, wins|
          opt = slot if opt == 'DEFAULT'
          wins.each{|w| last = w.configure(opt, value)}
        }
        return last
      end
    rescue
    end

    super(slot, value)
  end
delegate(option, *wins)

[Source]

# File tk/lib/tk/composite.rb, line 67
  def delegate(option, *wins)
    delegate_alias(option, option, *wins)
  end
delegate_alias(alias_opt, option, *wins)

[Source]

# File tk/lib/tk/composite.rb, line 47
  def delegate_alias(alias_opt, option, *wins)
    if wins.length == 0
      fail ArgumentError, "target widgets are not given"
    end
    if alias_opt != option && (alias_opt == 'DEFAULT' || option == 'DEFAULT')
      fail ArgumentError, "cannot alias 'DEFAULT' option"
    end
    alias_opt = alias_opt.to_s
    option = option.to_s
    if @delegates[alias_opt].kind_of?(Array)
      if (elem = @delegates[alias_opt].assoc(option))
        wins.each{|w| elem[1].push(w)}
      else
        @delegates[alias_opt] << [option, wins]
      end
    else
      @delegates[alias_opt] = [ [option, wins] ]
    end
  end
epath()

[Source]

# File tk/lib/tk/composite.rb, line 28
  def epath
    @epath
  end
option_methods(*opts)

[Source]

# File tk/lib/tk/composite.rb, line 35
  def option_methods(*opts)
    opts.each{|m_set, m_cget, m_info|
      m_set  = m_set.to_s
      m_cget = m_set if !m_cget && self.method(m_set).arity == -1
      m_cget = m_cget.to_s if m_cget
      m_info = m_info.to_s if m_info
      @option_methods[m_set] = {
        :set  => m_set, :cget => m_cget, :info => m_info
      }
    }
  end


Module: TkConfigMethod

Module | TkConfigMethod
In: | tk/lib/tk.rb

Methods

[] []= __confinfo_cmd __conv_keyonly_opts cget config_hash_kv configinfo configure configure_cmd current_configinfo

Included Modules

TkUtil TkTreatFont

Public Instance methods

[](id)

[Source]

# File tk/lib/tk.rb, line 2785
  def [](id)
    cget(id)
  end
[]=(id, val)

[Source]

# File tk/lib/tk.rb, line 2789
  def []=(id, val)
    configure(id, val)
    val
  end
__confinfo_cmd()

[Source]

# File tk/lib/tk.rb, line 2678
  def __confinfo_cmd
    __config_cmd
  end
__conv_keyonly_opts(keys)

[Source]

# File tk/lib/tk.rb, line 2757
  def __conv_keyonly_opts(keys)
    return keys unless keys.kind_of?(Hash)
    keyonly = __keyonly_optkeys
    keys2 = {}
    keys.each{|k, v|
      optkey = keyonly.find{|kk,vv| kk.to_s == k.to_s}
      if optkey
        defkey, undefkey = optkey
        if v
          keys2[defkey.to_s] = None
        elsif undefkey
          keys2[undefkey.to_s] = None
        else
          # remove key
        end
      else
        keys2[k.to_s] = v
      end
    }
    keys2
  end
cget(slot)

[Source]

# File tk/lib/tk.rb, line 2794
  def cget(slot)
    orig_slot = slot
    slot = slot.to_s

   if slot.length == 0
      fail ArgumentError, "Invalid option `#{orig_slot.inspect}'"
    end

    if ( method = _symbolkey2str(__val2ruby_optkeys())[slot] )
      optval = tk_call_without_enc(*(__cget_cmd << "-#{slot}"))
      begin
        return method.call(optval)
      rescue => e
        warn("Warning:: #{e.message} (when #{method}.call(#{optval.inspect})") if $DEBUG
        return optval
      end
    end

    if ( method = _symbolkey2str(__methodcall_optkeys)[slot] )
      return self.__send__(method)
    end

    case slot
    when /^(#{__numval_optkeys.join('|')})$/
      begin
        number(tk_call_without_enc(*(__cget_cmd << "-#{slot}")))
      rescue
        nil
      end

    when /^(#{__numstrval_optkeys.join('|')})$/
      num_or_str(tk_call_without_enc(*(__cget_cmd << "-#{slot}")))

    when /^(#{__boolval_optkeys.join('|')})$/
      begin
        bool(tk_call_without_enc(*(__cget_cmd << "-#{slot}")))
      rescue
        nil
      end

    when /^(#{__listval_optkeys.join('|')})$/
      simplelist(tk_call_without_enc(*(__cget_cmd << "-#{slot}")))

    when /^(#{__numlistval_optkeys.join('|')})$/
      conf = tk_call_without_enc(*(__cget_cmd << "-#{slot}"))
      if conf =~ /^[0-9+-]/
        list(conf)
      else
        conf
      end

    when /^(#{__strval_optkeys.join('|')})$/
      _fromUTF8(tk_call_without_enc(*(__cget_cmd << "-#{slot}")))

    when /^(|latin|ascii|kanji)(#{__font_optkeys.join('|')})$/
      fontcode = $1
      fontkey  = $2
      fnt = tk_tcl2ruby(tk_call_without_enc(*(__cget_cmd << "-#{fontkey}")), true)
      unless fnt.kind_of?(TkFont)
        fnt = fontobj(fontkey)
      end
      if fontcode == 'kanji' && JAPANIZED_TK && TK_VERSION =~ /^4\.*/
        # obsolete; just for compatibility
        fnt.kanji_font
      else
        fnt
      end

    when /^(#{__tkvariable_optkeys.join('|')})$/
      v = tk_call_without_enc(*(__cget_cmd << "-#{slot}"))
      (v.empty?)? nil: TkVarAccess.new(v)

    else
      tk_tcl2ruby(tk_call_without_enc(*(__cget_cmd << "-#{slot}")), true)
    end
  end
config_hash_kv(keys, enc_mode = nil, conf = nil)

[Source]

# File tk/lib/tk.rb, line 2779
  def config_hash_kv(keys, enc_mode = nil, conf = nil)
    hash_kv(__conv_keyonly_opts(keys), enc_mode, conf)
  end
configinfo(slot = nil)

[Source]

# File tk/lib/tk.rb, line 2939
  def configinfo(slot = nil)
    if TkComm::GET_CONFIGINFO_AS_ARRAY
      if (slot &&
          slot.to_s =~ /^(|latin|ascii|kanji)(#{__font_optkeys.join('|')})$/)
        fontkey  = $2
        # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{fontkey}"))))
        conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{fontkey}")), false, true)
        conf[__configinfo_struct[:key]] =
          conf[__configinfo_struct[:key]][1..-1]
        if ( ! __configinfo_struct[:alias] \
            || conf.size > __configinfo_struct[:alias] + 1 )
          conf[__configinfo_struct[:current_value]] = fontobj(fontkey)
        elsif ( __configinfo_struct[:alias] \
               && conf.size == __configinfo_struct[:alias] + 1 \
               && conf[__configinfo_struct[:alias]][0] == ?- )
          conf[__configinfo_struct[:alias]] =
            conf[__configinfo_struct[:alias]][1..-1]
        end
        conf
      else
        if slot
          slot = slot.to_s
          case slot
          when /^(#{__val2ruby_optkeys().keys.join('|')})$/
            method = _symbolkey2str(__val2ruby_optkeys())[slot]
            conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd() << "-#{slot}")), false, true)
            if ( __configinfo_struct[:default_value] \
                && conf[__configinfo_struct[:default_value]] )
              optval = conf[__configinfo_struct[:default_value]]
              begin
                val = method.call(optval)
              rescue => e
                warn("Warning:: #{e.message} (when #{method}.call(#{optval.inspect})") if $DEBUG
                val = optval
              end
              conf[__configinfo_struct[:default_value]] = val
            end
            if ( conf[__configinfo_struct[:current_value]] )
              optval = conf[__configinfo_struct[:current_value]]
              begin
                val = method.call(optval)
              rescue => e
                warn("Warning:: #{e.message} (when #{method}.call(#{optval.inspect})") if $DEBUG
                val = optval
              end
              conf[__configinfo_struct[:current_value]] = val
            end

          when /^(#{__methodcall_optkeys.keys.join('|')})$/
            method = _symbolkey2str(__methodcall_optkeys)[slot]
            return [slot, '', '', '', self.__send__(method)]

          when /^(#{__numval_optkeys.join('|')})$/
            # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
            conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), false, true)

            if ( __configinfo_struct[:default_value] \
                && conf[__configinfo_struct[:default_value]])
              begin
                conf[__configinfo_struct[:default_value]] =
                  number(conf[__configinfo_struct[:default_value]])
              rescue
                conf[__configinfo_struct[:default_value]] = nil
              end
            end
            if ( conf[__configinfo_struct[:current_value]] )
              begin
                conf[__configinfo_struct[:current_value]] =
                  number(conf[__configinfo_struct[:current_value]])
              rescue
                conf[__configinfo_struct[:current_value]] = nil
              end
            end

          when /^(#{__numstrval_optkeys.join('|')})$/
            # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
            conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), false, true)

            if ( __configinfo_struct[:default_value] \
                && conf[__configinfo_struct[:default_value]])
              conf[__configinfo_struct[:default_value]] =
                num_or_str(conf[__configinfo_struct[:default_value]])
            end
            if ( conf[__configinfo_struct[:current_value]] )
              conf[__configinfo_struct[:current_value]] =
                num_or_str(conf[__configinfo_struct[:current_value]])
            end

          when /^(#{__boolval_optkeys.join('|')})$/
            # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
            conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), false, true)

            if ( __configinfo_struct[:default_value] \
                && conf[__configinfo_struct[:default_value]])
              begin
                conf[__configinfo_struct[:default_value]] =
                  bool(conf[__configinfo_struct[:default_value]])
              rescue
                conf[__configinfo_struct[:default_value]] = nil
              end
            end
            if ( conf[__configinfo_struct[:current_value]] )
              begin
                conf[__configinfo_struct[:current_value]] =
                  bool(conf[__configinfo_struct[:current_value]])
              rescue
                conf[__configinfo_struct[:current_value]] = nil
              end
            end

          when /^(#{__listval_optkeys.join('|')})$/
            # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
            conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), false, true)

            if ( __configinfo_struct[:default_value] \
                && conf[__configinfo_struct[:default_value]])
              conf[__configinfo_struct[:default_value]] =
                simplelist(conf[__configinfo_struct[:default_value]])
            end
            if ( conf[__configinfo_struct[:current_value]] )
              conf[__configinfo_struct[:current_value]] =
                simplelist(conf[__configinfo_struct[:current_value]])
            end

          when /^(#{__numlistval_optkeys.join('|')})$/
            # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
            conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), false, true)

            if ( __configinfo_struct[:default_value] \
                && conf[__configinfo_struct[:default_value]] \
                && conf[__configinfo_struct[:default_value]] =~ /^[0-9]/ )
              conf[__configinfo_struct[:default_value]] =
                list(conf[__configinfo_struct[:default_value]])
            end
            if ( conf[__configinfo_struct[:current_value]] \
                && conf[__configinfo_struct[:current_value]] =~ /^[0-9]/ )
              conf[__configinfo_struct[:current_value]] =
                list(conf[__configinfo_struct[:current_value]])
            end

          when /^(#{__strval_optkeys.join('|')})$/
            # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
            conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), false, true)

          when /^(#{__tkvariable_optkeys.join('|')})$/
            conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), false, true)

            if ( __configinfo_struct[:default_value] \
                && conf[__configinfo_struct[:default_value]])
              v = conf[__configinfo_struct[:default_value]]
              if v.empty?
                conf[__configinfo_struct[:default_value]] = nil
              else
                conf[__configinfo_struct[:default_value]] = TkVarAccess.new(v)
              end
            end
            if ( conf[__configinfo_struct[:current_value]] )
              v = conf[__configinfo_struct[:current_value]]
              if v.empty?
                conf[__configinfo_struct[:current_value]] = nil
              else
                conf[__configinfo_struct[:current_value]] = TkVarAccess.new(v)
              end
            end

          else
            # conf = tk_split_list(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
            conf = tk_split_list(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), 0, false, true)
          end
          conf[__configinfo_struct[:key]] =
            conf[__configinfo_struct[:key]][1..-1]

          if ( __configinfo_struct[:alias] \
              && conf.size == __configinfo_struct[:alias] + 1 \
              && conf[__configinfo_struct[:alias]][0] == ?- )
            conf[__configinfo_struct[:alias]] =
              conf[__configinfo_struct[:alias]][1..-1]
          end

          conf

        else
          # ret = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*__confinfo_cmd))).collect{|conflist|
          #  conf = tk_split_simplelist(conflist)
          ret = tk_split_simplelist(tk_call_without_enc(*__confinfo_cmd), false, false).collect{|conflist|
            conf = tk_split_simplelist(conflist, false, true)
            conf[__configinfo_struct[:key]] =
              conf[__configinfo_struct[:key]][1..-1]

            optkey = conf[__configinfo_struct[:key]]
            case optkey
            when /^(#{__val2ruby_optkeys().keys.join('|')})$/
              method = _symbolkey2str(__val2ruby_optkeys())[optkey]
              if ( __configinfo_struct[:default_value] \
                  && conf[__configinfo_struct[:default_value]] )
                optval = conf[__configinfo_struct[:default_value]]
                begin
                  val = method.call(optval)
                rescue => e
                  warn("Warning:: #{e.message} (when #{method}.call(#{optval.inspect})") if $DEBUG
                  val = optval
                end
                conf[__configinfo_struct[:default_value]] = val
              end
              if ( conf[__configinfo_struct[:current_value]] )
                optval = conf[__configinfo_struct[:current_value]]
                begin
                  val = method.call(optval)
                rescue => e
                  warn("Warning:: #{e.message} (when #{method}.call(#{optval.inspect})") if $DEBUG
                  val = optval
                end
                conf[__configinfo_struct[:current_value]] = val
              end

            when /^(#{__strval_optkeys.join('|')})$/
              # do nothing

            when /^(#{__numval_optkeys.join('|')})$/
              if ( __configinfo_struct[:default_value] \
                  && conf[__configinfo_struct[:default_value]] )
                begin
                  conf[__configinfo_struct[:default_value]] =
                    number(conf[__configinfo_struct[:default_value]])
                rescue
                  conf[__configinfo_struct[:default_value]] = nil
                end
              end
              if ( conf[__configinfo_struct[:current_value]] )
                begin
                  conf[__configinfo_struct[:current_value]] =
                    number(conf[__configinfo_struct[:current_value]])
                rescue
                  conf[__configinfo_struct[:current_value]] = nil
                end
              end

            when /^(#{__numstrval_optkeys.join('|')})$/
              if ( __configinfo_struct[:default_value] \
                  && conf[__configinfo_struct[:default_value]] )
                conf[__configinfo_struct[:default_value]] =
                  num_or_str(conf[__configinfo_struct[:default_value]])
              end
              if ( conf[__configinfo_struct[:current_value]] )
                conf[__configinfo_struct[:current_value]] =
                  num_or_str(conf[__configinfo_struct[:current_value]])
              end

            when /^(#{__boolval_optkeys.join('|')})$/
              if ( __configinfo_struct[:default_value] \
                  && conf[__configinfo_struct[:default_value]] )
                begin
                  conf[__configinfo_struct[:default_value]] =
                    bool(conf[__configinfo_struct[:default_value]])
                rescue
                  conf[__configinfo_struct[:default_value]] = nil
                end
              end
              if ( conf[__configinfo_struct[:current_value]] )
                begin
                  conf[__configinfo_struct[:current_value]] =
                    bool(conf[__configinfo_struct[:current_value]])
                rescue
                  conf[__configinfo_struct[:current_value]] = nil
                end
              end

            when /^(#{__listval_optkeys.join('|')})$/
              if ( __configinfo_struct[:default_value] \
                  && conf[__configinfo_struct[:default_value]] )
                conf[__configinfo_struct[:default_value]] =
                  simplelist(conf[__configinfo_struct[:default_value]])
              end
              if ( conf[__configinfo_struct[:current_value]] )
                conf[__configinfo_struct[:current_value]] =
                  simplelist(conf[__configinfo_struct[:current_value]])
              end

            when /^(#{__numlistval_optkeys.join('|')})$/
              if ( __configinfo_struct[:default_value] \
                  && conf[__configinfo_struct[:default_value]] \
                  && conf[__configinfo_struct[:default_value]] =~ /^[0-9]/ )
                conf[__configinfo_struct[:default_value]] =
                  list(conf[__configinfo_struct[:default_value]])
              end
              if ( conf[__configinfo_struct[:current_value]] \
                  && conf[__configinfo_struct[:current_value]] =~ /^[0-9]/ )
                conf[__configinfo_struct[:current_value]] =
                  list(conf[__configinfo_struct[:current_value]])
              end

            when /^(#{__tkvariable_optkeys.join('|')})$/
              if ( __configinfo_struct[:default_value] \
                  && conf[__configinfo_struct[:default_value]] )
                v = conf[__configinfo_struct[:default_value]]
                if v.empty?
                  conf[__configinfo_struct[:default_value]] = nil
                else
                  conf[__configinfo_struct[:default_value]] = TkVarAccess.new(v)
                end
              end
              if ( conf[__configinfo_struct[:current_value]] )
                v = conf[__configinfo_struct[:current_value]]
                if v.empty?
                  conf[__configinfo_struct[:current_value]] = nil
                else
                  conf[__configinfo_struct[:current_value]] = TkVarAccess.new(v)
                end
              end

            else
              if ( __configinfo_struct[:default_value] \
                  && conf[__configinfo_struct[:default_value]] )
                if conf[__configinfo_struct[:default_value]].index('{')
                  conf[__configinfo_struct[:default_value]] =
                    tk_split_list(conf[__configinfo_struct[:default_value]])
                else
                  conf[__configinfo_struct[:default_value]] =
                    tk_tcl2ruby(conf[__configinfo_struct[:default_value]])
                end
              end
              if conf[__configinfo_struct[:current_value]]
                if conf[__configinfo_struct[:current_value]].index('{')
                  conf[__configinfo_struct[:current_value]] =
                    tk_split_list(conf[__configinfo_struct[:current_value]])
                else
                  conf[__configinfo_struct[:current_value]] =
                    tk_tcl2ruby(conf[__configinfo_struct[:current_value]])
                end
              end
            end

            if ( __configinfo_struct[:alias] \
                && conf.size == __configinfo_struct[:alias] + 1 \
                && conf[__configinfo_struct[:alias]][0] == ?- )
              conf[__configinfo_struct[:alias]] =
                conf[__configinfo_struct[:alias]][1..-1]
            end

            conf
          }

          __font_optkeys.each{|optkey|
            optkey = optkey.to_s
            fontconf = ret.assoc(optkey)
            if fontconf && fontconf.size > 2
              ret.delete_if{|inf| inf[0] =~ /^(|latin|ascii|kanji)#{optkey}$/}
              fontconf[__configinfo_struct[:current_value]] = fontobj(optkey)
              ret.push(fontconf)
            end
          }

          __methodcall_optkeys.each{|optkey, method|
            ret << [optkey.to_s, '', '', '', self.__send__(method)]
          }

          ret
        end
      end

    else # ! TkComm::GET_CONFIGINFO_AS_ARRAY
      if (slot &&
          slot.to_s =~ /^(|latin|ascii|kanji)(#{__font_optkeys.join('|')})$/)
        fontkey  = $2
        # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{fontkey}"))))
        conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{fontkey}")), false, true)
        conf[__configinfo_struct[:key]] =
          conf[__configinfo_struct[:key]][1..-1]

        if ( ! __configinfo_struct[:alias] \
            || conf.size > __configinfo_struct[:alias] + 1 )
          conf[__configinfo_struct[:current_value]] = fontobj(fontkey)
          { conf.shift => conf }
        elsif ( __configinfo_struct[:alias] \
               && conf.size == __configinfo_struct[:alias] + 1 )
          if conf[__configinfo_struct[:alias]][0] == ?-
            conf[__configinfo_struct[:alias]] =
              conf[__configinfo_struct[:alias]][1..-1]
          end
          { conf[0] => conf[1] }
        else
          { conf.shift => conf }
        end
      else
        if slot
          slot = slot.to_s
          case slot
          when /^(#{__val2ruby_optkeys().keys.join('|')})$/
            method = _symbolkey2str(__val2ruby_optkeys())[slot]
            conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), false, true)
            if ( __configinfo_struct[:default_value] \
                && conf[__configinfo_struct[:default_value]] )
              optval = conf[__configinfo_struct[:default_value]]
              begin
                val = method.call(optval)
              rescue => e
                warn("Warning:: #{e.message} (when #{method}.call(#{optval.inspect})") if $DEBUG
                val = optval
              end
              conf[__configinfo_struct[:default_value]] = val
            end
            if ( conf[__configinfo_struct[:current_value]] )
              optval = conf[__configinfo_struct[:current_value]]
              begin
                val = method.call(optval)
              rescue => e
                warn("Warning:: #{e.message} (when #{method}.call(#{optval.inspect})") if $DEBUG
                val = optval
              end
              conf[__configinfo_struct[:current_value]] = val
            end

          when /^(#{__methodcall_optkeys.keys.join('|')})$/
            method = _symbolkey2str(__methodcall_optkeys)[slot]
            return {slot => ['', '', '', self.__send__(method)]}

          when /^(#{__numval_optkeys.join('|')})$/
            # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
            conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), false, true)

            if ( __configinfo_struct[:default_value] \
                && conf[__configinfo_struct[:default_value]] )
              begin
                conf[__configinfo_struct[:default_value]] =
                  number(conf[__configinfo_struct[:default_value]])
              rescue
                conf[__configinfo_struct[:default_value]] = nil
              end
            end
            if ( conf[__configinfo_struct[:current_value]] )
              begin
                conf[__configinfo_struct[:current_value]] =
                  number(conf[__configinfo_struct[:current_value]])
              rescue
                conf[__configinfo_struct[:current_value]] = nil
              end
            end

          when /^(#{__numstrval_optkeys.join('|')})$/
            # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
            conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), false, true)

            if ( __configinfo_struct[:default_value] \
                && conf[__configinfo_struct[:default_value]] )
              conf[__configinfo_struct[:default_value]] =
                num_or_str(conf[__configinfo_struct[:default_value]])
            end
            if ( conf[__configinfo_struct[:current_value]] )
              conf[__configinfo_struct[:current_value]] =
                num_or_str(conf[__configinfo_struct[:current_value]])
            end

          when /^(#{__boolval_optkeys.join('|')})$/
            # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
            conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), false, true)

            if ( __configinfo_struct[:default_value] \
                && conf[__configinfo_struct[:default_value]] )
              begin
                conf[__configinfo_struct[:default_value]] =
                  bool(conf[__configinfo_struct[:default_value]])
              rescue
                conf[__configinfo_struct[:default_value]] = nil
              end
            end
            if ( conf[__configinfo_struct[:current_value]] )
              begin
                conf[__configinfo_struct[:current_value]] =
                  bool(conf[__configinfo_struct[:current_value]])
              rescue
                conf[__configinfo_struct[:current_value]] = nil
              end
            end

          when /^(#{__listval_optkeys.join('|')})$/
            # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
            conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), false, true)

            if ( __configinfo_struct[:default_value] \
                && conf[__configinfo_struct[:default_value]] )
              conf[__configinfo_struct[:default_value]] =
                simplelist(conf[__configinfo_struct[:default_value]])
            end
            if ( conf[__configinfo_struct[:current_value]] )
              conf[__configinfo_struct[:current_value]] =
                simplelist(conf[__configinfo_struct[:current_value]])
            end

          when /^(#{__numlistval_optkeys.join('|')})$/
            # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
            conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), false, true)

            if ( __configinfo_struct[:default_value] \
                && conf[__configinfo_struct[:default_value]] \
                && conf[__configinfo_struct[:default_value]] =~ /^[0-9]/ )
              conf[__configinfo_struct[:default_value]] =
                list(conf[__configinfo_struct[:default_value]])
            end
            if ( conf[__configinfo_struct[:current_value]] \
                && conf[__configinfo_struct[:current_value]] =~ /^[0-9]/ )
              conf[__configinfo_struct[:current_value]] =
                list(conf[__configinfo_struct[:current_value]])
            end

          when /^(#{__tkvariable_optkeys.join('|')})$/
            conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), false, true)

            if ( __configinfo_struct[:default_value] \
                && conf[__configinfo_struct[:default_value]] )
              v = conf[__configinfo_struct[:default_value]]
              if v.empty?
                conf[__configinfo_struct[:default_value]] = nil
              else
                conf[__configinfo_struct[:default_value]] = TkVarAccess.new(v)
              end
            end
            if ( conf[__configinfo_struct[:current_value]] )
              v = conf[__configinfo_struct[:current_value]]
              if v.empty?
                conf[__configinfo_struct[:current_value]] = nil
              else
                conf[__configinfo_struct[:current_value]] = TkVarAccess.new(v)
              end
            end

          when /^(#{__strval_optkeys.join('|')})$/
            # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
            conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), false, true)
          else
            # conf = tk_split_list(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
            conf = tk_split_list(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), 0, false, true)
          end
          conf[__configinfo_struct[:key]] =
            conf[__configinfo_struct[:key]][1..-1]

          if ( __configinfo_struct[:alias] \
              && conf.size == __configinfo_struct[:alias] + 1 )
            if conf[__configinfo_struct[:alias]][0] == ?-
              conf[__configinfo_struct[:alias]] =
                conf[__configinfo_struct[:alias]][1..-1]
            end
            { conf[0] => conf[1] }
          else
            { conf.shift => conf }
          end

        else
          ret = {}
          # tk_split_simplelist(_fromUTF8(tk_call_without_enc(*__confinfo_cmd))).each{|conflist|
          #  conf = tk_split_simplelist(conflist)
          tk_split_simplelist(tk_call_without_enc(*__confinfo_cmd), false, false).each{|conflist|
            conf = tk_split_simplelist(conflist, false, true)
            conf[__configinfo_struct[:key]] =
              conf[__configinfo_struct[:key]][1..-1]

            optkey = conf[__configinfo_struct[:key]]
            case optkey
            when /^(#{__val2ruby_optkeys().keys.join('|')})$/
              method = _symbolkey2str(__val2ruby_optkeys())[optkey]
              if ( __configinfo_struct[:default_value] \
                  && conf[__configinfo_struct[:default_value]] )
                optval = conf[__configinfo_struct[:default_value]]
                begin
                  val = method.call(optval)
                rescue => e
                  warn("Warning:: #{e.message} (when #{method}.call(#{optval.inspect})") if $DEBUG
                  val = optval
                end
                conf[__configinfo_struct[:default_value]] = val
              end
              if ( conf[__configinfo_struct[:current_value]] )
                optval = conf[__configinfo_struct[:current_value]]
                begin
                  val = method.call(optval)
                rescue => e
                  warn("Warning:: #{e.message} (when #{method}.call(#{optval.inspect})") if $DEBUG
                  val = optval
                end
                conf[__configinfo_struct[:current_value]] = val
              end

            when /^(#{__strval_optkeys.join('|')})$/
              # do nothing

            when /^(#{__numval_optkeys.join('|')})$/
              if ( __configinfo_struct[:default_value] \
                  && conf[__configinfo_struct[:default_value]] )
                begin
                  conf[__configinfo_struct[:default_value]] =
                    number(conf[__configinfo_struct[:default_value]])
                rescue
                  conf[__configinfo_struct[:default_value]] = nil
                end
              end
              if ( conf[__configinfo_struct[:current_value]] )
                begin
                  conf[__configinfo_struct[:current_value]] =
                    number(conf[__configinfo_struct[:current_value]])
                rescue
                  conf[__configinfo_struct[:current_value]] = nil
                end
              end

            when /^(#{__numstrval_optkeys.join('|')})$/
              if ( __configinfo_struct[:default_value] \
                  && conf[__configinfo_struct[:default_value]] )
                conf[__configinfo_struct[:default_value]] =
                  num_or_str(conf[__configinfo_struct[:default_value]])
              end
              if ( conf[__configinfo_struct[:current_value]] )
                conf[__configinfo_struct[:current_value]] =
                  num_or_str(conf[__configinfo_struct[:current_value]])
              end

            when /^(#{__boolval_optkeys.join('|')})$/
              if ( __configinfo_struct[:default_value] \
                  && conf[__configinfo_struct[:default_value]] )
                begin
                  conf[__configinfo_struct[:default_value]] =
                    bool(conf[__configinfo_struct[:default_value]])
                rescue
                  conf[__configinfo_struct[:default_value]] = nil
                end
              end
              if ( conf[__configinfo_struct[:current_value]] )
                begin
                  conf[__configinfo_struct[:current_value]] =
                    bool(conf[__configinfo_struct[:current_value]])
                rescue
                  conf[__configinfo_struct[:current_value]] = nil
                end
              end

            when /^(#{__listval_optkeys.join('|')})$/
              if ( __configinfo_struct[:default_value] \
                  && conf[__configinfo_struct[:default_value]] )
                conf[__configinfo_struct[:default_value]] =
                  simplelist(conf[__configinfo_struct[:default_value]])
              end
              if ( conf[__configinfo_struct[:current_value]] )
                conf[__configinfo_struct[:current_value]] =
                  simplelist(conf[__configinfo_struct[:current_value]])
              end

            when /^(#{__numlistval_optkeys.join('|')})$/
              if ( __configinfo_struct[:default_value] \
                  && conf[__configinfo_struct[:default_value]] \
                  && conf[__configinfo_struct[:default_value]] =~ /^[0-9]/ )
                conf[__configinfo_struct[:default_value]] =
                  list(conf[__configinfo_struct[:default_value]])
              end
              if ( conf[__configinfo_struct[:current_value]] \
                  && conf[__configinfo_struct[:current_value]] =~ /^[0-9]/ )
                conf[__configinfo_struct[:current_value]] =
                  list(conf[__configinfo_struct[:current_value]])
              end

            when /^(#{__tkvariable_optkeys.join('|')})$/
              if ( __configinfo_struct[:default_value] \
                  && conf[__configinfo_struct[:default_value]] )
                v = conf[__configinfo_struct[:default_value]]
                if v.empty?
                  conf[__configinfo_struct[:default_value]] = nil
                else
                  conf[__configinfo_struct[:default_value]] = TkVarAccess.new
                end
              end
              if ( conf[__configinfo_struct[:current_value]] )
                v = conf[__configinfo_struct[:current_value]]
                if v.empty?
                  conf[__configinfo_struct[:current_value]] = nil
                else
                  conf[__configinfo_struct[:current_value]] = TkVarAccess.new
                end
              end

            else
              if ( __configinfo_struct[:default_value] \
                  && conf[__configinfo_struct[:default_value]] )
                if conf[__configinfo_struct[:default_value]].index('{')
                  conf[__configinfo_struct[:default_value]] =
                    tk_split_list(conf[__configinfo_struct[:default_value]])
                else
                  conf[__configinfo_struct[:default_value]] =
                    tk_tcl2ruby(conf[__configinfo_struct[:default_value]])
                end
              end
              if conf[__configinfo_struct[:current_value]]
                if conf[__configinfo_struct[:current_value]].index('{')
                  conf[__configinfo_struct[:current_value]] =
                    tk_split_list(conf[__configinfo_struct[:current_value]])
                else
                  conf[__configinfo_struct[:current_value]] =
                    tk_tcl2ruby(conf[__configinfo_struct[:current_value]])
                end
              end
            end

            if ( __configinfo_struct[:alias] \
                && conf.size == __configinfo_struct[:alias] + 1 )
              if conf[__configinfo_struct[:alias]][0] == ?-
                conf[__configinfo_struct[:alias]] =
                  conf[__configinfo_struct[:alias]][1..-1]
              end
              ret[conf[0]] = conf[1]
            else
              ret[conf.shift] = conf
            end
          }

          __font_optkeys.each{|optkey|
            optkey = optkey.to_s
            fontconf = ret[optkey]
            if fontconf.kind_of?(Array)
              ret.delete(optkey)
              ret.delete('latin' << optkey)
              ret.delete('ascii' << optkey)
              ret.delete('kanji' << optkey)
              fontconf[__configinfo_struct[:current_value]] = fontobj(optkey)
              ret[optkey] = fontconf
            end
          }

          __methodcall_optkeys.each{|optkey, method|
            ret[optkey.to_s] = ['', '', '', self.__send__(method)]
          }

          ret
        end
      end
    end
  end
configure(slot, value=None)

[Source]

# File tk/lib/tk.rb, line 2871
  def configure(slot, value=None)
    if slot.kind_of? Hash
      slot = _symbolkey2str(slot)

      __methodcall_optkeys.each{|key, method|
        value = slot.delete(key.to_s)
        self.__send__(method, value) if value
      }

      __ruby2val_optkeys.each{|key, method|
        key = key.to_s
        slot[key] = method.call(slot[key]) if slot.has_key?(key)
      }

      __keyonly_optkeys.each{|defkey, undefkey|
        conf = slot.find{|kk, vv| kk == defkey.to_s}
        if conf
          k, v = conf
          if v
            slot[k] = None
          else
            slot[undefkey.to_s] = None if undefkey
            slot.delete(k)
          end
        end
      }

      if (slot.find{|k, v| k =~ /^(|latin|ascii|kanji)(#{__font_optkeys.join('|')})$/})
        font_configure(slot)
      elsif slot.size > 0
        tk_call(*(__config_cmd.concat(hash_kv(slot))))
      end

    else
      orig_slot = slot
      slot = slot.to_s
      if slot.length == 0
        fail ArgumentError, "Invalid option `#{orig_slot.inspect}'"
      end

      if ( conf = __keyonly_optkeys.find{|k, v| k.to_s == slot} )
        defkey, undefkey = conf
        if value
          tk_call(*(__config_cmd << "-#{defkey}"))
        elsif undefkey
          tk_call(*(__config_cmd << "-#{undefkey}"))
        end
      elsif ( method = _symbolkey2str(__ruby2val_optkeys)[slot] )
        tk_call(*(__config_cmd << "-#{slot}" << method.call(value)))
      elsif ( method = _symbolkey2str(__methodcall_optkeys)[slot] )
        self.__send__(method, value)
      elsif (slot =~ /^(|latin|ascii|kanji)(#{__font_optkeys.join('|')})$/)
        if value == None
          fontobj($2)
        else
          font_configure({slot=>value})
        end
      else
        tk_call(*(__config_cmd << "-#{slot}" << value))
      end
    end
    self
  end
configure_cmd(slot, value)

[Source]

# File tk/lib/tk.rb, line 2935
  def configure_cmd(slot, value)
    configure(slot, install_cmd(value))
  end
current_configinfo(slot = nil)

[Source]

# File tk/lib/tk.rb, line 3672
  def current_configinfo(slot = nil)
    if TkComm::GET_CONFIGINFO_AS_ARRAY
      if slot
        org_slot = slot
        begin
          conf = configinfo(slot)
          if ( ! __configinfo_struct[:alias] \
              || conf.size > __configinfo_struct[:alias] + 1 )
            return {conf[0] => conf[-1]}
          end
          slot = conf[__configinfo_struct[:alias]]
        end while(org_slot != slot)
        fail RuntimeError,
          "there is a configure alias loop about '#{org_slot}'"
      else
        ret = {}
        configinfo().each{|conf|
          if ( ! __configinfo_struct[:alias] \
              || conf.size > __configinfo_struct[:alias] + 1 )
            ret[conf[0]] = conf[-1]
          end
        }
        ret
      end
    else # ! TkComm::GET_CONFIGINFO_AS_ARRAY
      ret = {}
      configinfo(slot).each{|key, conf|
        ret[key] = conf[-1] if conf.kind_of?(Array)
      }
      ret
    end
  end


Module: TkConsole

Module | TkConsole
In: | tk/lib/tk/console.rb

Methods

create eval hide maininterp_eval maininterp_record show title

Included Modules

Tk

Constants

TkCommandNames = ['console'.freeze, 'consoleinterp'.freeze].freeze

Public Class methods

create()

[Source]

# File tk/lib/tk/console.rb, line 12
  def self.create
    TkCore::INTERP._create_console
  end
eval(tcl_script)

[Source]

# File tk/lib/tk/console.rb, line 26
  def self.eval(tcl_script)
    #
    # supports a Tcl script only
    # I have no idea to support a Ruby script seamlessly.
    #
    _fromUTF8(tk_call_without_enc('console', 'eval',
                                  _get_eval_enc_str(tcl_script)))
  end
hide()

[Source]

# File tk/lib/tk/console.rb, line 20
  def self.hide
    tk_call_without_enc('console', 'hide')
  end
maininterp_eval(tcl_script)

[Source]

# File tk/lib/tk/console.rb, line 34
  def self.maininterp_eval(tcl_script)
    #
    # supports a Tcl script only
    # I have no idea to support a Ruby script seamlessly.
    #
    _fromUTF8(tk_call_without_enc('consoleinterp', 'eval',
                                  _get_eval_enc_str(tcl_script)))

  end
maininterp_record(tcl_script)

[Source]

# File tk/lib/tk/console.rb, line 43
  def self.maininterp_record(tcl_script)
    #
    # supports a Tcl script only
    # I have no idea to support a Ruby script seamlessly.
    #
    _fromUTF8(tk_call_without_enc('consoleinterp', 'record',
                                  _get_eval_enc_str(tcl_script)))

  end
show()

[Source]

# File tk/lib/tk/console.rb, line 23
  def self.show
    tk_call_without_enc('console', 'show')
  end
title(str=None)

[Source]

# File tk/lib/tk/console.rb, line 17
  def self.title(str=None)
    tk_call 'console', str
  end


Module: TkCore

Module | TkCore
In: | tk/lib/tk.rb tk/lib/multi-tk.rb

start Tk which depends on MultiTkIp

Methods

_tk_call_to_list_core after after_cancel after_idle appname appsend appsend_deny appsend_displayof call callback callback_break callback_continue chooseColor chooseDirectory do_one_event event_generate getMultipleOpenFile getMultipleSaveFile getOpenFile getSaveFile get_eventloop_tick get_eventloop_weight get_no_event_wait inactive inactive_displayof info inspect ip_eval ip_eval_with_enc ip_eval_without_enc ip_invoke ip_invoke_with_enc ip_invoke_without_enc is_mainloop? load_cmd_on_ip mainloop mainloop_exist? mainloop_thread? mainloop_watchdog messageBox new rb_appsend rb_appsend_displayof reset_inactive reset_inactive_displayof restart scaling scaling_displayof set_eventloop_tick set_eventloop_weight set_no_event_wait tk_call tk_call_to_list tk_call_to_list_with_enc tk_call_to_list_without_enc tk_call_to_simplelist tk_call_to_simplelist_with_enc tk_call_to_simplelist_without_enc tk_call_with_enc tk_call_without_enc to_s windowingsystem

Included Modules

TkComm

Classes and Modules

Module TkCore::INTERP
Class TkCore::Tk_OBJECT_TABLE

Constants

INTERP | = | TclTkIp.new(name, opts)
WIDGET_DESTROY_HOOK | = | '<WIDGET_DESTROY_HOOK>'
EventFlag | = | TclTkLib::EventFlag
INTERP | = | MultiTkIp

Public Class methods

callback(*arg)

[Source]

# File tk/lib/tk.rb, line 1243
  def TkCore.callback(*arg)
    begin
      if TkCore::INTERP.tk_cmd_tbl.kind_of?(Hash)
        #TkCore::INTERP.tk_cmd_tbl[arg.shift].call(*arg)
        normal_ret = false
        ret = catch(:IRB_EXIT) do  # IRB hack
          retval = TkCore::INTERP.tk_cmd_tbl[arg.shift].call(*arg)
          normal_ret = true
          retval
        end
        unless normal_ret
          # catch IRB_EXIT
          exit(ret)
        end
        ret
      end
    rescue SystemExit=>e
      exit(e.status)
    rescue Interrupt=>e
      fail(e)
    rescue Exception => e
      begin
        msg = _toUTF8(e.class.inspect) + ': ' +
              _toUTF8(e.message) + "\n" +
              "\n---< backtrace of Ruby side >-----\n" +
              _toUTF8(e.backtrace.join("\n")) +
              "\n---< backtrace of Tk side >-------"
        msg.instance_variable_set(:@encoding, 'utf-8')
      rescue Exception
        msg = e.class.inspect + ': ' + e.message + "\n" +
              "\n---< backtrace of Ruby side >-----\n" +
              e.backtrace.join("\n") +
              "\n---< backtrace of Tk side >-------"
      end
      # TkCore::INTERP._set_global_var('errorInfo', msg)
      # fail(e)
      fail(e, msg)
    end
  end
new(ip, cmd)

[Source]

# File tk/lib/tk.rb, line 1099
        def initialize(ip, cmd)
          @ip = ip
          @cmd = cmd
        end

Public Instance methods

_tk_call_to_list_core(depth, arg_enc, val_enc, *args)

[Source]

# File tk/lib/tk.rb, line 1690
  def _tk_call_to_list_core(depth, arg_enc, val_enc, *args)
    args = _conv_args([], arg_enc, *args)
    val = _tk_call_core(false, *args)
    if !depth.kind_of?(Integer) || depth == 0
      tk_split_simplelist(val, false, val_enc)
    else
      tk_split_list(val, depth, false, val_enc)
    end
  end
after(ms, cmd=Proc.new)

[Source]

# File tk/lib/tk.rb, line 1325
  def after(ms, cmd=Proc.new)
    crit_bup = Thread.critical
    Thread.critical = true

    myid = _curr_cmd_id
    cmdid = install_cmd(proc{ret = cmd.call;uninstall_cmd(myid); ret})

    Thread.critical = crit_bup

    tk_call_without_enc("after",ms,cmdid)  # return id
#    return
#    if false #defined? Thread
#      Thread.start do
#       ms = Float(ms)/1000
#       ms = 10 if ms == 0
#       sleep ms/1000
#       cmd.call
#      end
#    else
#      cmdid = install_cmd(cmd)
#      tk_call("after",ms,cmdid)
#    end
  end
after_cancel(afterId)

[Source]

# File tk/lib/tk.rb, line 1361
  def after_cancel(afterId)
    tk_call_without_enc('after','cancel',afterId)
  end
after_idle(cmd=Proc.new)

[Source]

# File tk/lib/tk.rb, line 1349
  def after_idle(cmd=Proc.new)
    crit_bup = Thread.critical
    Thread.critical = true

    myid = _curr_cmd_id
    cmdid = install_cmd(proc{ret = cmd.call;uninstall_cmd(myid); ret})

    Thread.critical = crit_bup

    tk_call_without_enc('after','idle',cmdid)
  end
appname(name=None)

[Source]

# File tk/lib/tk.rb, line 1397
  def appname(name=None)
    tk_call('tk', 'appname', name)
  end
appsend(interp, async, *args)

[Source]

# File tk/lib/tk.rb, line 1405
  def appsend(interp, async, *args)
    if $SAFE >= 4
      fail SecurityError, "cannot send Tk commands at level 4"
    elsif $SAFE >= 1 && args.find{|obj| obj.tainted?}
      fail SecurityError, "cannot send tainted Tk commands at level #{$SAFE}"
    end
    if async != true && async != false && async != nil
      args.unshift(async)
      async = false
    end
    if async
      tk_call('send', '-async', '--', interp, *args)
    else
      tk_call('send', '--', interp, *args)
    end
  end
appsend_deny()

[Source]

# File tk/lib/tk.rb, line 1401
  def appsend_deny
    tk_call('rename', 'send', '')
  end
appsend_displayof(interp, win, async, *args)

[Source]

# File tk/lib/tk.rb, line 1440
  def appsend_displayof(interp, win, async, *args)
    if $SAFE >= 4
      fail SecurityError, "cannot send Tk commands at level 4"
    elsif $SAFE >= 1 && args.find{|obj| obj.tainted?}
      fail SecurityError, "cannot send tainted Tk commands at level #{$SAFE}"
    end
    win = '.' if win == nil
    if async != true && async != false && async != nil
      args.unshift(async)
      async = false
    end
    if async
      tk_call('send', '-async', '-displayof', win, '--', interp, *args)
    else
      tk_call('send', '-displayor', win, '--', interp, *args)
    end
  end
call(*args)

[Source]

# File tk/lib/tk.rb, line 1104
        def call(*args)
          @ip.cb_eval(@cmd, *args)
        end
callback_break()

[Source]

# File tk/lib/tk.rb, line 1235
  def callback_break
    fail TkCallbackBreak, "Tk callback returns 'break' status"
  end
callback_continue()

[Source]

# File tk/lib/tk.rb, line 1239
  def callback_continue
    fail TkCallbackContinue, "Tk callback returns 'continue' status"
  end
chooseColor(keys = nil)

[Source]

# File tk/lib/tk.rb, line 1580
  def chooseColor(keys = nil)
    tk_call('tk_chooseColor', *hash_kv(keys))
  end
chooseDirectory(keys = nil)

[Source]

# File tk/lib/tk.rb, line 1584
  def chooseDirectory(keys = nil)
    tk_call('tk_chooseDirectory', *hash_kv(keys))
  end
do_one_event(flag = TclTkLib::EventFlag::ALL)

[Source]

# File tk/lib/tk.rb, line 1506
  def do_one_event(flag = TclTkLib::EventFlag::ALL)
    TclTkLib.do_one_event(flag)
  end
event_generate(win, context, keys=nil)

[Source]

# File tk/lib/tk.rb, line 1547
  def event_generate(win, context, keys=nil)
    #win = win.path if win.kind_of?(TkObject)
    if context.kind_of?(TkEvent::Event)
      context.generate(win, ((keys)? keys: {}))
    elsif keys
      tk_call_without_enc('event', 'generate', win,
                          "<#{tk_event_sequence(context)}>",
                          *hash_kv(keys, true))
    else
      tk_call_without_enc('event', 'generate', win,
                          "<#{tk_event_sequence(context)}>")
    end
    nil
  end
getMultipleOpenFile(keys = nil)

[Source]

# File tk/lib/tk.rb, line 1569
  def getMultipleOpenFile(keys = nil)
    simplelist(tk_call('tk_getOpenFile', '-multiple', '1', *hash_kv(keys)))
  end
getMultipleSaveFile(keys = nil)

[Source]

# File tk/lib/tk.rb, line 1576
  def getMultipleSaveFile(keys = nil)
    simplelist(tk_call('tk_getSaveFile', '-multiple', '1', *hash_kv(keys)))
  end
getOpenFile(keys = nil)

[Source]

# File tk/lib/tk.rb, line 1566
  def getOpenFile(keys = nil)
    tk_call('tk_getOpenFile', *hash_kv(keys))
  end
getSaveFile(keys = nil)

[Source]

# File tk/lib/tk.rb, line 1573
  def getSaveFile(keys = nil)
    tk_call('tk_getSaveFile', *hash_kv(keys))
  end
get_eventloop_tick()

[Source]

# File tk/lib/tk.rb, line 1514
  def get_eventloop_tick()
    TclTkLib.get_eventloop_tick
  end
get_eventloop_weight()

[Source]

# File tk/lib/tk.rb, line 1530
  def get_eventloop_weight()
    TclTkLib.get_eventloop_weight
  end
get_no_event_wait()

[Source]

# File tk/lib/tk.rb, line 1522
  def get_no_event_wait()
    TclTkLib.get_no_eventloop_wait
  end
inactive()

[Source]

# File tk/lib/tk.rb, line 1384
  def inactive
    Integer(tk_call_without_enc('tk', 'inactive'))
  end
inactive_displayof(win)

[Source]

# File tk/lib/tk.rb, line 1387
  def inactive_displayof(win)
    Integer(tk_call_without_enc('tk', 'inactive', '-displayof', win))
  end
info(*args)

[Source]

# File tk/lib/tk.rb, line 1477
  def info(*args)
    tk_call('info', *args)
  end
inspect()

[Source]

# File tk/lib/tk.rb, line 1107
        def inspect
          sprintf("#<cb_entry:%0x>", self.__id__)
        end
ip_eval(cmd_string)

[Source]

# File tk/lib/tk.rb, line 1604
  def ip_eval(cmd_string)
    _ip_eval_core(nil, cmd_string)
  end
ip_eval_with_enc(cmd_string)

[Source]

# File tk/lib/tk.rb, line 1612
  def ip_eval_with_enc(cmd_string)
    _ip_eval_core(true, cmd_string)
  end
ip_eval_without_enc(cmd_string)

[Source]

# File tk/lib/tk.rb, line 1608
  def ip_eval_without_enc(cmd_string)
    _ip_eval_core(false, cmd_string)
  end
ip_invoke(*args)

[Source]

# File tk/lib/tk.rb, line 1632
  def ip_invoke(*args)
    _ip_invoke_core(nil, *args)
  end
ip_invoke_with_enc(*args)

[Source]

# File tk/lib/tk.rb, line 1640
  def ip_invoke_with_enc(*args)
    _ip_invoke_core(true, *args)
  end
ip_invoke_without_enc(*args)

[Source]

# File tk/lib/tk.rb, line 1636
  def ip_invoke_without_enc(*args)
    _ip_invoke_core(false, *args)
  end
is_mainloop?()

[Source]

# File tk/lib/tk.rb, line 1497
  def is_mainloop?
    TclTkLib.mainloop_thread? == true
  end
load_cmd_on_ip(tk_cmd)

[Source]

# File tk/lib/tk.rb, line 1321
  def load_cmd_on_ip(tk_cmd)
    bool(tk_call('auto_load', tk_cmd))
  end
mainloop(check_root = true)

[Source]

# File tk/lib/tk.rb, line 1481
  def mainloop(check_root = true)
    TclTkLib.mainloop(check_root)
  end
mainloop_exist?()

[Source]

# File tk/lib/tk.rb, line 1493
  def mainloop_exist?
    TclTkLib.mainloop_thread? != nil
  end
mainloop_thread?()

[Source]

# File tk/lib/tk.rb, line 1485
  def mainloop_thread?
    # true  : current thread is mainloop
    # nil   : there is no mainloop
    # false : mainloop is running on the other thread
    #         ( At then, it is dangerous to call Tk interpreter directly. )
    TclTkLib.mainloop_thread?
  end
mainloop_watchdog(check_root = true)

[Source]

# File tk/lib/tk.rb, line 1501
  def mainloop_watchdog(check_root = true)
    # watchdog restarts mainloop when mainloop is dead
    TclTkLib.mainloop_watchdog(check_root)
  end
messageBox(keys)

[Source]

# File tk/lib/tk.rb, line 1562
  def messageBox(keys)
    tk_call('tk_messageBox', *hash_kv(keys))
  end
rb_appsend(interp, async, *args)

[Source]

# File tk/lib/tk.rb, line 1422
  def rb_appsend(interp, async, *args)
    if $SAFE >= 4
      fail SecurityError, "cannot send Ruby commands at level 4"
    elsif $SAFE >= 1 && args.find{|obj| obj.tainted?}
      fail SecurityError, "cannot send tainted Ruby commands at level #{$SAFE}"
    end
    if async != true && async != false && async != nil
      args.unshift(async)
      async = false
    end
    #args = args.collect!{|c| _get_eval_string(c).gsub(/[\[\]$"]/, '\\\\\&')}
    args = args.collect!{|c| _get_eval_string(c).gsub(/[\[\]$"\\]/, '\\\\\&')}
    # args.push(').to_s"')
    # appsend(interp, async, 'ruby "(', *args)
    args.push('}.call)"')
    appsend(interp, async, 'ruby "TkComm._get_eval_string(proc{', *args)
  end
rb_appsend_displayof(interp, win, async, *args)

[Source]

# File tk/lib/tk.rb, line 1458
  def rb_appsend_displayof(interp, win, async, *args)
    if $SAFE >= 4
      fail SecurityError, "cannot send Ruby commands at level 4"
    elsif $SAFE >= 1 && args.find{|obj| obj.tainted?}
      fail SecurityError, "cannot send tainted Ruby commands at level #{$SAFE}"
    end
    win = '.' if win == nil
    if async != true && async != false && async != nil
      args.unshift(async)
      async = false
    end
    #args = args.collect!{|c| _get_eval_string(c).gsub(/[\[\]$"]/, '\\\\\&')}
    args = args.collect!{|c| _get_eval_string(c).gsub(/[\[\]$"\\]/, '\\\\\&')}
    # args.push(').to_s"')
    # appsend_displayof(interp, win, async, 'ruby "(', *args)
    args.push('}.call)"')
    appsend(interp, win, async, 'ruby "TkComm._get_eval_string(proc{', *args)
  end
reset_inactive()

[Source]

# File tk/lib/tk.rb, line 1390
  def reset_inactive
    tk_call_without_enc('tk', 'inactive', 'reset')
  end
reset_inactive_displayof(win)

[Source]

# File tk/lib/tk.rb, line 1393
  def reset_inactive_displayof(win)
    tk_call_without_enc('tk', 'inactive', '-displayof', win, 'reset')
  end
restart(app_name = nil, keys = {})

[Source]

# File tk/lib/tk.rb, line 1534
  def restart(app_name = nil, keys = {})
    TkCore::INTERP.init_ip_internal

    tk_call('set', 'argv0', app_name) if app_name
    if keys.kind_of?(Hash)
      # tk_call('set', 'argc', keys.size * 2)
      tk_call('set', 'argv', hash_kv(keys).join(' '))
    end

    INTERP.restart
    nil
  end
scaling(scale=nil)

[Source]

# File tk/lib/tk.rb, line 1369
  def scaling(scale=nil)
    if scale
      tk_call_without_enc('tk', 'scaling', scale)
    else
      Float(number(tk_call_without_enc('tk', 'scaling')))
    end
  end
scaling_displayof(win, scale=nil)

[Source]

# File tk/lib/tk.rb, line 1376
  def scaling_displayof(win, scale=nil)
    if scale
      tk_call_without_enc('tk', 'scaling', '-displayof', win, scale)
    else
      Float(number(tk_call_without_enc('tk', '-displayof', win, 'scaling')))
    end
  end
set_eventloop_tick(timer_tick)

[Source]

# File tk/lib/tk.rb, line 1510
  def set_eventloop_tick(timer_tick)
    TclTkLib.set_eventloop_tick(timer_tick)
  end
set_eventloop_weight(loop_max, no_event_tick)

[Source]

# File tk/lib/tk.rb, line 1526
  def set_eventloop_weight(loop_max, no_event_tick)
    TclTkLib.set_eventloop_weight(loop_max, no_event_tick)
  end
set_no_event_wait(wait)

[Source]

# File tk/lib/tk.rb, line 1518
  def set_no_event_wait(wait)
    TclTkLib.set_no_even_wait(wait)
  end
tk_call(*args)

[Source]

# File tk/lib/tk.rb, line 1678
  def tk_call(*args)
    _tk_call_core(nil, *args)
  end
tk_call_to_list(*args)

private :_tk_call_to_list_core

[Source]

# File tk/lib/tk.rb, line 1701
  def tk_call_to_list(*args)
    _tk_call_to_list_core(-1, nil, true, *args)
  end
tk_call_to_list_with_enc(*args)

[Source]

# File tk/lib/tk.rb, line 1709
  def tk_call_to_list_with_enc(*args)
    _tk_call_to_list_core(-1, true, true, *args)
  end
tk_call_to_list_without_enc(*args)

[Source]

# File tk/lib/tk.rb, line 1705
  def tk_call_to_list_without_enc(*args)
    _tk_call_to_list_core(-1, false, false, *args)
  end
tk_call_to_simplelist(*args)

[Source]

# File tk/lib/tk.rb, line 1713
  def tk_call_to_simplelist(*args)
    _tk_call_to_list_core(0, nil, true, *args)
  end
tk_call_to_simplelist_with_enc(*args)

[Source]

# File tk/lib/tk.rb, line 1721
  def tk_call_to_simplelist_with_enc(*args)
    _tk_call_to_list_core(0, true, true, *args)
  end
tk_call_to_simplelist_without_enc(*args)

[Source]

# File tk/lib/tk.rb, line 1717
  def tk_call_to_simplelist_without_enc(*args)
    _tk_call_to_list_core(0, false, false, *args)
  end
tk_call_with_enc(*args)

[Source]

# File tk/lib/tk.rb, line 1686
  def tk_call_with_enc(*args)
    _tk_call_core(true, *args)
  end
tk_call_without_enc(*args)

[Source]

# File tk/lib/tk.rb, line 1682
  def tk_call_without_enc(*args)
    _tk_call_core(false, *args)
  end
to_s()

Alias for inspect

windowingsystem()

[Source]

# File tk/lib/tk.rb, line 1365
  def windowingsystem
    tk_call_without_enc('tk', 'windowingsystem')
  end


Module: TkCore::INTERP

Module | TkCore::INTERP
In: |

Methods

__getip add_tk_procs cb_entry_class cb_eval create_table get_cb_entry init_ip_env init_ip_internal tk_cmd_tbl tk_object_table tk_windows

Public Class methods

__getip()

[Source]

# File tk/lib/tk.rb, line 1078
    def INTERP.__getip
      self
    end
add_tk_procs(name, args = nil, body = nil)

[Source]

# File tk/lib/tk.rb, line 1161
    def INTERP.add_tk_procs(name, args = nil, body = nil)
      @add_tk_procs << [name, args, body]
      self._invoke('proc', name, args, body) if args && body
    end
cb_entry_class()

[Source]

# File tk/lib/tk.rb, line 1114
    def INTERP.cb_entry_class
      @cb_entry_class
    end
cb_eval(cmd, *args)

[Source]

# File tk/lib/tk.rb, line 1153
    def INTERP.cb_eval(cmd, *args)
      TkUtil._get_eval_string(TkUtil.eval_cmd(cmd, *args))
    end
create_table()

[Source]

# File tk/lib/tk.rb, line 1136
    def INTERP.create_table
      id = @tk_table_list.size
      (tbl = {}).tainted? || tbl.taint
      @tk_table_list << tbl
#      obj = Object.new
#      obj.instance_eval <<-EOD
#        def self.method_missing(m, *args)
#         TkCore::INTERP.tk_object_table(#{id}).send(m, *args)
#        end
#      EOD
#      return obj
      Tk_OBJECT_TABLE.new(id)
    end
get_cb_entry(cmd)

[Source]

# File tk/lib/tk.rb, line 1150
    def INTERP.get_cb_entry(cmd)
      @cb_entry_class.new(__getip, cmd).freeze
    end
init_ip_env(script = Proc.new)

[Source]

# File tk/lib/tk.rb, line 1157
    def INTERP.init_ip_env(script = Proc.new)
      @init_ip_env << script
      script.call(self)
    end
init_ip_internal()

[Source]

# File tk/lib/tk.rb, line 1165
    def INTERP.init_ip_internal
      ip = self
      @init_ip_env.each{|script| script.call(ip)}
      @add_tk_procs.each{|name,args,body| ip._invoke('proc',name,args,body)}
    end
tk_cmd_tbl()

[Source]

# File tk/lib/tk.rb, line 1117
    def INTERP.tk_cmd_tbl
      @tk_cmd_tbl
    end
tk_object_table(id)

[Source]

# File tk/lib/tk.rb, line 1133
    def INTERP.tk_object_table(id)
      @tk_table_list[id]
    end
tk_windows()

[Source]

# File tk/lib/tk.rb, line 1120
    def INTERP.tk_windows
      @tk_windows
    end


Class: TkCore::Tk_OBJECT_TABLE

Class | TkCore::Tk_OBJECT_TABLE
In: | tk/lib/tk.rb
Parent: | Object

Methods

method_missing new

Public Class methods

new(id)

[Source]

# File tk/lib/tk.rb, line 1125
      def initialize(id)
        @id = id
      end

Public Instance methods

method_missing(m, *args, &b)

[Source]

# File tk/lib/tk.rb, line 1128
      def method_missing(m, *args, &b)
        TkCore::INTERP.tk_object_table(@id).__send__(m, *args, &b)
      end


Class: TkDatabaseClass

Class | TkDatabaseClass
In: | tk/lib/tk/bindtag.rb
Parent: | TkBindTag

Methods

inspect new new

Public Class methods

new(name, *args, &b)

[Source]

# File tk/lib/tk/bindtag.rb, line 71
  def initialize(name, *args, &b)
    @id = name
    BTagID_TBL[@id] = self
    bind(*args, &b) if args != []
  end
new(name, *args, &b)

[Source]

# File tk/lib/tk/bindtag.rb, line 66
  def self.new(name, *args, &b)
    return BTagID_TBL[name] if BTagID_TBL[name]
    super(name, *args, &b)
  end

Public Instance methods

inspect()

[Source]

# File tk/lib/tk/bindtag.rb, line 77
  def inspect
    #Kernel.format "#<TkDatabaseClass: %s>", @id
    '#<TkDatabaseClass: ' + @id + '>'
  end


Class: TkDialog

Class | TkDialog
In: | tk/lib/tk/dialog.rb
Parent: | TkDialogObj

TkDialog : with showing at initialize

Methods

new show

Public Class methods

new(*args)

[Source]

# File tk/lib/tk/dialog.rb, line 269
  def initialize(*args)
    super(*args)
    show
  end
show(*args)

[Source]

# File tk/lib/tk/dialog.rb, line 265
  def self.show(*args)
    self.new(*args)
  end


Class: TkDialogObj

Class | TkDialogObj
In: | tk/lib/tk/dialog.rb
Parent: | TkWindow

Methods

name show show value

Constants

TkCommandNames = ['tk_dialog'.freeze].freeze

Public Class methods

show(*args)

[Source]

# File tk/lib/tk/dialog.rb, line 12
  def self.show(*args)
    dlog = self.new(*args)
    dlog.show
    dlog
  end

Public Instance methods

name()

[Source]

# File tk/lib/tk/dialog.rb, line 201
  def name
    (@val)? @buttons[@val]: nil
  end
show()

[Source]

# File tk/lib/tk/dialog.rb, line 165
  def show
    # if @command.kind_of?(Proc)
    if TkComm._callback_entry?(@command)
      @command.call(self)
    end

    if @default_button.kind_of?(String)
      default_button = @buttons.index(@default_button)
    else
      default_button = @default_button
    end
    # default_button = '{}' if default_button == nil
    default_button = '' if default_button == nil
    #Tk.ip_eval('eval {global '+@var.id+';'+@config+
    #          'set '+@var.id+' [tk_dialog '+
    #          @path+" "+@title+" {#{@message}} "+@bitmap+" "+
    #          String(default_button)+" "+@buttons.join(' ')+']}')
    Tk.ip_eval(@config)
    # @val = Tk.ip_eval('tk_dialog ' + @path + ' ' + @title +
    #                 ' {' + @message + '} ' + @bitmap + ' ' +
    #                 String(default_button) + ' ' + @buttons.join(' ')).to_i
    # @val = Tk.ip_eval(self.class::TkCommandNames[0] + ' ' + @path + ' ' +
    #                   @title + ' {' + @message + '} ' + @bitmap + ' ' +
    #                   String(default_button) + ' ' + @buttons.join(' ')).to_i
    @val = Tk.ip_eval(array2tk_list([
                                      self.class::TkCommandNames[0],
                                      @path, @title, @message, @bitmap,
                                      String(default_button)
                                    ].concat(@buttons))).to_i
  end
value()

[Source]

# File tk/lib/tk/dialog.rb, line 196
  def value
    # @var.value.to_i
    @val
  end


Class: TkEntry

Class | TkEntry
In: | tk/lib/tk/entry.rb
Parent: | TkLabel

Methods

[] []= bbox cursor cursor= delete dragto get icursor icursor= index insert invoke_validate mark selection_adjust selection_clear selection_from selection_present selection_range selection_to set validate value value=

Included Modules

X_Scrollable TkValidation

Constants

TkCommandNames | = | ['entry'.freeze].freeze
WidgetClassName | = | 'Entry'.freeze

Public Instance methods

[](*args)

[Source]

# File tk/lib/tk/entry.rb, line 107
  def [](*args)
    self.value[*args]
  end
[]=(*args)

[Source]

# File tk/lib/tk/entry.rb, line 110
  def []=(*args)
    val = args.pop
    str = self.value
    str[*args] = val
    self.value = str
    val
  end
bbox(index)

[Source]

# File tk/lib/tk/entry.rb, line 29
  def bbox(index)
    list(tk_send_without_enc('bbox', index))
  end
cursor()

[Source]

# File tk/lib/tk/entry.rb, line 32
  def cursor
    number(tk_send_without_enc('index', 'insert'))
  end
cursor=(index)

[Source]

# File tk/lib/tk/entry.rb, line 36
  def cursor=(index)
    tk_send_without_enc('icursor', index)
    #self
    index
  end
delete(first, last=None)

[Source]

# File tk/lib/tk/entry.rb, line 49
  def delete(first, last=None)
    tk_send_without_enc('delete', first, last)
    self
  end
dragto(pos)

[Source]

# File tk/lib/tk/entry.rb, line 57
  def dragto(pos)
    tk_send_without_enc('scan', 'dragto', pos)
    self
  end
get()

Alias for value

icursor()

Alias for cursor

icursor=(index)

Alias for cursor=

index(idx)

[Source]

# File tk/lib/tk/entry.rb, line 42
  def index(idx)
    number(tk_send_without_enc('index', idx))
  end
insert(pos,text)

[Source]

# File tk/lib/tk/entry.rb, line 45
  def insert(pos,text)
    tk_send_without_enc('insert', pos, _get_eval_enc_str(text))
    self
  end
invoke_validate()

[Source]

# File tk/lib/tk/entry.rb, line 85
  def invoke_validate
    bool(tk_send_without_enc('validate'))
  end
mark(pos)

[Source]

# File tk/lib/tk/entry.rb, line 53
  def mark(pos)
    tk_send_without_enc('scan', 'mark', pos)
    self
  end
selection_adjust(index)

[Source]

# File tk/lib/tk/entry.rb, line 61
  def selection_adjust(index)
    tk_send_without_enc('selection', 'adjust', index)
    self
  end
selection_clear()

[Source]

# File tk/lib/tk/entry.rb, line 65
  def selection_clear
    tk_send_without_enc('selection', 'clear')
    self
  end
selection_from(index)

[Source]

# File tk/lib/tk/entry.rb, line 69
  def selection_from(index)
    tk_send_without_enc('selection', 'from', index)
    self
  end
selection_present()

[Source]

# File tk/lib/tk/entry.rb, line 73
  def selection_present()
    bool(tk_send_without_enc('selection', 'present'))
  end
selection_range(s, e)

[Source]

# File tk/lib/tk/entry.rb, line 76
  def selection_range(s, e)
    tk_send_without_enc('selection', 'range', s, e)
    self
  end
selection_to(index)

[Source]

# File tk/lib/tk/entry.rb, line 80
  def selection_to(index)
    tk_send_without_enc('selection', 'to', index)
    self
  end
set(val)

Alias for value=

validate(mode = nil)

[Source]

# File tk/lib/tk/entry.rb, line 88
  def validate(mode = nil)
    if mode
      configure 'validate', mode
    else
      invoke_validate
    end
  end
value()

[Source]

# File tk/lib/tk/entry.rb, line 96
  def value
    _fromUTF8(tk_send_without_enc('get'))
  end
value=(val)

[Source]

# File tk/lib/tk/entry.rb, line 99
  def value= (val)
    tk_send_without_enc('delete', 0, 'end')
    tk_send_without_enc('insert', 0, _get_eval_enc_str(val))
    val
  end


Module: TkEvent

Module | TkEvent
In: | tk/lib/tk/event.rb

Methods

generate valid_fields valid_for_generate

Classes and Modules

Class TkEvent::Event

Constants

KEY_TBL | = | [ [ ?#, ?n, :serial ], [ ?a, ?s, :above ], [ ?b, ?n, :num ], [ ?c, ?n, :count ], [ ?d, ?s, :detail ], [ ?f, ?b, :focus ], [ ?h, ?n, :height ], [ ?i, ?s, :win_hex ], [ ?k, ?n, :keycode ], [ ?m, ?s, :mode ], [ ?o, ?b, :override ], [ ?p, ?s, :place ], [ ?s, ?x, :state ], [ ?t, ?n, :time ], [ ?w, ?n, :width ], [ ?x, ?n, :x ], [ ?y, ?n, :y ], [ ?A, ?s, :char ], [ ?B, ?n, :borderwidth ], [ ?D, ?n, :wheel_delta ], [ ?E, ?b, :send_event ], [ ?K, ?s, :keysym ], [ ?N, ?n, :keysym_num ], [ ?P, ?s, :property ], [ ?R, ?s, :rootwin_id ], [ ?S, ?s, :subwindow ], [ ?T, ?n, :type ], [ ?W, ?w, :widget ], [ ?X, ?n, :x_root ], [ ?Y, ?n, :y_root ], nil | [ <’%’ subst-key char>, <proc type char>, <instance var (accessor) name>]
PROC_TBL | = | [ [ ?n, TkComm.method(:num_or_str) ], [ ?s, TkComm.method(:string) ], [ ?b, TkComm.method(:bool) ], [ ?w, TkComm.method(:window) ], [ ?x, proc{|val| begin TkComm::number(val) | [ <proc type char>, <proc/method to convert tcl-str to ruby-obj>]

Public Instance methods

generate(win, modkeys={})

[Source]

# File tk/lib/tk/event.rb, line 249
    def generate(win, modkeys={})
      klass = self.class

      if modkeys.has_key?(:type) || modkeys.has_key?('type')
        modkeys = TkComm._symbolkey2str(modkeys)
        type_id = modkeys.delete('type')
      else
        type_id = self.type
      end

      type_name  = klass.type_name(type_id)
      unless type_name
        fail RuntimeError, "type_id #{type_id} is invalid"
      end

      group_flag = klass.group_flag(type_id)

      opts = valid_for_generate(group_flag)

      modkeys.each{|key, val|
        if val
          opts[key.to_s] = val
        else
          opts.delete(key.to_s)
        end
      }

      if group_flag != Grp::KEY
        Tk.event_generate(win, type_name, opts)
      else
        # If type is KEY event, focus should be set to target widget.
        # If not set, original widget will get the same event.
        # That will make infinite loop.
        w = Tk.tk_call_without_enc('focus')
        begin
          Tk.tk_call_without_enc('focus', win)
          Tk.event_generate(win, type_name, opts)
        ensure
          Tk.tk_call_without_enc('focus', w)
        end
      end
    end
valid_fields(group_flag=nil)

[Source]

# File tk/lib/tk/event.rb, line 215
    def valid_fields(group_flag=nil)
      group_flag = self.class.group_flag(self.type) unless group_flag

      fields = {}
      FIELD_FLAG.each{|key, flag|
        next if (flag & group_flag) == 0
        begin
          val = self.__send__(key)
        rescue
          next
        end
        next if !val || val == '??'
        fields[key] = val
      }

      fields
    end
valid_for_generate(group_flag=nil)

[Source]

# File tk/lib/tk/event.rb, line 233
    def valid_for_generate(group_flag=nil)
      fields = valid_fields(group_flag)

      FIELD_OPERATION.each{|key, cmd|
        next unless fields.has_key?(key)
        val = FIELD_OPERATION[key].call(fields[key])
        if val
          fields[key] = val
        else
          fields.delete(key)
        end
      }

      fields
    end


Class: TkEvent::Event

Class | TkEvent::Event
In: | tk/lib/tk/event.rb
Parent: | TkUtil::CallbackSubst

Methods

group_flag type_id type_name

Classes and Modules

Module TkEvent::Event::Grp
Module TkEvent::Event::StateMask
Module TkEvent::Event::TypeNum

Constants

TYPE_NAME_TBL = Hash.new
TYPE_ID_TBL = Hash.new
TYPE_GROUP_TBL = Hash.new
FIELD_FLAG = { # key => flag 'above' => Grp::CONFIG, 'borderwidth' => (Grp::CREATE|Grp::CONFIG), 'button' => Grp::BUTTON, 'count' => Grp::EXPOSE, 'data' => Grp::VIRTUAL, 'delta' => Grp::MWHEEL, 'detail' => (Grp::FOCUS|Grp::CROSSING), 'focus' => Grp::CROSSING, 'height' => (Grp::EXPOSE|Grp::CONFIG), 'keycode' => Grp::KEY, 'keysym' => Grp::KEY, 'mode' => (Grp::CROSSING|Grp::FOCUS), 'override' => (Grp::CREATE|Grp::MAP|Grp::REPARENT|Grp::CONFIG), 'place' => Grp::CIRC, 'root' => (Grp::KEY_BUTTON_MOTION_VIRTUAL|Grp::CROSSING), 'rootx' => (Grp::KEY_BUTTON_MOTION_VIRTUAL|Grp::CROSSING), 'rooty' => (Grp::KEY_BUTTON_MOTION_VIRTUAL|Grp::CROSSING), 'sendevent' => Grp::ALL, 'serial' => Grp::ALL, 'state' => (Grp::KEY_BUTTON_MOTION_VIRTUAL| Grp::CROSSING|Grp::VISIBILITY), 'subwindow' => (Grp::KEY_BUTTON_MOTION_VIRTUAL|Grp::CROSSING), 'time' => (Grp::KEY_BUTTON_MOTION_VIRTUAL|Grp::CROSSING| Grp::PROP), 'warp' => Grp::KEY_BUTTON_MOTION_VIRTUAL, 'width' => (Grp::EXPOSE|Grp::CREATE|Grp::CONFIG), 'window' => (Grp::CREATE|Grp::UNMAP|Grp::MAP|Grp::REPARENT| Grp::CONFIG|Grp::GRAVITY|Grp::CIRC), 'when' => Grp::ALL, 'x' => (Grp::KEY_BUTTON_MOTION_VIRTUAL|Grp::CROSSING| Grp::EXPOSE|Grp::CREATE|Grp::CONFIG|Grp::GRAVITY| Grp::REPARENT), 'y' => (Grp::KEY_BUTTON_MOTION_VIRTUAL|Grp::CROSSING| Grp::EXPOSE|Grp::CREATE|Grp::CONFIG|Grp::GRAVITY| Grp::REPARENT), }
FIELD_OPERATION = { 'root' => proc{|val| begin Tk.tk_call_without_enc('winfo', 'pathname', val)

Public Class methods

group_flag(id)

[Source]

# File tk/lib/tk/event.rb, line 119
    def self.group_flag(id)
      TYPE_GROUP_TBL[id] || 0
    end
type_id(name)

[Source]

# File tk/lib/tk/event.rb, line 111
    def self.type_id(name)
      TYPE_NAME_TBL[name.to_s]
    end
type_name(id)

[Source]

# File tk/lib/tk/event.rb, line 115
    def self.type_name(id)
      TYPE_ID_TBL[id] && TYPE_ID_TBL[id][0]
    end


Module: TkEvent::Event::Grp

Module | TkEvent::Event::Grp
In: | tk/lib/tk/event.rb

Constants

KEY | = | 0x1
BUTTON | = | 0x2
MOTION | = | 0x4
CROSSING | = | 0x8
FOCUS | = | 0x10
EXPOSE | = | 0x20
VISIBILITY | = | 0x40
CREATE | = | 0x80
DESTROY | = | 0x100
UNMAP | = | 0x200
MAP | = | 0x400
REPARENT | = | 0x800
CONFIG | = | 0x1000
GRAVITY | = | 0x2000
CIRC | = | 0x4000
PROP | = | 0x8000
COLORMAP | = | 0x10000
VIRTUAL | = | 0x20000
ACTIVATE | = | 0x40000
MAPREQ | = | 0x80000
CONFIGREQ | = | 0x100000
RESIZEREQ | = | 0x200000
CIRCREQ | = | 0x400000
MWHEEL | = | 0x10000000
ALL | = | 0xFFFFFFFF
KEY_BUTTON_MOTION_VIRTUAL | = | (KEY|MWHEEL|BUTTON|MOTION|VIRTUAL)
KEY_BUTTON_MOTION_CROSSING | = | (KEY|MWHEEL|BUTTON|MOTION|CROSSING|VIRTUAL)


Module: TkEvent::Event::StateMask

Module | TkEvent::Event::StateMask
In: | tk/lib/tk/event.rb

Constants

ShiftMask | = | (1<<0)
LockMask | = | (1<<1)
ControlMask | = | (1<<2)
Mod1Mask | = | (1<<3)
Mod2Mask | = | (1<<4)
Mod3Mask | = | (1<<5)
Mod4Mask | = | (1<<6)
Mod5Mask | = | (1<<7)
Button1Mask | = | (1<<8)
Button2Mask | = | (1<<9)
Button3Mask | = | (1<<10)
Button4Mask | = | (1<<11)
Button5Mask | = | (1<<12)
AnyModifier | = | (1<<15)
META_MASK | = | (AnyModifier<<1)
ALT_MASK | = | (AnyModifier<<2)
EXTENDED_MASK | = | (AnyModifier<<3)
CommandMask | = | Mod1Mask
OptionMask | = | Mod2Mask


Module: TkEvent::Event::TypeNum

Module | TkEvent::Event::TypeNum
In: | tk/lib/tk/event.rb


Class: TkFont

Class | TkFont
In: | tk/lib/tk/font.rb
Parent: | Object

Methods

[] []= actual actual actual_displayof actual_displayof ascii_actual ascii_actual_displayof ascii_configinfo ascii_configure ascii_font ascii_metrics ascii_replace asciifont call_font_configure clone configinfo configinfo configure configure create_asciifont create_compoundfont create_compoundfont create_compoundfont create_copy create_kanjifont create_kanjifont create_kanjifont create_latinfont create_latinfont create_latinfont current_configinfo current_configinfo delete dup failsafe families font font_id get_obj id init_widget_font inspect kanji_actual kanji_actual_displayof kanji_configinfo kanji_configure kanji_font kanji_font_id kanji_metrics kanji_metrics_displayof kanji_replace kanjifont latin_actual latin_actual_displayof latin_configinfo latin_configure latin_font latin_font_id latin_metrics latin_metrics_displayof latin_replace latinfont measure measure measure_displayof measure_displayof method_missing metrics metrics metrics_displayof metrics_displayof names new replace reset_pointadjust to_eval used used_on

Included Modules

Tk TkFont::CoreMethods

Classes and Modules

Module TkFont::CoreMethods
Class TkFont::DescendantFont

Constants

TkCommandNames | = | ['font'.freeze].freeze
Tk_FontID | = | ["@font".freeze, "00000".taint].freeze
Tk_FontNameTBL | = | TkCore::INTERP.create_table
Tk_FontUseTBL | = | TkCore::INTERP.create_table
OptionType | = | Hash.new(?s) | option_type : default => string
MetricType | = | Hash.new(?n) | metric_type : default => num_or_str
DEFAULT_LATIN_FONT_NAME | = | 'a14'.freeze
DEFAULT_KANJI_FONT_NAME | = | 'k14'.freeze
DEFAULT_LATIN_FONT_NAME | = | ltn.freeze
DEFAULT_KANJI_FONT_NAME | = | knj.freeze
DEFAULT_LATIN_FONT_NAME | = | 'Helvetica'.freeze
DEFAULT_KANJI_FONT_NAME | = | 'mincho'.freeze

Public Class methods

actual(fnt, option=nil)

class methods

[Source]

# File tk/lib/tk/font.rb, line 166
  def TkFont.actual(fnt, option=nil)
    fnt = '{}' if fnt == ''
    if fnt.kind_of?(TkFont)
     fnt.actual(option)
    else
      actual_core(fnt, nil, option)
    end
  end
actual_displayof(fnt, win, option=nil)

[Source]

# File tk/lib/tk/font.rb, line 175
  def TkFont.actual_displayof(fnt, win, option=nil)
    fnt = '{}' if fnt == ''
    if fnt.kind_of?(TkFont)
     fnt.actual_displayof(win, option)
    else
      win = '.' unless win
      actual_core(fnt, win, option)
    end
  end
configinfo(fnt, slot=nil)

[Source]

# File tk/lib/tk/font.rb, line 194
  def TkFont.configinfo(fnt, slot=nil)
    if fnt.kind_of?(TkFont)
      fnt.configinfo(fnt, slot)
    else
      configinfo_core(fnt, slot)
    end
  end
configure(fnt, slot, value=None)

[Source]

# File tk/lib/tk/font.rb, line 185
  def TkFont.configure(fnt, slot, value=None)
    if fnt.kind_of?(TkFont)
      fnt.configure(fnt, slot, value)
    else
      configure_core(fnt, slot, value)
    end
    fnt
  end
create_copy(font)

[Source]

# File tk/lib/tk/font.rb, line 276
  def TkFont.create_copy(font)
    fail 'source-font must be a TkFont object' unless font.kind_of? TkFont
    if TkComm::GET_CONFIGINFOwoRES_AS_ARRAY
      keys = {}
      font.configinfo.each{|key,value| keys[key] = value }
      TkFont.new(font.latin_font_id, font.kanji_font_id, keys)
    else # ! TkComm::GET_CONFIGINFOwoRES_AS_ARRAY
      TkFont.new(font.latin_font_id, font.kanji_font_id, font.configinfo)
    end
  end
current_configinfo(fnt, slot=nil)

[Source]

# File tk/lib/tk/font.rb, line 202
  def TkFont.current_configinfo(fnt, slot=nil)
    if fnt.kind_of?(TkFont)
      fnt.current_configinfo(fnt, slot)
    else
      current_configinfo_core(fnt, slot)
    end
  end
failsafe(font)

[Source]

# File tk/lib/tk/font.rb, line 380
  def TkFont.failsafe(font)
    begin
      if /^8\.*/ === Tk::TK_VERSION  && JAPANIZED_TK
        tk_call('font', 'failsafe', font)
      end
    rescue
    end
  end
families(win=nil)

[Source]

# File tk/lib/tk/font.rb, line 248
  def TkFont.families(win=nil)
    case (Tk::TK_VERSION)
    when /^4\.*/
      ['fixed']

    when /^8\.*/
      if win
        tk_split_simplelist(tk_call('font', 'families', '-displayof', win))
      else
        tk_split_simplelist(tk_call('font', 'families'))
      end
    end
  end
get_obj(name)

[Source]

# File tk/lib/tk/font.rb, line 287
  def TkFont.get_obj(name)
    if name =~ /^(@font[0-9]+)(|c|l|k)$/
      Tk_FontNameTBL[$1]
    else
      nil
    end
  end
init_widget_font(pathname, *args)

[Source]

# File tk/lib/tk/font.rb, line 295
  def TkFont.init_widget_font(pathname, *args)
    win, tag, key = pathname.split(';')
    key = 'font' if key == nil || key == ''
    path = [win, tag, key].join(';')

    case (Tk::TK_VERSION)
    when /^4\.*/
      regexp = /^-(|kanji)#{key} /

      conf_list = tk_split_simplelist(tk_call(*args)).
        find_all{|prop| prop =~ regexp}.
        collect{|prop| tk_split_simplelist(prop)}

      if conf_list.size == 0
        raise RuntimeError, "the widget may not support 'font' option"
      end

      args << {}

      ltn_key = "-#{key}"
      knj_key = "-kanji#{key}"

      ltn_info = conf_list.find{|conf| conf[0] == ltn_key}
      ltn = ltn_info[-1]
      ltn = nil if ltn == [] || ltn == ""

      knj_info = conf_list.find{|conf| conf[0] == knj_key}
      knj = knj_info[-1]
      knj = nil if knj == [] || knj == ""

      TkFont.new(ltn, knj).call_font_configure([path, key], *args)

    when /^8\.*/
      regexp = /^-#{key} /

      conf_list = tk_split_simplelist(tk_call(*args)).
        find_all{|prop| prop =~ regexp}.
        collect{|prop| tk_split_simplelist(prop)}

      if conf_list.size == 0
        raise RuntimeError, "the widget may not support 'font' option"
      end

      args << {}

      optkey = "-#{key}"

      info = conf_list.find{|conf| conf[0] == optkey}
      fnt = info[-1]
      fnt = nil if fnt == [] || fnt == ""

      unless fnt
        # create dummy
        # TkFont.new(nil, nil).call_font_configure([path, key], *args)
        dummy_fnt = TkFont.allocate
        dummy_fnt.instance_eval{ init_dummy_fontobj() }
        dummy_fnt
      else
        begin
          compound = tk_split_simplelist(
              Hash[*tk_split_simplelist(tk_call('font', 'configure',
                                                fnt))].collect{|k,v|
                [k[1..-1], v]
              }.assoc('compound')[1])
        rescue
          compound = []
        end
        if compound == []
          TkFont.new(fnt).call_font_configure([path, key], *args)
        else
          TkFont.new(compound[0],
                     compound[1]).call_font_configure([path, key], *args)
        end
      end
    end
  end
measure(fnt, text)

[Source]

# File tk/lib/tk/font.rb, line 210
  def TkFont.measure(fnt, text)
    fnt = '{}' if fnt == ''
    if fnt.kind_of?(TkFont)
      fnt.measure(text)
    else
      measure_core(fnt, nil, text)
    end
  end
measure_displayof(fnt, win, text)

[Source]

# File tk/lib/tk/font.rb, line 219
  def TkFont.measure_displayof(fnt, win, text)
    fnt = '{}' if fnt == ''
    if fnt.kind_of?(TkFont)
      fnt.measure_displayof(win, text)
    else
      win = '.' unless win
      measure_core(fnt, win, text)
    end
  end
metrics(fnt, option=nil)

[Source]

# File tk/lib/tk/font.rb, line 229
  def TkFont.metrics(fnt, option=nil)
    fnt = '{}' if fnt == ''
    if fnt.kind_of?(TkFont)
      fnt.metrics(option)
    else
      metrics_core(fnt, nil, option)
    end
  end
metrics_displayof(fnt, win, option=nil)

[Source]

# File tk/lib/tk/font.rb, line 238
  def TkFont.metrics_displayof(fnt, win, option=nil)
    fnt = '{}' if fnt == ''
    if fnt.kind_of?(TkFont)
      font.metrics_displayof(win, option=nil)
    else
      win = '.' unless win
      metrics_core(fnt, win, option)
    end
  end
names()

[Source]

# File tk/lib/tk/font.rb, line 262
  def TkFont.names
    case (Tk::TK_VERSION)
    when /^4\.*/
      r = ['fixed']
      r += ['a14', 'k14'] if JAPANIZED_TK
      Tk_FontNameTBL.each_value{|obj| r.push(obj)}
      r | []

    when /^8\.*/
      tk_split_simplelist(tk_call('font', 'names'))

    end
  end
new(ltn=nil, knj=nil, keys=nil)

[Source]

# File tk/lib/tk/font.rb, line 435
  def initialize(ltn=nil, knj=nil, keys=nil)
    ltn = '{}' if ltn == ''
    knj = '{}' if knj == ''

    # @id = Tk_FontID.join('')
    @id = Tk_FontID.join(TkCore::INTERP._ip_id_)
    Tk_FontID[1].succ!
    Tk_FontNameTBL[@id] = self

    @latin_desscendant = nil
    @kanji_desscendant = nil

    if knj.kind_of?(Hash) && !keys
      keys = knj
      knj = nil
    end

    # compound font check
    if Tk::TK_VERSION == '8.0' && JAPANIZED_TK
      begin
        compound = tk_split_simplelist(tk_call('font', 'configure',
                                               ltn, '-compound'))
        if knj == nil
          if compound != []
            ltn, knj = compound
          end
        else
          if compound != []
            ltn = compound[0]
          end
          compound = tk_split_simplelist(tk_call('font', 'configure',
                                                 knj, '-compound'))
          if compound != []
            knj = compound[1]
          end
        end
      rescue
      end
    end

    if ltn
      if JAPANIZED_TK && !knj
        if Tk::TK_VERSION =~ /^4.*/
          knj = DEFAULT_KANJI_FONT_NAME
        else
          knj = ltn
        end
      end
    else
      ltn = DEFAULT_LATIN_FONT_NAME
      knj = DEFAULT_KANJI_FONT_NAME if JAPANIZED_TK && !knj
    end

    create_compoundfont(ltn, knj, keys)
  end
used_on(path=nil)

[Source]

# File tk/lib/tk/font.rb, line 372
  def TkFont.used_on(path=nil)
    if path
      Tk_FontUseTBL[path]
    else
      Tk_FontUseTBL.values | []
    end
  end

Public Instance methods

[](slot)

[Source]

# File tk/lib/tk/font.rb, line 1011
  def [](slot)
    configinfo slot
  end
[]=(slot, val)

[Source]

# File tk/lib/tk/font.rb, line 1015
  def []=(slot, val)
    configure slot, val
    val
  end
actual(option=nil)

[Source]

# File tk/lib/tk/font.rb, line 974
  def actual(option=nil)
    actual_core(@compoundfont, nil, option)
  end
actual_displayof(win, option=nil)

[Source]

# File tk/lib/tk/font.rb, line 978
  def actual_displayof(win, option=nil)
    win = '.' unless win
    actual_core(@compoundfont, win, option)
  end
ascii_actual(option=nil)

Alias for latin_actual

ascii_actual_displayof(win, option=nil)

Alias for latin_actual_displayof

ascii_configinfo(slot=nil)

Alias for latin_configinfo

ascii_configure(slot, value=None)

Alias for latin_configure

ascii_font()

Alias for latin_font

ascii_metrics(option=nil)

Alias for latin_metrics

ascii_replace(ltn)

Alias for latin_replace

asciifont()

Alias for latinfont

call_font_configure(path, *args)

[Source]

# File tk/lib/tk/font.rb, line 856
  def call_font_configure(path, *args)
    if path.kind_of?(Array)
      # [path, optkey]
      win, tag = path[0].split(';')
      optkey = path[1].to_s
    else
      win, tag, optkey = path.split(';')
    end

    fontslot = _symbolkey2str(@fontslot)
    if optkey && optkey != ""
      ltn = fontslot.delete('font')
      knj = fontslot.delete('kanjifont')
      fontslot[optkey] = ltn if ltn
      fontslot["kanji#{optkey}"] = knj if knj
    end

    keys = _symbolkey2str(args.pop).update(fontslot)
    args.concat(hash_kv(keys))
    tk_call(*args)
    Tk_FontUseTBL[[win, tag, optkey].join(';')] = self
    self
  end
clone()

[Source]

# File tk/lib/tk/font.rb, line 1202
  def clone
    TkFont.new(self)
  end
configinfo(slot=nil)

[Source]

# File tk/lib/tk/font.rb, line 1025
  def configinfo(slot=nil)
    configinfo_core(@compoundfont, slot)
  end
configure(slot, value=None)

[Source]

# File tk/lib/tk/font.rb, line 1020
  def configure(slot, value=None)
    configure_core(@compoundfont, slot, value)
    self
  end
create_asciifont(font)

Alias for create_latinfont

create_compoundfont(ltn, knj, keys)

Alias for create_compoundfont_tk8x

create_compoundfont(ltn, knj, keys)

Alias for create_compoundfont_tk4x

create_compoundfont(ltn, knj, keys)

Alias for create_compoundfont_tk8x

create_kanjifont(font)

Alias for create_kanjifont_tk8x

create_kanjifont(font)

Alias for create_kanjifont_tk4x

create_kanjifont(font)

Alias for create_kanjifont_tk8x

create_latinfont(font)

Alias for create_latinfont_tk8x

create_latinfont(font)

Alias for create_latinfont_tk8x

create_latinfont(font)

Alias for create_latinfont_tk4x

current_configinfo(slot=nil)

[Source]

# File tk/lib/tk/font.rb, line 1029
  def current_configinfo(slot=nil)
    current_configinfo_core(@compoundfont, slot)
  end
delete()

[Source]

# File tk/lib/tk/font.rb, line 1033
  def delete
    delete_core
  end
dup()

[Source]

# File tk/lib/tk/font.rb, line 1199
  def dup
    TkFont.new(self)
  end
font()

[Source]

# File tk/lib/tk/font.rb, line 941
  def font
    @compoundfont
  end
font_id()

Alias for font

id()

[Source]

# File tk/lib/tk/font.rb, line 933
  def id
    @id
  end
inspect()

[Source]

# File tk/lib/tk/font.rb, line 830
  def inspect
    sprintf("#<%s:%0x:%s>", self.class.inspect, self.__id__, @compoundfont)
  end
kanji_actual(option=nil)

[Source]

# File tk/lib/tk/font.rb, line 992
  def kanji_actual(option=nil)
    #if JAPANIZED_TK
    if @kanjifont != ""
      actual_core(@kanjifont, nil, option)
    else
      actual_core_tk4x(nil, nil, option)
    end
  end
kanji_actual_displayof(win, option=nil)

[Source]

# File tk/lib/tk/font.rb, line 1001
  def kanji_actual_displayof(win, option=nil)
    #if JAPANIZED_TK
    if @kanjifont != ""
      win = '.' unless win
      actual_core(@kanjifont, win, option)
    else
      actual_core_tk4x(nil, win, option)
    end
  end
kanji_configinfo(slot=nil)

[Source]

# File tk/lib/tk/font.rb, line 1066
  def kanji_configinfo(slot=nil)
    #if JAPANIZED_TK
    if @kanjifont != ""
      configinfo_core(@kanjifont, slot)
    else
      #[]
      configinfo(slot)
    end
  end
kanji_configure(slot, value=None)

[Source]

# File tk/lib/tk/font.rb, line 1054
  def kanji_configure(slot, value=None)
    #if JAPANIZED_TK
    if @kanjifont != ""
      configure_core(@kanjifont, slot, value)
      configure('size'=>configinfo('size')) # to reflect new configuration
    else
      #""
      configure(slot, value)
    end
    self
  end
kanji_font()

[Source]

# File tk/lib/tk/font.rb, line 964
  def kanji_font
    # @kanjifont
    if @kanji_descendant
      @kanji_descendant
    else
      @kanji_descendant = DescendantFont.new(self, 'kanji')
    end
  end
kanji_font_id()

[Source]

# File tk/lib/tk/font.rb, line 960
  def kanji_font_id
    @kanjifont
  end
kanji_metrics(option=nil)

[Source]

# File tk/lib/tk/font.rb, line 1122
  def kanji_metrics(option=nil)
    if JAPANIZED_TK
      metrics_core(@kanjifont, nil, option)
    else
      metrics_core_tk4x(nil, nil, option)
    end
  end
kanji_metrics_displayof(win, option=nil)

[Source]

# File tk/lib/tk/font.rb, line 1130
  def kanji_metrics_displayof(win, option=nil)
    if JAPANIZED_TK
      win = '.' unless win
      metrics_core(@kanjifont, win, option)
    else
      metrics_core_tk4x(nil, win, option)
    end
  end
kanji_replace(knj)

[Source]

# File tk/lib/tk/font.rb, line 1089
  def kanji_replace(knj)
    kanji_replace_core(knj)
    reset_pointadjust
    self
  end
kanjifont()

Alias for kanji_font

latin_actual(option=nil)

[Source]

# File tk/lib/tk/font.rb, line 983
  def latin_actual(option=nil)
    actual_core(@latinfont, nil, option)
  end
latin_actual_displayof(win, option=nil)

[Source]

# File tk/lib/tk/font.rb, line 987
  def latin_actual_displayof(win, option=nil)
    win = '.' unless win
    actual_core(@latinfont, win, option)
  end
latin_configinfo(slot=nil)

[Source]

# File tk/lib/tk/font.rb, line 1046
  def latin_configinfo(slot=nil)
    if JAPANIZED_TK
      configinfo_core(@latinfont, slot)
    else
      configinfo(slot)
    end
  end
latin_configure(slot, value=None)

[Source]

# File tk/lib/tk/font.rb, line 1037
  def latin_configure(slot, value=None)
    if JAPANIZED_TK
      configure_core(@latinfont, slot, value)
    else
      configure(slot, value)
    end
    self
  end
latin_font()

[Source]

# File tk/lib/tk/font.rb, line 950
  def latin_font
    # @latinfont
    if @latin_descendant
      @latin_descendant
    else
      @latin_descendant = DescendantFont.new(self, 'latin')
    end
  end
latin_font_id()

[Source]

# File tk/lib/tk/font.rb, line 946
  def latin_font_id
    @latinfont
  end
latin_metrics(option=nil)

[Source]

# File tk/lib/tk/font.rb, line 1113
  def latin_metrics(option=nil)
    metrics_core(@latinfont, nil, option)
  end
latin_metrics_displayof(win, option=nil)

[Source]

# File tk/lib/tk/font.rb, line 1117
  def latin_metrics_displayof(win, option=nil)
    win = '.' unless win
    metrics_core(@latinfont, win, option)
  end
latin_replace(ltn)

[Source]

# File tk/lib/tk/font.rb, line 1083
  def latin_replace(ltn)
    latin_replace_core(ltn)
    reset_pointadjust
    self
  end
latinfont()

Alias for latin_font

measure(text)

[Source]

# File tk/lib/tk/font.rb, line 1095
  def measure(text)
    measure_core(@compoundfont, nil, text)
  end
measure_displayof(win, text)

[Source]

# File tk/lib/tk/font.rb, line 1099
  def measure_displayof(win, text)
    win = '.' unless win
    measure_core(@compoundfont, win, text)
  end
method_missing(id, *args)

[Source]

# File tk/lib/tk/font.rb, line 834
  def method_missing(id, *args)
    name = id.id2name
    case args.length
    when 1
      if name[-1] == ?=
        configure name[0..-2], args[0]
        args[0]
      else
        configure name, args[0]
        self
      end
    when 0
      begin
        configinfo name
      rescue
        fail NameError, "undefined local variable or method `#{name}' for #{self.to_s}", error_at
      end
    else
      fail NameError, "undefined method `#{name}' for #{self.to_s}", error_at
    end
  end
metrics(option=nil)

[Source]

# File tk/lib/tk/font.rb, line 1104
  def metrics(option=nil)
    metrics_core(@compoundfont, nil, option)
  end
metrics_displayof(win, option=nil)

[Source]

# File tk/lib/tk/font.rb, line 1108
  def metrics_displayof(win, option=nil)
    win = '.' unless win
    metrics_core(@compoundfont, win, option)
  end
replace(ltn, knj=None)

[Source]

# File tk/lib/tk/font.rb, line 1076
  def replace(ltn, knj=None)
    knj = ltn if knj == None
    latin_replace(ltn)
    kanji_replace(knj)
    self
  end
reset_pointadjust()

[Source]

# File tk/lib/tk/font.rb, line 1139
  def reset_pointadjust
    begin
      if /^8\.*/ === Tk::TK_VERSION  && JAPANIZED_TK
        configure('pointadjust' => latin_actual.assoc('size')[1].to_f /
                                      kanji_actual.assoc('size')[1].to_f )
      end
    rescue
    end
    self
  end
to_eval()

[Source]

# File tk/lib/tk/font.rb, line 937
  def to_eval
    font
  end
used()

[Source]

# File tk/lib/tk/font.rb, line 880
  def used
    ret = []
    Tk_FontUseTBL.each{|key,value|
      next unless self == value
      if key.include?(';')
        win, tag, optkey = key.split(';')
        winobj = tk_tcl2ruby(win)
        if winobj.kind_of? TkText
          if optkey
            ret.push([winobj, winobj.tagid2obj(tag), optkey])
          else
            ret.push([winobj, winobj.tagid2obj(tag)])
          end
        elsif winobj.kind_of? TkCanvas
          if (tagobj = TkcTag.id2obj(winobj, tag)).kind_of? TkcTag
            if optkey
              ret.push([winobj, tagobj, optkey])
            else
              ret.push([winobj, tagobj])
            end
          elsif (tagobj = TkcItem.id2obj(winobj, tag)).kind_of? TkcItem
            if optkey
              ret.push([winobj, tagobj, optkey])
            else
              ret.push([winobj, tagobj])
            end
          else
            if optkey
              ret.push([winobj, tag, optkey])
            else
              ret.push([winobj, tag])
            end
          end
        elsif winobj.kind_of? TkMenu
          if optkey
            ret.push([winobj, tag, optkey])
          else
            ret.push([winobj, tag])
          end
        else
          if optkey
            ret.push([win, tag, optkey])
          else
            ret.push([win, tag])
          end
        end
      else
        ret.push(tk_tcl2ruby(key))
      end
    }
    ret
  end


Module: TkFont::CoreMethods

Module | TkFont::CoreMethods
In: | tk/lib/tk/font.rb

Included Modules

Tk


Class: TkFont::DescendantFont

Class | TkFont::DescendantFont
In: | tk/lib/tk/font.rb
Parent: | Object

Methods

[] []= clone dup font method_missing new to_eval

Public Class methods

new(compound, type)

[Source]

# File tk/lib/tk/font.rb, line 120
    def initialize(compound, type)
      unless compound.kind_of?(TkFont)
        fail ArgumentError, "a TkFont object is expected for the 1st argument"
      end
      @compound = compound
      case type
      when 'kanji', 'latin', 'ascii'
        @type = type
      when :kanji, :latin, :ascii
        @type = type.to_s
      else
        fail ArgumentError, "unknown type '#{type}'"
      end
    end

Public Instance methods

[](slot)

[Source]

# File tk/lib/tk/font.rb, line 149
    def [](slot)
      @compound.__send__(@type + '_configinfo', slot)
    end
[]=(slot, value)

[Source]

# File tk/lib/tk/font.rb, line 152
    def []=(slot, value)
      @compound.__send__(@type + '_configure', slot, value)
      value
    end
clone()

[Source]

# File tk/lib/tk/font.rb, line 138
    def clone
      fail RuntimeError, "cannot clone a descendant font"
    end
dup()

[Source]

# File tk/lib/tk/font.rb, line 135
    def dup
      fail RuntimeError, "cannot dupulicate a descendant font"
    end
font()

[Source]

# File tk/lib/tk/font.rb, line 145
    def font
      @compound.__send__(@type + '_font_id')
    end
method_missing(id, *args)

[Source]

# File tk/lib/tk/font.rb, line 157
    def method_missing(id, *args)
      @compound.__send__(@type + '_' + id.id2name, *args)
    end
to_eval()

[Source]

# File tk/lib/tk/font.rb, line 142
    def to_eval
      @compound.__send__(@type + '_font_id')
    end


Class: TkFrame

Class | TkFrame
In: | tk/lib/tk/frame.rb
Parent: | TkWindow

Methods

bind bind_append bind_remove bindinfo database_class database_classname database_classname new

Constants

TkCommandNames | = | ['frame'.freeze].freeze
WidgetClassName | = | 'Frame'.freeze

Public Class methods

bind(*args, &b)

[Source]

# File tk/lib/tk/frame.rb, line 100
  def self.bind(*args, &b)
    if self == WidgetClassNames[WidgetClassName] || self.name == ''
      super(*args, &b)
    else
      TkDatabaseClass.new(self.name).bind(*args, &b)
    end
  end
bind_append(*args, &b)

[Source]

# File tk/lib/tk/frame.rb, line 107
  def self.bind_append(*args, &b)
    if self == WidgetClassNames[WidgetClassName] || self.name == ''
      super(*args, &b)
    else
      TkDatabaseClass.new(self.name).bind_append(*args, &b)
    end
  end
bind_remove(*args)

[Source]

# File tk/lib/tk/frame.rb, line 114
  def self.bind_remove(*args)
    if self == WidgetClassNames[WidgetClassName] || self.name == ''
      super(*args)
    else
      TkDatabaseClass.new(self.name).bind_remove(*args)
    end
  end
bindinfo(*args)

[Source]

# File tk/lib/tk/frame.rb, line 121
  def self.bindinfo(*args)
    if self == WidgetClassNames[WidgetClassName] || self.name == ''
      super(*args)
    else
      TkDatabaseClass.new(self.name).bindinfo(*args)
    end
  end
database_class()

[Source]

# File tk/lib/tk/frame.rb, line 89
  def self.database_class
    if self == WidgetClassNames[WidgetClassName] || self.name == ''
      self
    else
      TkDatabaseClass.new(self.name)
    end
  end
database_classname()

[Source]

# File tk/lib/tk/frame.rb, line 96
  def self.database_classname
    self.database_class.name
  end
new(parent=nil, keys=nil)

[Source]

# File tk/lib/tk/frame.rb, line 38
  def initialize(parent=nil, keys=nil)
    my_class_name = nil
    if self.class < WidgetClassNames[self.class::WidgetClassName]
      my_class_name = self.class.name
      my_class_name = nil if my_class_name == ''
    end
    if parent.kind_of? Hash
      keys = _symbolkey2str(parent)
    else
      if keys
        keys = _symbolkey2str(keys)
        keys['parent'] = parent
      else
        keys = {'parent'=>parent}
      end
    end
    if keys.key?('classname')
       keys['class'] = keys.delete('classname')
    end
    @classname = keys['class']
    @colormap  = keys['colormap']
    @container = keys['container']
    @visual    = keys['visual']
    if !@classname && my_class_name
      keys['class'] = @classname = my_class_name
    end
    if @classname.kind_of? TkBindTag
      @db_class = @classname
      @classname = @classname.id
    elsif @classname
      @db_class = TkDatabaseClass.new(@classname)
    else
      @db_class = self.class
      @classname = @db_class::WidgetClassName
    end
    super(keys)
  end

Public Instance methods

database_classname()

def create_self(keys)

  if keys and keys != None
    tk_call_without_enc('frame', @path, *hash_kv(keys))
  else
    tk_call_without_enc( 'frame', @path)
  end

end private :create_self

[Source]

# File tk/lib/tk/frame.rb, line 85
  def database_classname
    @classname
  end


Module: TkGrid

Module | TkGrid
In: | tk/lib/tk/grid.rb

Methods

add anchor bbox columnconfiginfo columnconfigure configure forget grid info location propagate remove rowconfiginfo rowconfigure size slaves

Included Modules

Tk

Constants

TkCommandNames = ['grid'.freeze].freeze

Public Instance methods

add(widget, *args)

[Source]

# File tk/lib/tk/grid.rb, line 129
  def add(widget, *args)
    configure(widget, *args)
  end
anchor(master, anchor=None)

[Source]

# File tk/lib/tk/grid.rb, line 12
  def anchor(master, anchor=None)
    # master = master.epath if master.kind_of?(TkObject)
    master = _epath(master)
    tk_call_without_enc('grid', 'anchor', master, anchor)
  end
bbox(master, *args)

[Source]

# File tk/lib/tk/grid.rb, line 18
  def bbox(master, *args)
    # master = master.epath if master.kind_of?(TkObject)
    master = _epath(master)
    args.unshift(master)
    list(tk_call_without_enc('grid', 'bbox', *args))
  end
columnconfiginfo(master, index, slot=nil)

[Source]

# File tk/lib/tk/grid.rb, line 71
  def columnconfiginfo(master, index, slot=nil)
    # master = master.epath if master.kind_of?(TkObject)
    master = _epath(master)
    if slot
      case slot
      when 'uniform', :uniform
        tk_call_without_enc('grid', 'columnconfigure',
                            master, index, "-#{slot}")
      else
        num_or_str(tk_call_without_enc('grid', 'columnconfigure',
                                       master, index, "-#{slot}"))
      end
    else
      #ilist = list(tk_call_without_enc('grid','columnconfigure',master,index))
      ilist = simplelist(tk_call_without_enc('grid', 'columnconfigure',
                                             master, index))
      info = {}
      while key = ilist.shift
        case key
        when 'uniform'
          info[key[1..-1]] = ilist.shift
        else
          info[key[1..-1]] = tk_tcl2ruby(ilist.shift)
        end
      end
      info
    end
  end
columnconfigure(master, index, args)

[Source]

# File tk/lib/tk/grid.rb, line 58
  def columnconfigure(master, index, args)
    # master = master.epath if master.kind_of?(TkObject)
    master = _epath(master)
    tk_call_without_enc("grid", 'columnconfigure',
                        master, index, *hash_kv(args))
  end
configure(win, *args)

[Source]

# File tk/lib/tk/grid.rb, line 25
  def configure(win, *args)
    if args[-1].kind_of?(Hash)
      opts = args.pop
    else
      opts = {}
    end
    params = []
    params.push(_epath(win))
    args.each{|win|
      case win
      when '-', 'x', '^'  # RELATIVE PLACEMENT
        params.push(win)
      else
        params.push(_epath(win))
      end
    }
    opts.each{|k, v|
      params.push("-#{k}")
      params.push((v.kind_of?(TkObject))? v.epath: v)
    }
    if Tk::TCL_MAJOR_VERSION < 8 ||
        (Tk::TCL_MAJOR_VERSION == 8 && Tk::TCL_MINOR_VERSION <= 3)
      if params[0] == '-' || params[0] == 'x' || params[0] == '^'
        tk_call_without_enc('grid', *params)
      else
        tk_call_without_enc('grid', 'configure', *params)
      end
    else
      tk_call_without_enc('grid', 'configure', *params)
    end
  end
forget(*args)

[Source]

# File tk/lib/tk/grid.rb, line 133
  def forget(*args)
    return '' if args.size == 0
    wins = args.collect{|win|
      # (win.kind_of?(TkObject))? win.epath: win
      _epath(win)
    }
    tk_call_without_enc('grid', 'forget', *wins)
  end
grid(win, *args)

Alias for configure

info(slave)

[Source]

# File tk/lib/tk/grid.rb, line 142
  def info(slave)
    # slave = slave.epath if slave.kind_of?(TkObject)
    slave = _epath(slave)
    #ilist = list(tk_call_without_enc('grid', 'info', slave))
    ilist = simplelist(tk_call_without_enc('grid', 'info', slave))
    info = {}
    while key = ilist.shift
      #info[key[1..-1]] = ilist.shift
      info[key[1..-1]] = tk_tcl2ruby(ilist.shift)
    end
    return info
  end
location(master, x, y)

[Source]

# File tk/lib/tk/grid.rb, line 155
  def location(master, x, y)
    # master = master.epath if master.kind_of?(TkObject)
    master = _epath(master)
    list(tk_call_without_enc('grid', 'location', master, x, y))
  end
propagate(master, mode=None)

[Source]

# File tk/lib/tk/grid.rb, line 161
  def propagate(master, mode=None)
    # master = master.epath if master.kind_of?(TkObject)
    master = _epath(master)
    if mode == None
      bool(tk_call_without_enc('grid', 'propagate', master))
    else
      tk_call_without_enc('grid', 'propagate', master, mode)
    end
  end
remove(*args)

[Source]

# File tk/lib/tk/grid.rb, line 171
  def remove(*args)
    return '' if args.size == 0
    wins = args.collect{|win|
      # (win.kind_of?(TkObject))? win.epath: win
      _epath(win)
    }
    tk_call_without_enc('grid', 'remove', *wins)
  end
rowconfiginfo(master, index, slot=nil)

[Source]

# File tk/lib/tk/grid.rb, line 100
  def rowconfiginfo(master, index, slot=nil)
    # master = master.epath if master.kind_of?(TkObject)
    master = _epath(master)
    if slot
      case slot
      when 'uniform', :uniform
        tk_call_without_enc('grid', 'rowconfigure',
                            master, index, "-#{slot}")
      else
        num_or_str(tk_call_without_enc('grid', 'rowconfigure',
                                       master, index, "-#{slot}"))
      end
    else
      #ilist = list(tk_call_without_enc('grid', 'rowconfigure', master, index))
      ilist = simplelist(tk_call_without_enc('grid', 'rowconfigure',
                                             master, index))
      info = {}
      while key = ilist.shift
        case key
        when 'uniform'
          info[key[1..-1]] = ilist.shift
        else
          info[key[1..-1]] = tk_tcl2ruby(ilist.shift)
        end
      end
      info
    end
  end
rowconfigure(master, index, args)

[Source]

# File tk/lib/tk/grid.rb, line 65
  def rowconfigure(master, index, args)
    # master = master.epath if master.kind_of?(TkObject)
    master = _epath(master)
    tk_call_without_enc("grid", 'rowconfigure', master, index, *hash_kv(args))
  end
size(master)

[Source]

# File tk/lib/tk/grid.rb, line 180
  def size(master)
    # master = master.epath if master.kind_of?(TkObject)
    master = _epath(master)
    list(tk_call_without_enc('grid', 'size', master))
  end
slaves(master, args)

[Source]

# File tk/lib/tk/grid.rb, line 186
  def slaves(master, args)
    # master = master.epath if master.kind_of?(TkObject)
    master = _epath(master)
    list(tk_call_without_enc('grid', 'slaves', master, *hash_kv(args)))
  end


Class: TkImage

Class | TkImage
In: | tk/lib/tk/image.rb
Parent: | TkObject

Methods

delete height inuse itemtype names new new types width

Included Modules

Tk

Constants

TkCommandNames | = | ['image'.freeze].freeze
Tk_IMGTBL | = | TkCore::INTERP.create_table
Tk_Image_ID | = | ['i'.freeze, '00000'.taint].freeze

Public Class methods

names()

[Source]

# File tk/lib/tk/image.rb, line 87
  def TkImage.names
    Tk.tk_call_without_enc('image', 'names').split.collect!{|id|
      (Tk_IMGTBL[id])? Tk_IMGTBL[id] : id
    }
  end
new(keys=nil)

[Source]

# File tk/lib/tk/image.rb, line 17
  def self.new(keys=nil)
    if keys.kind_of?(Hash)
      name = nil
      if keys.key?(:imagename)
        name = keys[:imagename]
      elsif keys.key?('imagename')
        name = keys['imagename']
      end
      if name
        if name.kind_of?(TkImage)
          obj = name
        else
          name = _get_eval_string(name)
          obj = Tk_IMGTBL[name]
        end
        if obj
          if !(keys[:without_creating] || keys['without_creating'])
            keys = _symbolkey2str(keys)
            keys.delete('imagename')
            keys.delete('without_creating')
            obj.instance_eval{
              tk_call_without_enc('image', 'create',
                                  @type, @path, *hash_kv(keys, true))
            }
          end
          return obj
        end
      end
    end
    super(keys)
  end
new(keys=nil)

[Source]

# File tk/lib/tk/image.rb, line 49
  def initialize(keys=nil)
    @path = nil
    without_creating = false
    if keys.kind_of?(Hash)
      keys = _symbolkey2str(keys)
      @path = keys.delete('imagename')
      without_creating = keys.delete('without_creating')
    end
    unless @path
      # @path = Tk_Image_ID.join('')
      @path = Tk_Image_ID.join(TkCore::INTERP._ip_id_)
      Tk_Image_ID[1].succ!
    end
    unless without_creating
      tk_call_without_enc('image', 'create',
                          @type, @path, *hash_kv(keys, true))
    end
    Tk_IMGTBL[@path] = self
  end
types()

[Source]

# File tk/lib/tk/image.rb, line 93
  def TkImage.types
    Tk.tk_call_without_enc('image', 'types').split
  end

Public Instance methods

delete()

[Source]

# File tk/lib/tk/image.rb, line 69
  def delete
    Tk_IMGTBL.delete(@id) if @id
    tk_call_without_enc('image', 'delete', @path)
    self
  end
height()

[Source]

# File tk/lib/tk/image.rb, line 74
  def height
    number(tk_call_without_enc('image', 'height', @path))
  end
inuse()

[Source]

# File tk/lib/tk/image.rb, line 77
  def inuse
    bool(tk_call_without_enc('image', 'inuse', @path))
  end
itemtype()

[Source]

# File tk/lib/tk/image.rb, line 80
  def itemtype
    tk_call_without_enc('image', 'type', @path)
  end
width()

[Source]

# File tk/lib/tk/image.rb, line 83
  def width
    number(tk_call_without_enc('image', 'width', @path))
  end


Module: TkItemConfigMethod

Module | TkItemConfigMethod
In: | tk/lib/tk/itemconfig.rb

Methods

current_itemconfiginfo itemcget itemconfiginfo itemconfigure tagid

Included Modules

TkUtil TkTreatItemFont TkItemConfigOptkeys

Public Instance methods

current_itemconfiginfo(tagOrId, slot = nil)

[Source]

# File tk/lib/tk/itemconfig.rb, line 1024
  def current_itemconfiginfo(tagOrId, slot = nil)
    if TkComm::GET_CONFIGINFO_AS_ARRAY
      if slot
        org_slot = slot
        begin
          conf = itemconfiginfo(tagOrId, slot)
          if ( ! __item_configinfo_struct(tagid(tagOrId))[:alias] \
              || conf.size > __item_configinfo_struct(tagid(tagOrId))[:alias] + 1 )
            return {conf[0] => conf[-1]}
          end
          slot = conf[__item_configinfo_struct(tagid(tagOrId))[:alias]]
        end while(org_slot != slot)
        fail RuntimeError,
          "there is a configure alias loop about '#{org_slot}'"
      else
        ret = {}
        itemconfiginfo(tagOrId).each{|conf|
          if ( ! __item_configinfo_struct(tagid(tagOrId))[:alias] \
              || conf.size > __item_configinfo_struct(tagid(tagOrId))[:alias] + 1 )
            ret[conf[0]] = conf[-1]
          end
        }
        ret
      end
    else # ! TkComm::GET_CONFIGINFO_AS_ARRAY
      ret = {}
      itemconfiginfo(slot).each{|key, conf|
        ret[key] = conf[-1] if conf.kind_of?(Array)
      }
      ret
    end
  end
itemcget(tagOrId, option)

[Source]

# File tk/lib/tk/itemconfig.rb, line 152
  def itemcget(tagOrId, option)
    orig_opt = option
    option = option.to_s

    if option.length == 0
      fail ArgumentError, "Invalid option `#{orig_opt.inspect}'"
    end

    if ( method = _symbolkey2str(__item_val2ruby_optkeys(tagid(tagOrId)))[option] )
      optval = tk_call_without_enc(*(__item_cget_cmd(tagid(tagOrId)) << "-#{option}"))
      begin
        return method.call(tagOrId, optval)
      rescue => e
        warn("Warning:: #{e.message} (when #{method}.call(#{tagOrId.inspect}, #{optval.inspect})") if $DEBUG
        return optval
      end
    end

    if ( method = _symbolkey2str(__item_methodcall_optkeys(tagid(tagOrId)))[option] )
      return self.__send__(method, tagOrId)
    end

    case option
    when /^(#{__item_numval_optkeys(tagid(tagOrId)).join('|')})$/
      begin
        number(tk_call_without_enc(*(__item_cget_cmd(tagid(tagOrId)) << "-#{option}")))
      rescue
        nil
      end

    when /^(#{__item_numstrval_optkeys(tagid(tagOrId)).join('|')})$/
      num_or_str(tk_call_without_enc(*(__item_cget_cmd(tagid(tagOrId)) << "-#{option}")))

    when /^(#{__item_boolval_optkeys(tagid(tagOrId)).join('|')})$/
      begin
        bool(tk_call_without_enc(*(__item_cget_cmd(tagid(tagOrId)) << "-#{option}")))
      rescue
        nil
      end

    when /^(#{__item_listval_optkeys(tagid(tagOrId)).join('|')})$/
      simplelist(tk_call_without_enc(*(__item_cget_cmd(tagid(tagOrId)) << "-#{option}")))

    when /^(#{__item_numlistval_optkeys(tagid(tagOrId)).join('|')})$/
      conf = tk_call_without_enc(*(__item_cget_cmd(tagid(tagOrId)) << "-#{option}"))
      if conf =~ /^[0-9]/
        list(conf)
      else
        conf
      end

    when /^(#{__item_tkvariable_optkeys(tagid(tagOrId)).join('|')})$/
      v = tk_call_without_enc(*(__item_cget_cmd(tagid(tagOrId)) << "-#{option}"))
      (v.empty?)? nil: TkVarAccess.new(v)

    when /^(#{__item_strval_optkeys(tagid(tagOrId)).join('|')})$/
      _fromUTF8(tk_call_without_enc(*(__item_cget_cmd(tagid(tagOrId)) << "-#{option}")))

    when /^(|latin|ascii|kanji)(#{__item_font_optkeys(tagid(tagOrId)).join('|')})$/
      fontcode = $1
      fontkey  = $2
      fnt = tk_tcl2ruby(tk_call_without_enc(*(__item_cget_cmd(tagid(tagOrId)) << "-#{fontkey}")), true)
      unless fnt.kind_of?(TkFont)
        fnt = tagfontobj(tagid(tagOrId), fontkey)
      end
      if fontcode == 'kanji' && JAPANIZED_TK && TK_VERSION =~ /^4\.*/
        # obsolete; just for compatibility
        fnt.kanji_font
      else
        fnt
      end
    else
      tk_tcl2ruby(tk_call_without_enc(*(__item_cget_cmd(tagid(tagOrId)) << "-#{option}")), true)
    end
  end
itemconfiginfo(tagOrId, slot = nil)

[Source]

# File tk/lib/tk/itemconfig.rb, line 292
  def itemconfiginfo(tagOrId, slot = nil)
    if TkComm::GET_CONFIGINFO_AS_ARRAY
      if (slot && slot.to_s =~ /^(|latin|ascii|kanji)(#{__item_font_optkeys(tagid(tagOrId)).join('|')})$/)
        fontkey  = $2
        # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{fontkey}"))))
        conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{fontkey}")), false, true)
        conf[__item_configinfo_struct(tagid(tagOrId))[:key]] =
          conf[__item_configinfo_struct(tagid(tagOrId))[:key]][1..-1]
        if ( ! __item_configinfo_struct(tagid(tagOrId))[:alias] \
            || conf.size > __item_configinfo_struct(tagid(tagOrId))[:alias] + 1 )
          conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = tagfontobj(tagid(tagOrId), fontkey)
        elsif ( __item_configinfo_struct(tagid(tagOrId))[:alias] \
               && conf.size == __item_configinfo_struct(tagid(tagOrId))[:alias] + 1 \
               && conf[__item_configinfo_struct(tagid(tagOrId))[:alias]][0] == ?- )
          conf[__item_configinfo_struct(tagid(tagOrId))[:alias]] =
            conf[__item_configinfo_struct(tagid(tagOrId))[:alias]][1..-1]
        end
        conf
      else
        if slot
          slot = slot.to_s
          case slot
          when /^(#{__item_val2ruby_optkeys(tagid(tagOrId)).keys.join('|')})$/
            method = _symbolkey2str(__item_val2ruby_optkeys(tagid(tagOrId)))[slot]
            conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), false, true)
            if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
                && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
              optval = conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]]
              begin
                val = method.call(tagOrId, optval)
              rescue => e
                warn("Warning:: #{e.message} (when #{method}.call(#{tagOrId.inspect}, #{optval.inspect})") if $DEBUG
                val = optval
              end
              conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] = val
            end
            if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] )
              optval = conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]]
              begin
                val = method.call(tagOrId, optval)
              rescue => e
                warn("Warning:: #{e.message} (when #{method}lcall(#{tagOrId.inspect}, #{optval.inspect})") if $DEBUG
                val = optval
              end
              conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = val
            end

          when /^(#{__item_methodcall_optkeys(tagid(tagOrId)).keys.join('|')})$/
            method = _symbolkey2str(__item_methodcall_optkeys(tagid(tagOrId)))[slot]
            return [slot, '', '', '', self.__send__(method, tagOrId)]

          when /^(#{__item_numval_optkeys(tagid(tagOrId)).join('|')})$/
            # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
            conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), false, true)

            if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
                && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
              begin
                conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] =
                  number(conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]])
              rescue
                conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] = nil
              end
            end
            if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] )
              begin
                conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] =
                  number(conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]])
              rescue
                conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = nil
              end
            end

          when /^(#{__item_numstrval_optkeys(tagid(tagOrId)).join('|')})$/
            # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
            conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), false, true)

            if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
                && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
              conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] =
                num_or_str(conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]])
            end
            if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] )
              conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] =
                num_or_str(conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]])
            end

          when /^(#{__item_boolval_optkeys(tagid(tagOrId)).join('|')})$/
            # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
            conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), false, true)

            if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
                && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
              begin
                conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] =
                  bool(conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]])
              rescue
                conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] = nil
              end
            end
            if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] )
              begin
                conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] =
                  bool(conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]])
              rescue
                conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = nil
              end
            end

          when /^(#{__item_listval_optkeys(tagid(tagOrId)).join('|')})$/
            # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
            conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), false, true)

            if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
                && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
              conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] =
                simplelist(conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]])
            end
            if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] )
              conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] =
                simplelist(conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]])
            end

          when /^(#{__item_numlistval_optkeys(tagid(tagOrId)).join('|')})$/
            # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
            conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), false, true)

            if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
                && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] \
                && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] =~ /^[0-9]/ )
              conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] =
                list(conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]])
            end
            if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] \
                && conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] =~ /^[0-9]/ )
              conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] =
                list(conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]])
            end

          when /^(#{__item_strval_optkeys(tagid(tagOrId)).join('|')})$/
            # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
            conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), false, true)

          when /^(#{__item_tkvariable_optkeys(tagid(tagOrId)).join('|')})$/
            conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), false, true)

            if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
                && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
              v = conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]]
              if v.empty?
                conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] = nil
              else
                conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] = TkVarAccess.new(v)
              end
            end
            if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] )
              v = conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]]
              if v.empty?
                conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = nil
              else
                conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = TkVarAccess.new(v)
              end
            end

          else
            # conf = tk_split_list(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
            conf = tk_split_list(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), 0, false, true)
          end
          conf[__item_configinfo_struct(tagid(tagOrId))[:key]] =
            conf[__item_configinfo_struct(tagid(tagOrId))[:key]][1..-1]

          if ( __item_configinfo_struct(tagid(tagOrId))[:alias] \
              && conf.size == __item_configinfo_struct(tagid(tagOrId))[:alias] + 1 \
              && conf[__item_configinfo_struct(tagid(tagOrId))[:alias]][0] == ?- )
            conf[__item_configinfo_struct(tagid(tagOrId))[:alias]] =
              conf[__item_configinfo_struct(tagid(tagOrId))[:alias]][1..-1]
          end

          conf

        else
          # ret = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)))))).collect{|conflist|
          #   conf = tk_split_simplelist(conflist)
          ret = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)))), false, false).collect{|conflist|
            conf = tk_split_simplelist(conflist, false, true)
            conf[__item_configinfo_struct(tagid(tagOrId))[:key]] =
              conf[__item_configinfo_struct(tagid(tagOrId))[:key]][1..-1]

            optkey = conf[__item_configinfo_struct(tagid(tagOrId))[:key]]
            case optkey
            when /^(#{__item_val2ruby_optkeys(tagid(tagOrId)).keys.join('|')})$/
              method = _symbolkey2str(__item_val2ruby_optkeys(tagid(tagOrId)))[optkey]
              if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
                  && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
                optval = conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]]
                begin
                  val = method(tagOrId, optval)
                rescue => e
                  warn("Warning:: #{e.message} (when #{method}.call(#{tagOrId.inspect}, #{optval.inspect})") if $DEBUG
                  val = optval
                end
                conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] = val
              end
              if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] )
                optval = conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]]
                begin
                  val = method.call(tagOrId, optval)
                rescue => e
                  warn("Warning:: #{e.message} (when #{method}.call(#{tagOrId.inspect}, #{optval.inspect})") if $DEBUG
                  val = optval
                end
                conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = val
              end

            when /^(#{__item_strval_optkeys(tagid(tagOrId)).join('|')})$/
              # do nothing

            when /^(#{__item_numval_optkeys(tagid(tagOrId)).join('|')})$/
              if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
                  && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
                begin
                  conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] =
                    number(conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]])
                rescue
                  conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] = nil
                end
              end
              if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] )
                begin
                  conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] =
                    number(conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]])
                rescue
                  conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = nil
                end
              end

            when /^(#{__item_numstrval_optkeys(tagid(tagOrId)).join('|')})$/
              if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
                  && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
                conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] =
                  num_or_str(conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]])
              end
              if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] )
                conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] =
                  num_or_str(conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]])
              end

            when /^(#{__item_boolval_optkeys(tagid(tagOrId)).join('|')})$/
              if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
                  && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
                begin
                  conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] =
                    bool(conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]])
                rescue
                  conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] = nil
                end
              end
              if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] )
                begin
                  conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] =
                    bool(conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]])
                rescue
                  conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = nil
                end
              end

            when /^(#{__item_listval_optkeys(tagid(tagOrId)).join('|')})$/
              if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
                  && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
                conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] =
                  simplelist(conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]])
              end
              if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] )
                conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] =
                  simplelist(conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]])
              end

            when /^(#{__item_numlistval_optkeys(tagid(tagOrId)).join('|')})$/
              if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
                  && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] \
                  && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] =~ /^[0-9]/ )
                conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] =
                  list(conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]])
              end
              if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] \
                  && conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] =~ /^[0-9]/ )
                conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] =
                  list(conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]])
              end

            when /^(#{__item_tkvariable_optkeys(tagid(tagOrId)).join('|')})$/
              if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
                  && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
                v = conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]]
                if v.empty?
                  conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] = nil
                else
                  conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] = TkVarAccess.new(v)
                end
              end
              if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] )
                v = conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]]
                if v.empty?
                  conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = nil
                else
                  conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = TkVarAccess.new
                end
              end

            else
              if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
                  && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
                if conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]].index('{')
                  conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] =
                    tk_split_list(conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]])
                else
                  conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] =
                    tk_tcl2ruby(conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]])
                end
              end
              if conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]]
                if conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]].index('{')
                  conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] =
                    tk_split_list(conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]])
                else
                  conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] =
                    tk_tcl2ruby(conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]])
                end
              end
            end

            if ( __item_configinfo_struct(tagid(tagOrId))[:alias] \
                && conf.size == __item_configinfo_struct(tagid(tagOrId))[:alias] + 1 \
                && conf[__item_configinfo_struct(tagid(tagOrId))[:alias]][0] == ?- )
              conf[__item_configinfo_struct(tagid(tagOrId))[:alias]] =
                conf[__item_configinfo_struct(tagid(tagOrId))[:alias]][1..-1]
            end

            conf
          }

          __item_font_optkeys(tagid(tagOrId)).each{|optkey|
            optkey = optkey.to_s
            fontconf = ret.assoc(optkey)
            if fontconf && fontconf.size > 2
              ret.delete_if{|inf| inf[0] =~ /^(|latin|ascii|kanji)#{optkey}$/}
              fontconf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = tagfontobj(tagid(tagOrId), optkey)
              ret.push(fontconf)
            end
          }

          __item_methodcall_optkeys(tagid(tagOrId)).each{|optkey, method|
            ret << [optkey.to_s, '', '', '', self.__send__(method, tagOrId)]
          }

          ret
        end
      end

    else # ! TkComm::GET_CONFIGINFO_AS_ARRAY
      if (slot && slot.to_s =~ /^(|latin|ascii|kanji)(#{__item_font_optkeys(tagid(tagOrId)).join('|')})$/)
        fontkey  = $2
        # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{fontkey}"))))
        conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{fontkey}")), false, true)
        conf[__item_configinfo_struct(tagid(tagOrId))[:key]] =
          conf[__item_configinfo_struct(tagid(tagOrId))[:key]][1..-1]

        if ( ! __item_configinfo_struct(tagid(tagOrId))[:alias] \
            || conf.size > __item_configinfo_struct(tagid(tagOrId))[:alias] + 1 )
          conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = fontobj(tagid(tagOrId), fontkey)
          { conf.shift => conf }
        elsif ( __item_configinfo_struct(tagid(tagOrId))[:alias] \
               && conf.size == __item_configinfo_struct(tagid(tagOrId))[:alias] + 1 )
          if conf[__item_configinfo_struct(tagid(tagOrId))[:alias]][0] == ?-
            conf[__item_configinfo_struct(tagid(tagOrId))[:alias]] =
              conf[__item_configinfo_struct(tagid(tagOrId))[:alias]][1..-1]
          end
          { conf[0] => conf[1] }
        else
          { conf.shift => conf }
        end
      else
        if slot
          slot = slot.to_s
          case slot
          when /^(#{__item_val2ruby_optkeys(tagid(tagOrId)).keys.join('|')})$/
            method = _symbolkey2str(__item_val2ruby_optkeys(tagid(tagOrId)))[slot]
            conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), false, true)
            if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
                && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
              optval = conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]]
              begin
                val = method.call(tagOrId, optval)
              rescue => e
                warn("Warning:: #{e.message} (when #{method}.call(#{tagOrId.inspect}, #{optval.inspect})") if $DEBUG
                val = optval
              end
              conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] = val
            end
            if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] )
              optval = conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]]
              begin
                val = method.call(tagOrId, optval)
              rescue => e
                warn("Warning:: #{e.message} (when #{method}.call(#{tagOrId.inspect}, #{optval.inspect})") if $DEBUG
                val = optval
              end
              conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = val
            end

          when /^(#{__item_methodcall_optkeys(tagid(tagOrId)).keys.join('|')})$/
            method = _symbolkey2str(__item_methodcall_optkeys(tagid(tagOrId)))[slot]
            return {slot => ['', '', '', self.__send__(method, tagOrId)]}

          when /^(#{__item_numval_optkeys(tagid(tagOrId)).join('|')})$/
            # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
            conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), false, true)

            if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
                && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
              begin
                conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] =
                  number(conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]])
              rescue
                conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] = nil
              end
            end
            if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] )
              begin
                conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] =
                  number(conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]])
              rescue
                conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = nil
              end
            end

          when /^(#{__item_numstrval_optkeys(tagid(tagOrId)).join('|')})$/
            # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
            conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), false, true)

            if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
                && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
              conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] =
                num_or_stre(conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]])
            end
            if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] )
              conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] =
                num_or_str(conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]])
            end

          when /^(#{__item_boolval_optkeys(tagid(tagOrId)).join('|')})$/
            # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
            conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), false, true)

            if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
                && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
              begin
                conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] =
                  bool(conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]])
              rescue
                conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] = nil
              end
            end
            if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] )
              begin
                conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] =
                  bool(conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]])
              rescue
                conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = nil
              end
            end

          when /^(#{__item_listval_optkeys(tagid(tagOrId)).join('|')})$/
            # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
            conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), false, true)

            if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
                && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
              conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] =
                simplelist(conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]])
            end
            if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] )
              conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] =
                simplelist(conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]])
            end

          when /^(#{__item_numlistval_optkeys(tagid(tagOrId)).join('|')})$/
            # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
            conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), false, true)

            if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
                && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] \
                && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] =~ /^[0-9]/ )
              conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] =
                list(conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]])
            end
            if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] \
                && conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] =~ /^[0-9]/ )
              conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] =
                list(conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]])
            end

          when /^(#{__item_strval_optkeys(tagid(tagOrId)).join('|')})$/
            # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
            conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), false, true)

          when /^(#{__item_tkvariable_optkeys(tagid(tagOrId)).join('|')})$/
            conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), false, true)

            if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
                && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
              v = conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]]
              if v.empty?
                conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] = nil
              else
                conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] = TkVarAccess.new(v)
              end
            end
            if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] )
              v = conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]]
              if v.empty?
                conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = nil
              else
                conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = TkVarAccess.new(v)
              end
            end

          else
            # conf = tk_split_list(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
            conf = tk_split_list(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), 0, false, true)
          end
          conf[__item_configinfo_struct(tagid(tagOrId))[:key]] =
            conf[__item_configinfo_struct(tagid(tagOrId))[:key]][1..-1]

          if ( __item_configinfo_struct(tagid(tagOrId))[:alias] \
              && conf.size == __item_configinfo_struct(tagid(tagOrId))[:alias] + 1 )
            if conf[__item_configinfo_struct(tagid(tagOrId))[:alias]][0] == ?-
              conf[__item_configinfo_struct(tagid(tagOrId))[:alias]] =
                conf[__item_configinfo_struct(tagid(tagOrId))[:alias]][1..-1]
            end
            { conf[0] => conf[1] }
          else
            { conf.shift => conf }
          end

        else
          ret = {}
          # tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)))))).each{|conflist|
          #   conf = tk_split_simplelist(conflist)
          tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)))), false, false).each{|conflist|
            conf = tk_split_simplelist(conflist, false, true)
            conf[__item_configinfo_struct(tagid(tagOrId))[:key]] =
              conf[__item_configinfo_struct(tagid(tagOrId))[:key]][1..-1]

            optkey = conf[__item_configinfo_struct(tagid(tagOrId))[:key]]
            case optkey
            when /^(#{__item_val2ruby_optkeys(tagid(tagOrId)).keys.join('|')})$/
              method = _symbolkey2str(__item_val2ruby_optkeys(tagid(tagOrId)))[optkey]
              if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
                  && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
                optval = conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]]
                begin
                  val = method.call(tagOrId, optval)
                rescue => e
                  warn("Warning:: #{e.message} (when #{method}.call(#{tagOrId.inspect}, #{optval.inspect})") if $DEBUG
                  val = optval
                end
                conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] = val
              end
              if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] )
                optval = conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]]
                begin
                  val = method.call(tagOrId, optval)
                rescue => e
                  warn("Warning:: #{e.message} (when #{method}.call(#{tagOrId.inspect}, #{optval.inspect})") if $DEBUG
                  val = optval
                end
                conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = val
              end

            when /^(#{__item_strval_optkeys(tagid(tagOrId)).join('|')})$/
              # do nothing

            when /^(#{__item_numval_optkeys(tagid(tagOrId)).join('|')})$/
              if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
                  && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
                begin
                  conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] =
                    number(conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]])
                rescue
                  conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] = nil
                end
              end
              if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] )
                begin
                  conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] =
                    number(conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]])
                rescue
                  conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = nil
                end
              end

            when /^(#{__item_numstrval_optkeys(tagid(tagOrId)).join('|')})$/
              if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
                  && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
                conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] =
                  num_or_str(conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]])
              end
              if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] )
                conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] =
                  num_or_str(conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]])
              end

            when /^(#{__item_boolval_optkeys(tagid(tagOrId)).join('|')})$/
              if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
                  && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
                begin
                  conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] =
                    bool(conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]])
                rescue
                  conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] = nil
                end
              end
              if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] )
                begin
                  conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] =
                    bool(conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]])
                rescue
                  conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = nil
                end
              end

            when /^(#{__item_listval_optkeys(tagid(tagOrId)).join('|')})$/
              if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
                  && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
                conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] =
                  simplelist(conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]])
              end
              if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] )
                conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] =
                  simplelist(conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]])
              end

            when /^(#{__item_numlistval_optkeys(tagid(tagOrId)).join('|')})$/
              if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
                  && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] \
                  && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] =~ /^[0-9]/ )
                conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] =
                  list(conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]])
              end
              if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] \
                  && conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] =~ /^[0-9]/ )
                conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] =
                  list(conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]])
              end

            when /^(#{__item_tkvariable_optkeys(tagid(tagOrId)).join('|')})$/
              if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
                  && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
                v = conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]]
                if v.empty?
                  conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] = nil
                else
                  conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] = TkVarAccess.new(v)
                end
              end
              if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] )
                v = conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]]
                if v.empty?
                  conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = nil
                else
                  conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = TkVarAccess.new(v)
                end
              end

            else
              if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
                  && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
                if conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]].index('{')
                  conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] =
                    tk_split_list(conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]])
                else
                  conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] =
                    tk_tcl2ruby(conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]])
                end
              end
              if conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]]
                if conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]].index('{')
                  conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] =
                    tk_split_list(conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]])
                else
                  conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] =
                    tk_tcl2ruby(conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]])
                end
              end
            end

            if ( __item_configinfo_struct(tagid(tagOrId))[:alias] \
                && conf.size == __item_configinfo_struct(tagid(tagOrId))[:alias] + 1 )
              if conf[__item_configinfo_struct(tagid(tagOrId))[:alias]][0] == ?-
                conf[__item_configinfo_struct(tagid(tagOrId))[:alias]] =
                  conf[__item_configinfo_struct(tagid(tagOrId))[:alias]][1..-1]
              end
              ret[conf[0]] = conf[1]
            else
              ret[conf.shift] = conf
            end
          }

          __item_font_optkeys(tagid(tagOrId)).each{|optkey|
            optkey = optkey.to_s
            fontconf = ret[optkey]
            if fontconf.kind_of?(Array)
              ret.delete(optkey)
              ret.delete('latin' << optkey)
              ret.delete('ascii' << optkey)
              ret.delete('kanji' << optkey)
              fontconf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = tagfontobj(tagid(tagOrId), optkey)
              ret[optkey] = fontconf
            end
          }

          __item_methodcall_optkeys(tagid(tagOrId)).each{|optkey, method|
            ret[optkey.to_s] = ['', '', '', self.__send__(method, tagOrId)]
          }

          ret
        end
      end
    end
  end
itemconfigure(tagOrId, slot, value=None)

[Source]

# File tk/lib/tk/itemconfig.rb, line 228
  def itemconfigure(tagOrId, slot, value=None)
    if slot.kind_of? Hash
      slot = _symbolkey2str(slot)

      __item_methodcall_optkeys(tagid(tagOrId)).each{|key, method|
        value = slot.delete(key.to_s)
        self.__send__(method, tagOrId, value) if value
      }

      __item_ruby2val_optkeys(tagid(tagOrId)).each{|key, method|
        key = key.to_s
        slot[key] = method.call(tagOrId, slot[key]) if slot.has_key?(key)
      }

      __item_keyonly_optkeys(tagid(tagOrId)).each{|defkey, undefkey|
        conf = slot.find{|kk, vv| kk == defkey.to_s}
        if conf
          k, v = conf
          if v
            slot[k] = None
          else
            slot[undefkey.to_s] = None if undefkey
            slot.delete(k)
          end
        end
      }

      if (slot.find{|k, v| k =~ /^(|latin|ascii|kanji)(#{__item_font_optkeys(tagid(tagOrId)).join('|')})$/})
        tagfont_configure(tagid(tagOrId), slot)
      elsif slot.size > 0
        tk_call(*(__item_config_cmd(tagid(tagOrId)).concat(hash_kv(slot))))
      end

    else
      orig_slot = slot
      slot = slot.to_s
      if slot.length == 0
        fail ArgumentError, "Invalid option `#{orig_slot.inspect}'"
      end

      if ( conf = __item_keyonly_optkeys(tagid(tagOrId)).find{|k, v| k.to_s == slot } )
        defkey, undefkey = conf
        if value
          tk_call(*(__item_config_cmd(tagid(tagOrId)) << "-#{defkey}"))
        elsif undefkey
          tk_call(*(__item_config_cmd(tagid(tagOrId)) << "-#{undefkey}"))
        end
      elsif ( method = _symbolkey2str(__item_ruby2val_optkeys(tagid(tagOrId)))[slot] )
        tk_call(*(__item_config_cmd(tagid(tagOrId)) << "-#{slot}" << method.call(tagOrId, value)))
      elsif ( method = _symbolkey2str(__item_methodcall_optkeys(tagid(tagOrId)))[slot] )
        self.__send__(method, tagOrId, value)
      elsif (slot =~ /^(|latin|ascii|kanji)(#{__item_font_optkeys(tagid(tagOrId)).join('|')})$/)
        if value == None
          tagfontobj(tagid(tagOrId), $2)
        else
          tagfont_configure(tagid(tagOrId), {slot=>value})
        end
      else
        tk_call(*(__item_config_cmd(tagid(tagOrId)) << "-#{slot}" << value))
      end
    end
    self
  end
tagid(tagOrId)

[Source]

# File tk/lib/tk/itemconfig.rb, line 145
  def tagid(tagOrId)
    # maybe need to override
    tagOrId
  end


Module: TkItemConfigOptkeys

Module | TkItemConfigOptkeys
In: | tk/lib/tk/itemconfig.rb

Methods

__conv_item_keyonly_opts itemconfig_hash_kv

Included Modules

TkUtil

Public Instance methods

__conv_item_keyonly_opts(id, keys)

[Source]

# File tk/lib/tk/itemconfig.rb, line 88
  def __conv_item_keyonly_opts(id, keys)
    return keys unless keys.kind_of?(Hash)
    keyonly = __item_keyonly_optkeys(id)
    keys2 = {}
    keys.each{|k, v|
      optkey = keyonly.find{|kk,vv| kk.to_s == k.to_s}
      if optkey
        defkey, undefkey = optkey
        if v
          keys2[defkey.to_s] = None
        else
          keys2[undefkey.to_s] = None
        end
      else
        keys2[k.to_s] = v
      end
    }
    keys2
  end
itemconfig_hash_kv(id, keys, enc_mode = nil, conf = nil)

[Source]

# File tk/lib/tk/itemconfig.rb, line 108
  def itemconfig_hash_kv(id, keys, enc_mode = nil, conf = nil)
    hash_kv(__conv_item_keyonly_opts(id, keys), enc_mode, conf)
  end


Module: TkItemFontOptkeys

Module | TkItemFontOptkeys
In: | tk/lib/tk/itemfont.rb


Class: TkKernel

Class | TkKernel
In: | tk/tkutil.c
Parent: | Object

Methods

new

Public Class methods

new(...)

/

[Source]

/*************************************/

static VALUE
tk_s_new(argc, argv, klass)
    int argc;
    VALUE *argv;
    VALUE klass;
{
    VALUE obj = rb_class_new_instance(argc, argv, klass);

    if (rb_block_given_p()) rb_obj_instance_eval(0, 0, obj);
    return obj;
}


Module: TkKinput

Module | TkKinput
In: | tk/lib/tk/kinput.rb

Methods

attribute_config attribute_info input_end input_start kanji_input_end kanji_input_start kinput_attribute_config kinput_attribute_info kinput_send_spot kinput_start send_spot start

Included Modules

Tk

Constants

TkCommandNames = [ 'kinput_start'.freeze, 'kinput_send_spot'.freeze, 'kanjiInput'.freeze

Public Class methods

attribute_config(win, slot, value=None)

[Source]

# File tk/lib/tk/kinput.rb, line 37
  def TkKinput.attribute_config(win, slot, value=None)
    if slot.kind_of? Hash
      tk_call('kanjiInput', 'attribute', win, *hash_kv(slot))
    else
      tk_call('kanjiInput', 'attribute', win, "-#{slot}", value)
    end
  end
attribute_info(win, slot=nil)

[Source]

# File tk/lib/tk/kinput.rb, line 48
  def TkKinput.attribute_info(win, slot=nil)
    if slot
      conf = tk_split_list(tk_call('kanjiInput', 'attribute',
                                   win, "-#{slot}"))
      conf[0] = conf[0][1..-1]
      conf
    else
      tk_split_list(tk_call('kanjiInput', 'attribute', win)).collect{|conf|
        conf[0] = conf[0][1..-1]
        conf
      }
    end
  end
input_end(win)

[Source]

# File tk/lib/tk/kinput.rb, line 65
  def TkKinput.input_end(win)
    tk_call('kanjiInput', 'end', win)
  end
input_start(win, keys=nil)

[Source]

# File tk/lib/tk/kinput.rb, line 30
  def TkKinput.input_start(win, keys=nil)
    tk_call('kanjiInput', 'start', win, *hash_kv(keys))
  end
send_spot(win)

[Source]

# File tk/lib/tk/kinput.rb, line 23
  def TkKinput.send_spot(win)
    tk_call('kinput_send_spot', win)
  end
start(win, style=None)

[Source]

# File tk/lib/tk/kinput.rb, line 16
  def TkKinput.start(win, style=None)
    tk_call('kinput_start', win, style)
  end

Public Instance methods

kanji_input_end()

[Source]

# File tk/lib/tk/kinput.rb, line 68
  def kanji_input_end
    TkKinput.input_end(self)
  end
kanji_input_start(keys=nil)

[Source]

# File tk/lib/tk/kinput.rb, line 33
  def kanji_input_start(keys=nil)
    TkKinput.input_start(self, keys)
  end
kinput_attribute_config(slot, value=None)

[Source]

# File tk/lib/tk/kinput.rb, line 44
  def kinput_attribute_config(slot, value=None)
    TkKinput.attribute_config(self, slot, value)
  end
kinput_attribute_info(slot=nil)

[Source]

# File tk/lib/tk/kinput.rb, line 61
  def kinput_attribute_info(slot=nil)
    TkKinput.attribute_info(self, slot)
  end
kinput_send_spot()

[Source]

# File tk/lib/tk/kinput.rb, line 26
  def kinput_send_spot
    TkKinput.send_spot(self)
  end
kinput_start(style=None)

[Source]

# File tk/lib/tk/kinput.rb, line 19
  def kinput_start(style=None)
    TkKinput.start(self, style)
  end


Class: TkLabel

Class | TkLabel
In: | tk/lib/tk/label.rb
Parent: | TkWindow

Constants

TkCommandNames | = | ['label'.freeze].freeze
WidgetClassName | = | 'Label'.freeze


Class: TkLabelFrame

Class | TkLabelFrame
In: | tk/lib/tk/labelframe.rb
Parent: | TkFrame

Constants

TkCommandNames | = | ['labelframe'.freeze].freeze
WidgetClassName | = | 'Labelframe'.freeze


Module: TkListItemConfig

Module | TkListItemConfig
In: | tk/lib/tk/listbox.rb

Included Modules

TkItemConfigMethod


Class: TkListbox

Class | TkListbox
In: | tk/lib/tk/listbox.rb
Parent: | TkTextWin

Methods

activate clear curselection erase get index nearest selection_anchor selection_clear selection_includes selection_set size tagid value value=

Included Modules

TkListItemConfig Scrollable

Constants

TkCommandNames | = | ['listbox'.freeze].freeze
WidgetClassName | = | 'Listbox'.freeze

Public Instance methods

activate(y)

[Source]

# File tk/lib/tk/listbox.rb, line 45
  def activate(y)
    tk_send_without_enc('activate', y)
    self
  end
clear()

[Source]

# File tk/lib/tk/listbox.rb, line 100
  def clear
    tk_send_without_enc('delete', '0', 'end')
    self
  end
curselection()

[Source]

# File tk/lib/tk/listbox.rb, line 49
  def curselection
    list(tk_send_without_enc('curselection'))
  end
erase()

Alias for clear

get(first, last=nil)

[Source]

# File tk/lib/tk/listbox.rb, line 52
  def get(first, last=nil)
    if last
      # tk_split_simplelist(_fromUTF8(tk_send_without_enc('get', first, last)))
      tk_split_simplelist(tk_send_without_enc('get', first, last), false, true)
    else
      _fromUTF8(tk_send_without_enc('get', first))
    end
  end
index(idx)

[Source]

# File tk/lib/tk/listbox.rb, line 82
  def index(idx)
    tk_send_without_enc('index', idx).to_i
  end
nearest(y)

[Source]

# File tk/lib/tk/listbox.rb, line 60
  def nearest(y)
    tk_send_without_enc('nearest', y).to_i
  end
selection_anchor(index)

[Source]

# File tk/lib/tk/listbox.rb, line 66
  def selection_anchor(index)
    tk_send_without_enc('selection', 'anchor', index)
    self
  end
selection_clear(first, last=None)

[Source]

# File tk/lib/tk/listbox.rb, line 70
  def selection_clear(first, last=None)
    tk_send_without_enc('selection', 'clear', first, last)
    self
  end
selection_includes(index)

[Source]

# File tk/lib/tk/listbox.rb, line 74
  def selection_includes(index)
    bool(tk_send_without_enc('selection', 'includes', index))
  end
selection_set(first, last=None)

[Source]

# File tk/lib/tk/listbox.rb, line 77
  def selection_set(first, last=None)
    tk_send_without_enc('selection', 'set', first, last)
    self
  end
size()

[Source]

# File tk/lib/tk/listbox.rb, line 63
  def size
    tk_send_without_enc('size').to_i
  end
tagid(id)

[Source]

# File tk/lib/tk/listbox.rb, line 40
  def tagid(id)
    #id.to_s
    _get_eval_string(id)
  end
value()

[Source]

# File tk/lib/tk/listbox.rb, line 86
  def value
    get('0', 'end')
  end
value=(vals)

[Source]

# File tk/lib/tk/listbox.rb, line 90
  def value= (vals)
    unless vals.kind_of?(Array)
      fail ArgumentError, 'an Array is expected'
    end
    tk_send_without_enc('delete', '0', 'end')
    tk_send_without_enc('insert', '0',
                        *(vals.collect{|v| _get_eval_enc_str(v)}))
    vals
  end


Module: TkMacResource

Module | TkMacResource
In: | tk/lib/tk/macpkg.rb

Methods

close delete files list open package_name read types write

Constants

TkCommandNames | = | ['resource'.freeze].freeze
PACKAGE_NAME | = | 'resource'.freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tk/macpkg.rb, line 30
  def self.package_name
    PACKAGE_NAME
  end

Public Instance methods

close(rsrcRef)

[Source]

# File tk/lib/tk/macpkg.rb, line 36
  def close(rsrcRef)
    tk_call('resource', 'close', rsrcRef)
  end
delete(rsrcType, opts=nil)

[Source]

# File tk/lib/tk/macpkg.rb, line 40
  def delete(rsrcType, opts=nil)
    tk_call('resource', 'delete', *(hash_kv(opts) << rsrcType))
  end
files(rsrcRef=nil)

[Source]

# File tk/lib/tk/macpkg.rb, line 44
  def files(rsrcRef=nil)
    if rsrcRef
      tk_call('resource', 'files', rsrcRef)
    else
      tk_split_simplelist(tk_call('resource', 'files'))
    end
  end
list(rsrcType, rsrcRef=nil)

[Source]

# File tk/lib/tk/macpkg.rb, line 52
  def list(rsrcType, rsrcRef=nil)
    tk_split_simplelist(tk_call('resource', 'list', rsrcType, rsrcRef))
  end
open(fname, access=nil)

[Source]

# File tk/lib/tk/macpkg.rb, line 56
  def open(fname, access=nil)
    tk_call('resource', 'open', fname, access)
  end
read(rsrcType, rsrcID, rsrcRef=nil)

[Source]

# File tk/lib/tk/macpkg.rb, line 60
  def read(rsrcType, rsrcID, rsrcRef=nil)
    tk_call('resource', 'read', rsrcType, rsrcID, rsrcRef)
  end
types(rsrcRef=nil)

[Source]

# File tk/lib/tk/macpkg.rb, line 64
  def types(rsrcRef=nil)
    tk_split_simplelist(tk_call('resource', 'types', rsrcRef))
  end
write(rsrcType, data, opts=nil)

[Source]

# File tk/lib/tk/macpkg.rb, line 68
  def write(rsrcType, data, opts=nil)
    tk_call('resource', 'write', *(hash_kv(opts) << rsrcType << data))
  end


Module: TkManageFocus

Module | TkManageFocus
In: | tk/lib/tk/mngfocus.rb

Methods

focusNext focusPrev followsMouse next prev

Constants

TkCommandNames = [ 'tk_focusFollowMouse'.freeze, 'tk_focusNext'.freeze, 'tk_focusPrev'.freeze

Public Class methods

followsMouse()

[Source]

# File tk/lib/tk/mngfocus.rb, line 16
  def TkManageFocus.followsMouse
    tk_call_without_enc('tk_focusFollowsMouse')
  end
next(win)

[Source]

# File tk/lib/tk/mngfocus.rb, line 20
  def TkManageFocus.next(win)
    tk_tcl2ruby(tk_call('tk_focusNext', win))
  end
prev(win)

[Source]

# File tk/lib/tk/mngfocus.rb, line 27
  def TkManageFocus.prev(win)
    tk_tcl2ruby(tk_call('tk_focusPrev', win))
  end

Public Instance methods

focusNext()

[Source]

# File tk/lib/tk/mngfocus.rb, line 23
  def focusNext
    TkManageFocus.next(self)
  end
focusPrev()

[Source]

# File tk/lib/tk/mngfocus.rb, line 30
  def focusPrev
    TkManageFocus.prev(self)
  end


Class: TkMenu

Class | TkMenu
In: | tk/lib/tk/menu.rb
Parent: | TkWindow

Methods

activate add add_cascade add_checkbutton add_command add_radiobutton add_separator delete index insert invoke menutype new_menuspec popup post postcascade postcommand set_focus tagid tearoffcommand unpost yposition

Included Modules

TkMenuEntryConfig

Constants

TkCommandNames | = | ['menu'.freeze].freeze
WidgetClassName | = | 'Menu'.freeze

Public Class methods

new_menuspec(menu_spec, parent = nil, tearoff = false, keys = nil)

[Source]

# File tk/lib/tk/menu.rb, line 72
  def self.new_menuspec(menu_spec, parent = nil, tearoff = false, keys = nil)
    if parent.kind_of?(Hash)
      keys = _symbolkey2str(parent)
      parent = keys.delete('parent')
      tearoff = keys.delete('tearoff')
    elsif tearoff.kind_of?(Hash)
      keys = _symbolkey2str(tearoff)
      tearoff = keys.delete('tearoff')
    elsif keys
      keys = _symbolkey2str(keys)
    else
      keys = {}
    end

    widgetname = keys.delete('widgetname')
    _create_menu(parent, menu_spec, widgetname, tearoff, keys)
  end

Public Instance methods

activate(index)

[Source]

# File tk/lib/tk/menu.rb, line 95
  def activate(index)
    tk_send_without_enc('activate', _get_eval_enc_str(index))
    self
  end
add(type, keys=nil)

[Source]

# File tk/lib/tk/menu.rb, line 99
  def add(type, keys=nil)
    tk_send_without_enc('add', type, *hash_kv(keys, true))
    self
  end
add_cascade(keys=nil)

[Source]

# File tk/lib/tk/menu.rb, line 103
  def add_cascade(keys=nil)
    add('cascade', keys)
  end
add_checkbutton(keys=nil)

[Source]

# File tk/lib/tk/menu.rb, line 106
  def add_checkbutton(keys=nil)
    add('checkbutton', keys)
  end
add_command(keys=nil)

[Source]

# File tk/lib/tk/menu.rb, line 109
  def add_command(keys=nil)
    add('command', keys)
  end
add_radiobutton(keys=nil)

[Source]

# File tk/lib/tk/menu.rb, line 112
  def add_radiobutton(keys=nil)
    add('radiobutton', keys)
  end
add_separator(keys=nil)

[Source]

# File tk/lib/tk/menu.rb, line 115
  def add_separator(keys=nil)
    add('separator', keys)
  end
delete(first, last=nil)

[Source]

# File tk/lib/tk/menu.rb, line 130
  def delete(first, last=nil)
    if last
      tk_send_without_enc('delete', _get_eval_enc_str(first),
                          _get_eval_enc_str(last))
    else
      tk_send_without_enc('delete', _get_eval_enc_str(first))
    end
    self
  end
index(idx)

[Source]

# File tk/lib/tk/menu.rb, line 118
  def index(idx)
    ret = tk_send_without_enc('index', _get_eval_enc_str(idx))
    (ret == 'none')? nil: number(ret)
  end
insert(index, type, keys=nil)

[Source]

# File tk/lib/tk/menu.rb, line 125
  def insert(index, type, keys=nil)
    tk_send_without_enc('insert', _get_eval_enc_str(index),
                        type, *hash_kv(keys, true))
    self
  end
invoke(index)

[Source]

# File tk/lib/tk/menu.rb, line 122
  def invoke(index)
    _fromUTF8(tk_send_without_enc('invoke', _get_eval_enc_str(index)))
  end
menutype(index)

[Source]

# File tk/lib/tk/menu.rb, line 167
  def menutype(index)
    tk_send_without_enc('type', _get_eval_enc_str(index))
  end
popup(x, y, index=nil)

[Source]

# File tk/lib/tk/menu.rb, line 139
  def popup(x, y, index=nil)
    if index
      tk_call_without_enc('tk_popup', path, x, y,
                          _get_eval_enc_str(index))
    else
      tk_call_without_enc('tk_popup', path, x, y)
    end
    self
  end
post(x, y)

[Source]

# File tk/lib/tk/menu.rb, line 148
  def post(x, y)
    _fromUTF8(tk_send_without_enc('post', x, y))
  end
postcascade(index)

[Source]

# File tk/lib/tk/menu.rb, line 151
  def postcascade(index)
    tk_send_without_enc('postcascade', _get_eval_enc_str(index))
    self
  end
postcommand(cmd=Proc.new)

[Source]

# File tk/lib/tk/menu.rb, line 155
  def postcommand(cmd=Proc.new)
    configure_cmd 'postcommand', cmd
    self
  end
set_focus()

[Source]

# File tk/lib/tk/menu.rb, line 159
  def set_focus
    tk_call_without_enc('tk_menuSetFocus', path)
    self
  end
tagid(id)

[Source]

# File tk/lib/tk/menu.rb, line 90
  def tagid(id)
    #id.to_s
    _get_eval_string(id)
  end
tearoffcommand(cmd=Proc.new)

[Source]

# File tk/lib/tk/menu.rb, line 163
  def tearoffcommand(cmd=Proc.new)
    configure_cmd 'tearoffcommand', cmd
    self
  end
unpost()

[Source]

# File tk/lib/tk/menu.rb, line 170
  def unpost
    tk_send_without_enc('unpost')
    self
  end
yposition(index)

[Source]

# File tk/lib/tk/menu.rb, line 174
  def yposition(index)
    number(tk_send_without_enc('yposition', _get_eval_enc_str(index)))
  end


Class: TkMenuClone

Class | TkMenuClone
In: | tk/lib/tk/menu.rb
Parent: | TkMenu

Methods

new

Public Class methods

new(parent, type=None)

[Source]

# File tk/lib/tk/menu.rb, line 355
  def initialize(parent, type=None)
    widgetname = nil
    if parent.kind_of? Hash
      keys = _symbolkey2str(parent)
      parent = keys.delete('parent')
      widgetname = keys.delete('widgetname')
      type = keys.delete('type'); type = None unless type
    end
    #unless parent.kind_of?(TkMenu)
    #  fail ArgumentError, "parent must be TkMenu"
    #end
    @parent = parent
    install_win(@parent.path, widgetname)
    tk_call_without_enc(@parent.path, 'clone', @path, type)
  end


Module: TkMenuEntryConfig

Module | TkMenuEntryConfig
In: | tk/lib/tk/menu.rb

Included Modules

TkItemConfigMethod

External Aliases

itemcget | -> | entrycget
itemconfigure | -> | entryconfigure
itemconfiginfo | -> | entryconfiginfo
current_itemconfiginfo | -> | current_entryconfiginfo


Module: TkMenuSpec

Module | TkMenuSpec
In: | tk/lib/tk/menuspec.rb

tk/menuspec.rb

                             Hidethoshi NAGAI (nagai@ai.kyutech.ac.jp)

based on tkmenubar.rb :

  Copyright (C) 1998 maeda shugo. All rights reserved.
  This file can be distributed under the terms of the Ruby.

The format of the menu_spec is:

  [ menu_info, menu_info, ... ]

And the format of the menu_info is:

  [
    [text, underline, configs], # menu button/entry (*1)
    [label, command, underline, accelerator, configs],   # command entry
    [label, TkVar_obj, underline, accelerator, configs], # checkbutton entry
    [label, [TkVar_obj, value],
                       underline, accelerator, configs], # radiobutton entry
    [label, [[...menu_info...], [...menu_info...], ...],
                       underline, accelerator, configs], # cascade entry (*2)
    '---', # separator
    ...
  ]

underline, accelerator, and configs are optional pearameters. Hashes are OK instead of Arrays. Then the entry type (‘command’, ‘checkbutton’, ‘radiobutton’ or ‘cascade’) is given by ‘type’ key (e.g. :type=>’cascade’). When type is ‘cascade’, an array of menu_info is acceptable for ‘menu’ key (then, create sub-menu).

NOTE: (*1)

  If you want to make special menus (*.help for UNIX, *.system for Win,
  and *.apple for Mac), append 'menu_name'=>name (name is 'help' for UNIX,
  'system' for Win, and 'apple' for Mac) option to the configs hash of
  menu button/entry information.

NOTE: (*2)

  If you want to configure a cascade menu, add :menu_config=>{...configs..}
  to the configs of the cascade entry.


Class: TkMenubar

Class | TkMenubar
In: | tk/lib/tk/menubar.rb
Parent: | TkFrame

Methods

[] add_menu new

Included Modules

TkComposite TkMenuSpec

Public Class methods

new(parent = nil, spec = nil, options = nil)

[Source]

# File tk/lib/tk/menubar.rb, line 96
  def initialize(parent = nil, spec = nil, options = nil)
    if parent.kind_of? Hash
      options = _symbolkey2str(parent)
      spec = options.delete('spec')
      super(options)
    else
      super(parent, options)
    end

    @menus = []

    spec.each{|info| add_menu(info)} if spec

    options.each{|key, value| configure(key, value)} if options
  end

Public Instance methods

[](index)

[Source]

# File tk/lib/tk/menubar.rb, line 128
  def [](index)
    return @menus[index]
  end
add_menu(menu_info)

[Source]

# File tk/lib/tk/menubar.rb, line 112
  def add_menu(menu_info)
    mbtn, menu = _create_menubutton(@frame, menu_info)

    submenus = _get_cascade_menus(menu).flatten

    @menus.push([mbtn, menu])
    delegate('tearoff', menu, *submenus)
    delegate('foreground', mbtn, menu, *submenus)
    delegate('background', mbtn, menu, *submenus)
    delegate('disabledforeground', mbtn, menu, *submenus)
    delegate('activeforeground', mbtn, menu, *submenus)
    delegate('activebackground', mbtn, menu, *submenus)
    delegate('font', mbtn, menu, *submenus)
    delegate('kanjifont', mbtn, menu, *submenus)
  end


Class: TkMenubutton

Class | TkMenubutton
In: | tk/lib/tk/menu.rb
Parent: | TkLabel

Constants

TkCommandNames | = | ['menubutton'.freeze].freeze
WidgetClassName | = | 'Menubutton'.freeze


Class: TkMessage

Class | TkMessage
In: | tk/lib/tk/message.rb
Parent: | TkLabel

Constants

TkCommandNames | = | ['message'.freeze].freeze
WidgetClassName | = | 'Message'.freeze


Class: TkMsgCatalog

Class | TkMsgCatalog
In: | tk/lib/tk/msgcat.rb
Parent: | TkObject

class TkMsgCatalog

Methods

[] callback def_unknown_proc def_unknown_proc load load load_rb load_rb load_tk load_tk locale locale locale= locale= maxlen maxlen mc method_missing new package_name preferences preferences set_translation set_translation set_translation_list set_translation_list translate translate

Included Modules

TkCore

Constants

TkCommandNames | = | [ '::msgcat::mc'.freeze, '::msgcat::mcmax'.freeze, '::msgcat::mclocale'.freeze, '::msgcat::mcpreferences'.freeze, '::msgcat::mcload'.freeze, '::msgcat::mcset'.freeze, '::msgcat::mcmset'.freeze, '::msgcat::mcunknown'.freeze | extend TkMsgCatalog
PACKAGE_NAME | = | 'msgcat'.freeze
MSGCAT_EXT | = | '.msg'
UNKNOWN_CBTBL | = | Hash.new{|hash,key| hash[key] = {}}.taint

External Aliases

translate | -> | mc
translate | -> | []

Attributes

msgcat_ext [RW]

Public Class methods

callback(namespace, locale, src_str, *args)

[Source]

# File tk/lib/tk/msgcat.rb, line 59
  def self.callback(namespace, locale, src_str, *args)
    src_str = sprintf(src_str, *args) unless args.empty?
    cmd_tbl = TkMsgCatalog::UNKNOWN_CBTBL[TkCore::INTERP.__getip]
    cmd = cmd_tbl[namespace]
    cmd = cmd_tbl['::'] unless cmd  # use global scope as interp default
    return src_str unless cmd       # no cmd -> return src-str (default action)
    begin
      cmd.call(locale, src_str)
    rescue SystemExit
      exit(0)
    rescue Interrupt
      exit!(1)
    rescue Exception => e
      begin
        msg = _toUTF8(e.class.inspect) + ': ' +
              _toUTF8(e.message) + "\n" +
              "\n---< backtrace of Ruby side >-----\n" +
              _toUTF8(e.backtrace.join("\n")) +
              "\n---< backtrace of Tk side >-------"
        msg.instance_variable_set(:@encoding, 'utf-8')
      rescue Exception
        msg = e.class.inspect + ': ' + e.message + "\n" +
              "\n---< backtrace of Ruby side >-----\n" +
              e.backtrace.join("\n") +
              "\n---< backtrace of Tk side >-------"
      end
      fail(e, msg)
    end
  end
def_unknown_proc(cmd=Proc.new)

[Source]

# File tk/lib/tk/msgcat.rb, line 284
  def self.def_unknown_proc(cmd=Proc.new)
    TkMsgCatalog::UNKNOWN_CBTBL[TkCore::INTERP.__getip]['::'] = cmd
  end
load(dir)

[Source]

# File tk/lib/tk/msgcat.rb, line 220
  def self.load(dir)
    self.load_rb(dir)
  end
load_rb(dir)

[Source]

# File tk/lib/tk/msgcat.rb, line 192
  def self.load_rb(dir)
    count = 0
    preferences().each{|loc|
      file = File.join(dir, loc + self::MSGCAT_EXT)
      if File.readable?(file)
        count += 1
        eval(open(file){|f| f.read})
      end
    }
    count
  end
load_tk(dir)

[Source]

# File tk/lib/tk/msgcat.rb, line 188
  def self.load_tk(dir)
    number(tk_call('::msgcat::mcload', dir))
  end
locale()

[Source]

# File tk/lib/tk/msgcat.rb, line 167
  def self.locale
    tk_call('::msgcat::mclocale')
  end
locale=(locale)

[Source]

# File tk/lib/tk/msgcat.rb, line 174
  def self.locale=(locale)
    tk_call('::msgcat::mclocale', locale)
  end
maxlen(*src_strings)

[Source]

# File tk/lib/tk/msgcat.rb, line 160
  def self.maxlen(*src_strings)
    tk_call('::msgcat::mcmax', *src_strings).to_i
  end
new(namespace = nil)

[Source]

# File tk/lib/tk/msgcat.rb, line 89
  def initialize(namespace = nil)
    if namespace.kind_of?(TkNamespace)
      @namespace = namespace
    elsif namespace == nil
      @namespace = TkNamespace.new('::')  # global namespace
    else
      @namespace = TkNamespace.new(namespace)
    end
    @path = @namespace.path

    @msgcat_ext = '.msg'
  end
package_name()

[Source]

# File tk/lib/tk/msgcat.rb, line 27
  def self.package_name
    PACKAGE_NAME
  end
preferences()

[Source]

# File tk/lib/tk/msgcat.rb, line 181
  def self.preferences
    tk_split_simplelist(tk_call('::msgcat::mcpreferences'))
  end
set_translation(locale, src_str, trans_str=None, enc='utf-8')

[Source]

# File tk/lib/tk/msgcat.rb, line 225
  def self.set_translation(locale, src_str, trans_str=None, enc='utf-8')
    if trans_str && trans_str != None
      trans_str = Tk.UTF8_String(_toUTF8(trans_str, enc))
      Tk.UTF8_String(tk_call_without_enc('::msgcat::mcset',
                                         locale,
                                         _get_eval_string(src_str, true),
                                         trans_str))
    else
      Tk.UTF8_String(tk_call_without_enc('::msgcat::mcset',
                                         locale,
                                         _get_eval_string(src_str, true)))
    end
  end
set_translation_list(locale, trans_list, enc='utf-8')

[Source]

# File tk/lib/tk/msgcat.rb, line 255
  def self.set_translation_list(locale, trans_list, enc='utf-8')
    # trans_list ::= [ [src, trans], [src, trans], ... ]
    list = []
    trans_list.each{|src, trans|
      if trans && trans != None
        list << _get_eval_string(src, true)
        list << Tk.UTF8_Stirng(_toUTF8(trans, enc))
      else
        list << _get_eval_string(src, true) << ''
      end
    }
    number(tk_call_without_enc('::msgcat::mcmset', locale, list))
  end
translate(*args)

*args ::= form, arg, arg, …

[Source]

# File tk/lib/tk/msgcat.rb, line 140
  def self.translate(*args)
    dst = args.collect{|src|
      tk_call_without_enc('::msgcat::mc', _get_eval_string(src, true))
    }
    Tk.UTF8_String(sprintf(*dst))
  end

Public Instance methods

[](*args)

Alias for translate

def_unknown_proc(cmd=Proc.new)

[Source]

# File tk/lib/tk/msgcat.rb, line 287
  def def_unknown_proc(cmd=Proc.new)
    TkMsgCatalog::UNKNOWN_CBTBL[TkCore::INTERP.__getip][@namespace.path] = cmd
  end
load(dir)

Alias for load_rb

load_rb(dir)

[Source]

# File tk/lib/tk/msgcat.rb, line 208
  def load_rb(dir)
    count = 0
    preferences().each{|loc|
      file = File.join(dir, loc + @msgcat_ext)
      if File.readable?(file)
        count += 1
        @namespace.eval(open(file){|f| f.read})
      end
    }
    count
  end
load_tk(dir)

[Source]

# File tk/lib/tk/msgcat.rb, line 204
  def load_tk(dir)
    number(@namespace.eval{tk_call('::msgcat::mcload', dir)})
  end
locale()

[Source]

# File tk/lib/tk/msgcat.rb, line 170
  def locale
    @namespace.eval{tk_call('::msgcat::mclocale')}
  end
locale=(locale)

[Source]

# File tk/lib/tk/msgcat.rb, line 177
  def locale=(locale)
    @namespace.eval{tk_call('::msgcat::mclocale', locale)}
  end
maxlen(*src_strings)

[Source]

# File tk/lib/tk/msgcat.rb, line 163
  def maxlen(*src_strings)
    @namespace.eval{tk_call('::msgcat::mcmax', *src_strings).to_i}
  end
mc(*args)

Alias for translate

method_missing(id, *args)

[Source]

# File tk/lib/tk/msgcat.rb, line 103
  def method_missing(id, *args)
    # locale(src, trans) ==> set_translation(locale, src, trans)
    loc = id.id2name
    case args.length
    when 0 # set locale
      self.locale=(loc)

    when 1 # src only, or trans_list
      if args[0].kind_of?(Array)
        # trans_list
        #list = args[0].collect{|src, trans|
        #  [ Tk::UTF8_String.new(src), Tk::UTF8_String.new(trans) ]
        #}
        self.set_translation_list(loc, args[0])
      else
        # src
        #self.set_translation(loc, Tk::UTF8_String.new(args[0]))
        self.set_translation(loc, args[0])
      end

    when 2 # src and trans, or, trans_list and enc
      if args[0].kind_of?(Array)
      else
        #self.set_translation(loc, args[0], Tk::UTF8_String.new(args[1]))
        self.set_translation(loc, *args)
      end

    when 3 # src and trans and enc
      self.set_translation(loc, *args)

    else
      fail NameError, "undefined method `#{name}' for #{self.to_s}", error_at

    end
  end
preferences()

[Source]

# File tk/lib/tk/msgcat.rb, line 184
  def preferences
    tk_split_simplelist(@namespace.eval{tk_call('::msgcat::mcpreferences')})
  end
set_translation(locale, src_str, trans_str=None, enc='utf-8')

[Source]

# File tk/lib/tk/msgcat.rb, line 238
  def set_translation(locale, src_str, trans_str=None, enc='utf-8')
    if trans_str && trans_str != None
      trans_str = Tk.UTF8_String(_toUTF8(trans_str, enc))
      Tk.UTF8_String(@namespace.eval{
                       tk_call_without_enc('::msgcat::mcset',
                                           locale,
                                           _get_eval_string(src_str, true),
                                           trans_str)
                     })
    else
      Tk.UTF8_String(@namespace.eval{
                       tk_call_without_enc('::msgcat::mcset',
                                           locale,
                                           _get_eval_string(src_str, true))})
    end
  end
set_translation_list(locale, trans_list, enc='utf-8')

[Source]

# File tk/lib/tk/msgcat.rb, line 268
  def set_translation_list(locale, trans_list, enc='utf-8')
    # trans_list ::= [ [src, trans], [src, trans], ... ]
    list = []
    trans_list.each{|src, trans|
      if trans && trans != None
        list << _get_eval_string(src, true)
        list << Tk.UTF8_String(_toUTF8(trans, enc))
      else
        list << _get_eval_string(src, true) << ''
      end
    }
    number(@namespace.eval{
             tk_call_without_enc('::msgcat::mcmset', locale, list)
           })
  end
translate(*args)

[Source]

# File tk/lib/tk/msgcat.rb, line 150
  def translate(*args)
    dst = args.collect{|src|
      @namespace.eval{tk_call_without_enc('::msgcat::mc',
                                          _get_eval_string(src, true))}
    }
    Tk.UTF8_String(sprintf(*dst))
  end


Class: TkNamespace

Class | TkNamespace
In: | tk/lib/tk/namespace.rb
Parent: | TkObject

Methods

children children code code current current current_namespace delete delete ensemble_configinfo ensemble_configure ensemble_create ensemble_exist? eval eval exist? exist? export export export_with_clear export_with_clear force_import force_import forget forget get_path import import inscope inscope new ns_tk_call ns_tk_call_with_enc ns_tk_call_without_enc origin parent parent qualifiers set_path set_path tail tk_call tk_call_with_enc tk_call_without_enc which which_command which_variable

Classes and Modules

Class TkNamespace::Ensemble
Class TkNamespace::NsCode
Class TkNamespace::ScopeArgs

Constants

TkCommandNames | = | [ 'namespace'.freeze, ].freeze
Tk_Namespace_ID_TBL | = | TkCore::INTERP.create_table
Tk_Namespace_ID | = | ["ns".freeze, "00000".taint].freeze

External Aliases

tk_call | -> | __tk_call
tk_call_without_enc | -> | __tk_call_without_enc
tk_call_with_enc | -> | __tk_call_with_enc

Public Class methods

children(*args)

[Source]

# File tk/lib/tk/namespace.rb, line 224
  def self.children(*args)
    # args ::= [<namespace>] [<pattern>]
    # <pattern> must be glob-style pattern
    tk_split_simplelist(tk_call('namespace', 'children', *args)).collect{|ns|
      # ns is fullname
      if Tk_Namespace_ID_TBL.key?(ns)
        Tk_Namespace_ID_TBL[ns]
      else
        ns
      end
    }
  end
code(script = Proc.new)

[Source]

# File tk/lib/tk/namespace.rb, line 240
  def self.code(script = Proc.new)
    TkNamespace.new('').code(script)
  end
current()

[Source]

# File tk/lib/tk/namespace.rb, line 255
  def self.current
    tk_call('namespace', 'current')
  end
delete(*ns_list)

[Source]

# File tk/lib/tk/namespace.rb, line 264
  def self.delete(*ns_list)
    tk_call('namespace', 'delete', *ns_list)
  end
ensemble_configinfo(cmd, slot = nil)

[Source]

# File tk/lib/tk/namespace.rb, line 281
  def self.ensemble_configinfo(cmd, slot = nil)
    if slot
      tk_call('namespace', 'ensemble', 'configure', cmd, '-' + slot.to_s)
    else
      inf = {}
      Hash(*tk_split_simplelist(tk_call('namespace', 'ensemble', 'configure', cmd))).each{|k, v| inf[k[1..-1]] = v}
      inf
    end
  end
ensemble_configure(cmd, slot, value=None)

[Source]

# File tk/lib/tk/namespace.rb, line 274
  def self.ensemble_configure(cmd, slot, value=None)
    if slot.kind_of?(Hash)
      tk_call('namespace', 'ensemble', 'configure', cmd, *hash_kv(slot))
    else
      tk_call('namespace', 'ensemble', 'configure', cmd, '-'+slot.to_s, value)
    end
  end
ensemble_create(*keys)

[Source]

# File tk/lib/tk/namespace.rb, line 271
  def self.ensemble_create(*keys)
    tk_call('namespace', 'ensemble', 'create', *hash_kv(keys))
  end
ensemble_exist?(cmd)

[Source]

# File tk/lib/tk/namespace.rb, line 290
  def self.ensemble_exist?(cmd)
    bool(tk_call('namespace', 'ensemble', 'exists', cmd))
  end
eval(namespace, cmd = Proc.new, *args)

[Source]

# File tk/lib/tk/namespace.rb, line 294
  def self.eval(namespace, cmd = Proc.new, *args)
    #tk_call('namespace', 'eval', namespace, cmd, *args)
    TkNamespace.new(namespece).eval(cmd, *args)
  end
exist?(ns)

[Source]

# File tk/lib/tk/namespace.rb, line 308
  def self.exist?(ns)
    bool(tk_call('namespace', 'exists', ns))
  end
export(*patterns)

[Source]

# File tk/lib/tk/namespace.rb, line 315
  def self.export(*patterns)
    tk_call('namespace', 'export', *patterns)
  end
export_with_clear(*patterns)

[Source]

# File tk/lib/tk/namespace.rb, line 318
  def self.export_with_clear(*patterns)
    tk_call('namespace', 'export', '-clear', *patterns)
  end
force_import(*patterns)

[Source]

# File tk/lib/tk/namespace.rb, line 338
  def self.force_import(*patterns)
    tk_call('namespace', 'import', '-force', *patterns)
  end
forget(*patterns)

[Source]

# File tk/lib/tk/namespace.rb, line 328
  def self.forget(*patterns)
    tk_call('namespace', 'forget', *patterns)
  end
get_path()

[Source]

# File tk/lib/tk/namespace.rb, line 371
  def self.get_path
    tk_call('namespace', 'path')
  end
import(*patterns)

[Source]

# File tk/lib/tk/namespace.rb, line 335
  def self.import(*patterns)
    tk_call('namespace', 'import', *patterns)
  end
inscope(namespace, script, *args)

[Source]

# File tk/lib/tk/namespace.rb, line 348
  def self.inscope(namespace, script, *args)
    tk_call('namespace', 'inscope', namespace, script, *args)
  end
new(name = nil, parent = nil)

[Source]

# File tk/lib/tk/namespace.rb, line 182
  def initialize(name = nil, parent = nil)
    unless name
      # name = Tk_Namespace_ID.join('')
      name = Tk_Namespace_ID.join(TkCore::INTERP._ip_id_)
      Tk_Namespace_ID[1].succ!
    end
    name = __tk_call('namespace', 'current') if name == ''
    if parent
      if parent =~ /^::/
        if name =~ /^::/
          @fullname = parent + name
        else
          @fullname = parent +'::'+ name
        end
      else
        ancestor = __tk_call('namespace', 'current')
        ancestor = '' if ancestor == '::'
        if name =~ /^::/
          @fullname = ancestor + '::' + parent + name
        else
          @fullname = ancestor + '::'+ parent +'::'+ name
        end
      end
    else # parent == nil
      ancestor = __tk_call('namespace', 'current')
      ancestor = '' if ancestor == '::'
      if name =~ /^::/
        @fullname = name
      else
        @fullname = ancestor + '::' + name
      end
    end
    @path = @fullname
    @parent = __tk_call('namespace', 'qualifiers', @fullname)
    @name = __tk_call('namespace', 'tail', @fullname)

    # create namespace
    __tk_call('namespace', 'eval', @fullname, '')

    Tk_Namespace_ID_TBL[@fullname] = self
  end
origin(cmd)

[Source]

# File tk/lib/tk/namespace.rb, line 355
  def self.origin(cmd)
    tk_call('namespace', 'origin', cmd)
  end
parent(namespace=None)

[Source]

# File tk/lib/tk/namespace.rb, line 359
  def self.parent(namespace=None)
    ns = tk_call('namespace', 'parent', namespace)
    if Tk_Namespace_ID_TBL.key?(ns)
      Tk_Namespace_ID_TBL[ns]
    else
      ns
    end
  end
qualifiers(str)

[Source]

# File tk/lib/tk/namespace.rb, line 381
  def self.qualifiers(str)
    tk_call('namespace', 'qualifiers', str)
  end
set_path(*namespace_list)

[Source]

# File tk/lib/tk/namespace.rb, line 374
  def self.set_path(*namespace_list)
    tk_call('namespace', 'path', array2tk_list(namespace_list))
  end
tail(str)

[Source]

# File tk/lib/tk/namespace.rb, line 385
  def self.tail(str)
    tk_call('namespace', 'tail', str)
  end
which(name)

[Source]

# File tk/lib/tk/namespace.rb, line 389
  def self.which(name)
    tk_call('namespace', 'which', name)
  end
which_command(name)

[Source]

# File tk/lib/tk/namespace.rb, line 392
  def self.which_command(name)
    tk_call('namespace', 'which', '-command', name)
  end
which_variable(name)

[Source]

# File tk/lib/tk/namespace.rb, line 395
  def self.which_variable(name)
    tk_call('namespace', 'which', '-variable', name)
  end

Public Instance methods

children(pattern=None)

[Source]

# File tk/lib/tk/namespace.rb, line 236
  def children(pattern=None)
    TkNamespace.children(@fullname, pattern)
  end
code(script = Proc.new)

[Source]

# File tk/lib/tk/namespace.rb, line 243
  def code(script = Proc.new)
    if script.kind_of?(String)
      cmd = proc{|*args| ScopeArgs.new(@fullname,*args).instance_eval(script)}
    elsif script.kind_of?(Proc)
      cmd = proc{|*args| ScopeArgs.new(@fullname,*args).instance_eval(&script)}
    else
      fail ArgumentError, "String or Proc is expected"
    end
    TkNamespace::NsCode.new(tk_call_without_enc('namespace', 'code',
                                                _get_eval_string(cmd, false)))
  end
current()

Alias for current_namespace

current_namespace()

[Source]

# File tk/lib/tk/namespace.rb, line 258
  def current_namespace
    # ns_tk_call('namespace', 'current')
    @fullname
  end
delete()

[Source]

# File tk/lib/tk/namespace.rb, line 267
  def delete
    TkNamespece.delete(@fullname)
  end
eval(cmd = Proc.new, *args)

[Source]

# File tk/lib/tk/namespace.rb, line 298
  def eval(cmd = Proc.new, *args)
    #TkNamespace.eval(@fullname, cmd, *args)
    #ns_tk_call(cmd, *args)
    code_obj = code(cmd)
    ret = code_obj.call(*args)
    # uninstall_cmd(TkCore::INTERP._split_tklist(code_obj.path)[-1])
    uninstall_cmd(_fromUTF8(TkCore::INTERP._split_tklist(_toUTF8(code_obj.path))[-1]))
    ret
  end
exist?()

[Source]

# File tk/lib/tk/namespace.rb, line 311
  def exist?
    TkNamespece.delete(@fullname)
  end
export()

[Source]

# File tk/lib/tk/namespace.rb, line 321
  def export
    TkNamespace.export(@fullname)
  end
export_with_clear()

[Source]

# File tk/lib/tk/namespace.rb, line 324
  def export_with_clear
    TkNamespace.export_with_clear(@fullname)
  end
force_import()

[Source]

# File tk/lib/tk/namespace.rb, line 344
  def force_import
    TkNamespace.force_import(@fullname)
  end
forget()

[Source]

# File tk/lib/tk/namespace.rb, line 331
  def forget
    TkNamespace.forget(@fullname)
  end
import()

[Source]

# File tk/lib/tk/namespace.rb, line 341
  def import
    TkNamespace.import(@fullname)
  end
inscope(script, *args)

[Source]

# File tk/lib/tk/namespace.rb, line 351
  def inscope(script, *args)
    TkNamespace(@fullname, script, *args)
  end
ns_tk_call(*args)

Alias for tk_call

ns_tk_call_with_enc(*args)

Alias for tk_call_with_enc

ns_tk_call_without_enc(*args)

Alias for tk_call_without_enc

parent()

[Source]

# File tk/lib/tk/namespace.rb, line 367
  def parent
    tk_call('namespace', 'parent', @fullname)
  end
set_path()

[Source]

# File tk/lib/tk/namespace.rb, line 377
  def set_path
    tk_call('namespace', 'path', @fullname)
  end
tk_call(*args)

[Source]

# File tk/lib/tk/namespace.rb, line 160
  def tk_call(*args)
    #super('namespace', 'eval', @fullname, *args)
    args = args.collect{|arg| (s = _get_eval_string(arg, true))? s: ''}
    super('namespace', 'eval', @fullname,
          TkCore::INTERP._merge_tklist(*args))
  end
tk_call_with_enc(*args)

[Source]

# File tk/lib/tk/namespace.rb, line 172
  def tk_call_with_enc(*args)
    #super('namespace', 'eval', @fullname, *args)
    args = args.collect{|arg| (s = _get_eval_string(arg, true))? s: ''}
    super('namespace', 'eval', @fullname,
          TkCore::INTERP._merge_tklist(*args))
  end
tk_call_without_enc(*args)

[Source]

# File tk/lib/tk/namespace.rb, line 166
  def tk_call_without_enc(*args)
    #super('namespace', 'eval', @fullname, *args)
    args = args.collect{|arg| (s = _get_eval_string(arg, true))? s: ''}
    super('namespace', 'eval', @fullname,
          TkCore::INTERP._merge_tklist(*args))
  end


Class: TkNamespace::Ensemble

Class | TkNamespace::Ensemble
In: | tk/lib/tk/namespace.rb
Parent: | TkObject

Methods

cget configinfo exist? exists? new

Public Class methods

exist?(ensemble)

[Source]

# File tk/lib/tk/namespace.rb, line 44
    def self.exist?(ensemble)
      bool(tk_call('namespace', 'ensemble', 'exists', ensemble))
    end
new(keys = {})

[Source]

# File tk/lib/tk/namespace.rb, line 48
    def initialize(keys = {})
      @ensemble = @path = tk_call('namespace', 'ensemble', 'create', keys)
    end

Public Instance methods

cget(slot)

[Source]

# File tk/lib/tk/namespace.rb, line 52
    def cget(slot)
      if slot == :namespace || slot == 'namespace'
        ns = super(slot)
        if TkNamespace::Tk_Namespace_ID_TBL.key?(ns)
          TkNamespace::Tk_Namespace_ID_TBL[ns]
        else
          ns
        end
      else
        super(slot)
      end
    end
configinfo(slot = nil)

[Source]

# File tk/lib/tk/namespace.rb, line 65
    def configinfo(slot = nil)
      if slot
        if slot == :namespace || slot == 'namespace'
          val = super(slot)
          if TkNamespace::Tk_Namespace_ID_TBL.key?(val)
            val = TkNamespace::Tk_Namespace_ID_TBL[val]
          end
        else
          val = super(slot)
        end

        if TkComm::GET_CONFIGINFO_AS_ARRAY
          [slot.to_s, val]
        else # ! TkComm::GET_CONFIGINFO_AS_ARRAY
          {slot.to_s => val}
        end

      else
        info = super()

        if TkComm::GET_CONFIGINFO_AS_ARRAY
          info.map!{|inf|
            if inf[0] == 'namespace' &&
                TkNamespace::Tk_Namespace_ID_TBL.key?(inf[-1])
              [inf[0], TkNamespace::Tk_Namespace_ID_TBL[inf[-1]]]
            else
              inf
            end
          }
        else # ! TkComm::GET_CONFIGINFO_AS_ARRAY
          val = info['namespace']
          if TkNamespace::Tk_Namespace_ID_TBL.key?(val)
            info['namespace'] = TkNamespace::Tk_Namespace_ID_TBL[val]
          end
        end

        info
      end
    end
exists?()

[Source]

# File tk/lib/tk/namespace.rb, line 105
    def exists?
      bool(tk_call('namespace', 'ensemble', 'exists', @path))
    end


Class: TkNamespace::NsCode

Class | TkNamespace::NsCode
In: | tk/lib/tk/namespace.rb
Parent: | TkObject

Methods

call new path to_eval

Public Class methods

new(scope)

[Source]

# File tk/lib/tk/namespace.rb, line 143
    def initialize(scope)
      @scope = scope + ' '
    end

Public Instance methods

call(*args)

[Source]

# File tk/lib/tk/namespace.rb, line 152
    def call(*args)
      TkCore::INTERP._eval_without_enc(@scope + array2tk_list(args))
    end
path()

[Source]

# File tk/lib/tk/namespace.rb, line 146
    def path
      @scope
    end
to_eval()

[Source]

# File tk/lib/tk/namespace.rb, line 149
    def to_eval
      @scope
    end


Class: TkNamespace::ScopeArgs

Class | TkNamespace::ScopeArgs
In: | tk/lib/tk/namespace.rb
Parent: | Array

Methods

new tk_call tk_call_with_enc tk_call_without_enc

Included Modules

Tk

Public Class methods

new(namespace, *args)

[Source]

# File tk/lib/tk/namespace.rb, line 135
    def initialize(namespace, *args)
      @namespace = namespace
      super(args.size)
      self.replace(args)
    end

Public Instance methods

tk_call(*args)

alias __tk_call tk_call alias __tk_call_without_enc tk_call_without_enc alias __tk_call_with_enc tk_call_with_enc

[Source]

# File tk/lib/tk/namespace.rb, line 116
    def tk_call(*args)
      #super('namespace', 'eval', @namespace, *args)
      args = args.collect{|arg| (s = _get_eval_string(arg, true))? s: ''}
      super('namespace', 'eval', @namespace,
            TkCore::INTERP._merge_tklist(*args))
    end
tk_call_with_enc(*args)

[Source]

# File tk/lib/tk/namespace.rb, line 128
    def tk_call_with_enc(*args)
      #super('namespace', 'eval', @namespace, *args)
      args = args.collect{|arg| (s = _get_eval_string(arg, true))? s: ''}
      super('namespace', 'eval', @namespace,
            TkCore::INTERP._merge_tklist(*args))
    end
tk_call_without_enc(*args)

[Source]

# File tk/lib/tk/namespace.rb, line 122
    def tk_call_without_enc(*args)
      #super('namespace', 'eval', @namespace, *args)
      args = args.collect{|arg| (s = _get_eval_string(arg, true))? s: ''}
      super('namespace', 'eval', @namespace,
            TkCore::INTERP._merge_tklist(*args))
    end


Class: TkObject

Class | TkObject
In: | tk/tkutil.c tk/lib/tk.rb
Parent: | TkKernel

Methods

destroy epath event_generate method_missing path tk_send tk_send_to_list tk_send_to_list_with_enc tk_send_to_list_without_enc tk_send_to_simplelist tk_send_to_simplelist_with_enc tk_send_to_simplelist_without_enc tk_send_with_enc tk_send_without_enc to_eval

Included Modules

Tk TkConfigMethod TkBindCore

Public Instance methods

destroy()

[Source]

# File tk/lib/tk.rb, line 3814
  def destroy
    #tk_call 'trace', 'vdelete', @tk_vn, 'w', @var_id if @var_id
  end
epath()
 --> definition is moved to TkUtil module

def path

  @path

end

[Source]

# File tk/lib/tk.rb, line 3717
  def epath
    @path
  end
event_generate(context, keys=nil)

[Source]

# File tk/lib/tk.rb, line 3790
  def event_generate(context, keys=nil)
    if context.kind_of?(TkEvent::Event)
      context.generate(self, ((keys)? keys: {}))
    elsif keys
      #tk_call('event', 'generate', path,
      #       "<#{tk_event_sequence(context)}>", *hash_kv(keys))
      tk_call_without_enc('event', 'generate', path,
                          "<#{tk_event_sequence(context)}>",
                          *hash_kv(keys, true))
    else
      #tk_call('event', 'generate', path, "<#{tk_event_sequence(context)}>")
      tk_call_without_enc('event', 'generate', path,
                          "<#{tk_event_sequence(context)}>")
    end
  end
method_missing(id, *args)

[Source]

# File tk/lib/tk.rb, line 3755
  def method_missing(id, *args)
    name = id.id2name
    case args.length
    when 1
      if name[-1] == ?=
        configure name[0..-2], args[0]
        args[0]
      else
        configure name, args[0]
        self
      end
    when 0
      begin
        cget(name)
      rescue
        fail NameError,
             "undefined local variable or method `#{name}' for #{self.to_s}",
             error_at
      end
    else
      fail NameError, "undefined method `#{name}' for #{self.to_s}", error_at
    end
  end
path()

/

[Source]

/*************************************/

static VALUE
tkobj_path(self)
    VALUE self;
{
    return rb_ivar_get(self, ID_at_path);
}
tk_send(cmd, *rest)

[Source]

# File tk/lib/tk.rb, line 3725
  def tk_send(cmd, *rest)
    tk_call(path, cmd, *rest)
  end
tk_send_to_list(cmd, *rest)

private :tk_send, :tk_send_without_enc, :tk_send_with_enc

[Source]

# File tk/lib/tk.rb, line 3736
  def tk_send_to_list(cmd, *rest)
    tk_call_to_list(path, cmd, *rest)
  end
tk_send_to_list_with_enc(cmd, *rest)

[Source]

# File tk/lib/tk.rb, line 3742
  def tk_send_to_list_with_enc(cmd, *rest)
    tk_call_to_list_with_enc(path, cmd, *rest)
  end
tk_send_to_list_without_enc(cmd, *rest)

[Source]

# File tk/lib/tk.rb, line 3739
  def tk_send_to_list_without_enc(cmd, *rest)
    tk_call_to_list_without_enc(path, cmd, *rest)
  end
tk_send_to_simplelist(cmd, *rest)

[Source]

# File tk/lib/tk.rb, line 3745
  def tk_send_to_simplelist(cmd, *rest)
    tk_call_to_simplelist(path, cmd, *rest)
  end
tk_send_to_simplelist_with_enc(cmd, *rest)

[Source]

# File tk/lib/tk.rb, line 3751
  def tk_send_to_simplelist_with_enc(cmd, *rest)
    tk_call_to_simplelist_with_enc(path, cmd, *rest)
  end
tk_send_to_simplelist_without_enc(cmd, *rest)

[Source]

# File tk/lib/tk.rb, line 3748
  def tk_send_to_simplelist_without_enc(cmd, *rest)
    tk_call_to_simplelist_without_enc(path, cmd, *rest)
  end
tk_send_with_enc(cmd, *rest)

[Source]

# File tk/lib/tk.rb, line 3731
  def tk_send_with_enc(cmd, *rest)
    tk_call_with_enc(path, cmd, *rest)
  end
tk_send_without_enc(cmd, *rest)

[Source]

# File tk/lib/tk.rb, line 3728
  def tk_send_without_enc(cmd, *rest)
    tk_call_without_enc(path, cmd, *rest)
  end
to_eval()

[Source]

# File tk/lib/tk.rb, line 3721
  def to_eval
    @path
  end


Module: TkOptionDB

Module | TkOptionDB
In: | tk/lib/tk/optiondb.rb

Methods

__create_new_class __get_random_basename __remove_methods_of_proc_class add clear eval_under_random_base get new_proc_class new_proc_class_random read_entries read_file read_with_encoding readfile

Included Modules

Tk

Classes and Modules

Module TkOptionDB::Priority

Constants

TkCommandNames | = | ['option'.freeze].freeze
CmdClassID | = | ['CMD_CLASS'.freeze, '00000'.taint].freeze
RAND_BASE_CNT | = | [0]
RAND_BASE_HEAD | = | 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
RAND_BASE_CHAR | = | RAND_BASE_HEAD + 'abcdefghijklmnopqrstuvwxyz0123456789_'

Public Instance methods

__create_new_class(klass, func, safe = 4, add = false, parent = nil)

[Source]

# File tk/lib/tk/optiondb.rb, line 250
  def __create_new_class(klass, func, safe = 4, add = false, parent = nil)
    if klass.kind_of?(TkWindow)
      carrier = klass.path
      klass = CmdClassID.join(TkCore::INTERP._ip_id_)
      CmdClassID[1].succ!
      parent = nil # ignore parent
    else
      klass = klass.to_s if klass.kind_of?(Symbol)
      unless (?A..?Z) === klass[0]
        fail ArgumentError, "bad string '#{klass}' for class name"
      end
      if parent == nil
        install_win(nil)
      elsif parent.kind_of?(TkWindow)
        install_win(parent.path)
      elsif parent <= @@resource_proc_class
        install_win(parent::CARRIER)
      else
        fail ArgumentError, "parent must be Resource-Proc class"
      end
      carrier = Tk.tk_call_without_enc('frame', @path, '-class', klass)
    end

    unless func.kind_of?(Array)
      fail ArgumentError, "method-list must be Array"
    end
    func_str = func.join(' ')

    if parent.kind_of?(Class) && parent <= @@resource_proc_class
      cmd_klass = Class.new(parent)
    else
      cmd_klass = Class.new(TkOptionDB.module_eval('@@resource_proc_class'))
    end
    cmd_klass.const_set(:CARRIER, carrier.dup.freeze)

    cmd_klass.instance_variable_set('@method_tbl', TkCore::INTERP.create_table)
    cmd_klass.instance_variable_set('@add_method', add)
    cmd_klass.instance_variable_set('@safe_mode', safe)
    func.each{|f|
      cmd_klass.instance_variable_get('@method_tbl')[f.to_s.intern] = nil
    }
??

    cmd_klass
  end
__get_random_basename()

[Source]

# File tk/lib/tk/optiondb.rb, line 327
  def __get_random_basename
    name = '%s%03d' % [RAND_BASE_HEAD[rand(RAND_BASE_HEAD.size),1],
                       RAND_BASE_CNT[0]]
    len = RAND_BASE_CHAR.size
    (6+rand(10)).times{
      name << RAND_BASE_CHAR[rand(len),1]
    }
    RAND_BASE_CNT[0] = RAND_BASE_CNT[0] + 1
    name
  end
__remove_methods_of_proc_class(klass)

[Source]

# File tk/lib/tk/optiondb.rb, line 303
  def __remove_methods_of_proc_class(klass)
    # for security, make these methods invalid
    class << klass
      def __null_method(*args); nil; end
      [ :class_eval, :name, :superclass, :clone, :dup, :autoload, :autoload?,
        :ancestors, :const_defined?, :const_get, :const_set, :const_missing,
        :class_variables, :constants, :included_modules, :instance_methods,
        :method_defined?, :module_eval, :private_instance_methods,
        :protected_instance_methods, :public_instance_methods,
        :singleton_methods, :remove_const, :remove_method, :undef_method,
        :to_s, :inspect, :display, :method, :methods, :respond_to?,
        :instance_variable_get, :instance_variable_set, :instance_method,
        :instance_eval, :instance_variables, :kind_of?, :is_a?,
        :private_methods, :protected_methods, :public_methods ].each{|m|
        alias_method(m, :__null_method)
      }
    end
  end
add(pat, value, pri=None)

[Source]

# File tk/lib/tk/optiondb.rb, line 20
  def add(pat, value, pri=None)
    # if $SAFE >= 4
    #   fail SecurityError, "can't call 'TkOptionDB.add' at $SAFE >= 4"
    # end
    tk_call('option', 'add', pat, value, pri)
  end
clear()

[Source]

# File tk/lib/tk/optiondb.rb, line 26
  def clear
    # if $SAFE >= 4
    #   fail SecurityError, "can't call 'TkOptionDB.crear' at $SAFE >= 4"
    # end
    tk_call_without_enc('option', 'clear')
  end
eval_under_random_base(parent = nil, &b)

[Source]

# File tk/lib/tk/optiondb.rb, line 353
  def eval_under_random_base(parent = nil, &b)
    new_klass = __create_new_class(__get_random_basename(),
                                   [], 4, false, parent)
    ret = new_klass.class_eval(&b) if block_given?
    __remove_methods_of_proc_class(new_klass)
    new_klass.freeze
    ret
  end
get(win, name, klass)

[Source]

# File tk/lib/tk/optiondb.rb, line 32
  def get(win, name, klass)
    tk_call('option', 'get', win ,name, klass)
  end
new_proc_class(klass, func, safe = 4, add = false, parent = nil, &b)

define new proc class : If you want to modify the new class or create a new subclass, you must do such operation in the block parameter. Because the created class is flozen after evaluating the block.

[Source]

# File tk/lib/tk/optiondb.rb, line 344
  def new_proc_class(klass, func, safe = 4, add = false, parent = nil, &b)
    new_klass = __create_new_class(klass, func, safe, add, parent)
    new_klass.class_eval(&b) if block_given?
    __remove_methods_of_proc_class(new_klass)
    new_klass.freeze
    new_klass
  end
new_proc_class_random(klass, func, safe = 4, add = false, &b)

[Source]

# File tk/lib/tk/optiondb.rb, line 363
  def new_proc_class_random(klass, func, safe = 4, add = false, &b)
    eval_under_random_base(){
      TkOption.new_proc_class(klass, func, safe, add, self, &b)
    }
  end
read_entries(file, f_enc=nil)

[Source]

# File tk/lib/tk/optiondb.rb, line 41
  def read_entries(file, f_enc=nil)
    if TkCore::INTERP.safe?
      fail SecurityError,
        "can't call 'TkOptionDB.read_entries' on a safe interpreter"
    end

    i_enc = ((Tk.encoding)? Tk.encoding : Tk.encoding_system)

    unless f_enc
      f_enc = i_enc
    end

    ent = []
    cline = ''
    open(file, 'r') {|f|
      while line = f.gets
        #cline += line.chomp!
        cline.concat(line.chomp!)
        case cline
        when /\\$/    # continue
          cline.chop!
          next
        when /^\s*(!|#)/     # coment
          cline = ''
          next
        when /^([^:]+):(.*)$/
          pat = $1.strip
          val = $2.lstrip
          p "ResourceDB: #{[pat, val].inspect}" if $DEBUG
          pat = TkCore::INTERP._toUTF8(pat, f_enc)
          pat = TkCore::INTERP._fromUTF8(pat, i_enc)
          val = TkCore::INTERP._toUTF8(val, f_enc)
          val = TkCore::INTERP._fromUTF8(val, i_enc)
          ent << [pat, val]
          cline = ''
        else          # unknown --> ignore
          cline = ''
          next
        end
      end
    }
    ent
  end
read_file(file, pri=None)

Alias for readfile

read_with_encoding(file, f_enc=nil, pri=None)

[Source]

# File tk/lib/tk/optiondb.rb, line 86
  def read_with_encoding(file, f_enc=nil, pri=None)
    # try to read the file as an OptionDB file
    read_entries(file, f_enc).each{|pat, val|
      add(pat, val, pri)
    }

??
  end
readfile(file, pri=None)

[Source]

# File tk/lib/tk/optiondb.rb, line 35
  def readfile(file, pri=None)
    tk_call('option', 'readfile', file, pri)
  end


Module: TkOptionDB::Priority

Module | TkOptionDB::Priority
In: | tk/lib/tk/optiondb.rb

Constants

WidgetDefault | = | 20
StartupFile | = | 40
UserDefault | = | 60
Interactive | = | 80


Class: TkOptionMenubutton

Class | TkOptionMenubutton
In: | tk/lib/tk/menu.rb
Parent: | TkMenubutton

Methods

activate add current_entryconfiginfo current_menuconfiginfo delete entrycget entryconfiginfo entryconfigure index insert invoke menu menucget menuconfiginfo menuconfigure new value value= yposition

Classes and Modules

Class TkOptionMenubutton::OptionMenu

Constants

TkCommandNames = ['tk_optionMenu'.freeze].freeze

Public Class methods

new(*args)

[Source]

# File tk/lib/tk/menu.rb, line 455
  def initialize(*args)
    # args :: [parent,] [var,] [value[, ...],] [keys]
    #    parent --> TkWindow or nil
    #    var    --> TkVariable or nil
    #    keys   --> Hash
    #       keys[:parent] or keys['parent']     --> parent
    #       keys[:variable] or keys['variable'] --> var
    #       keys[:values] or keys['values']     --> value, ...
    #       other Hash keys are menubutton options
    keys = {}
    keys = args.pop if args[-1].kind_of?(Hash)
    keys = _symbolkey2str(keys)

    parent = nil
    if args[0].kind_of?(TkWindow) || args[0] == nil
      keys.delete('parent') # ignore
      parent = args.shift
    else
      parent = keys.delete('parent')
    end

    @variable = nil
    if args[0].kind_of?(TkVariable) || args[0] == nil
      keys.delete('variable') # ignore
      @variable = args.shift
    else
      @variable = keys.delete('variable')
    end
    @variable = TkVariable.new unless @variable

    (args = keys.delete('values') || []) if args.empty?
    if args.empty?
      args << @variable.value
    else
      @variable.value = args[0]
    end

    install_win(if parent then parent.path end)
    @menu = OptionMenu.new(tk_call('tk_optionMenu',
                                   @path, @variable.id, *args))

    configure(keys) if keys
  end

Public Instance methods

activate(index)

[Source]

# File tk/lib/tk/menu.rb, line 507
  def activate(index)
    @menu.activate(index)
    self
  end
add(value)

[Source]

# File tk/lib/tk/menu.rb, line 511
  def add(value)
    @menu.add('radiobutton', 'variable'=>@variable,
              'label'=>value, 'value'=>value)
    self
  end
current_entryconfiginfo(index, key=nil)

[Source]

# File tk/lib/tk/menu.rb, line 560
  def current_entryconfiginfo(index, key=nil)
    @menu.current_entryconfiginfo(index, key)
  end
current_menuconfiginfo(key=nil)

[Source]

# File tk/lib/tk/menu.rb, line 547
  def current_menuconfiginfo(key=nil)
    @menu.current_configinfo(key)
  end
delete(index, last=None)

[Source]

# File tk/lib/tk/menu.rb, line 527
  def delete(index, last=None)
    @menu.delete(index, last)
    self
  end
entrycget(index, key)

[Source]

# File tk/lib/tk/menu.rb, line 550
  def entrycget(index, key)
    @menu.entrycget(index, key)
  end
entryconfiginfo(index, key=nil)

[Source]

# File tk/lib/tk/menu.rb, line 557
  def entryconfiginfo(index, key=nil)
    @menu.entryconfiginfo(index, key)
  end
entryconfigure(index, key, val=None)

[Source]

# File tk/lib/tk/menu.rb, line 553
  def entryconfigure(index, key, val=None)
    @menu.entryconfigure(index, key, val)
    self
  end
index(index)

[Source]

# File tk/lib/tk/menu.rb, line 516
  def index(index)
    @menu.index(index)
  end
insert(index, value)

[Source]

# File tk/lib/tk/menu.rb, line 522
  def insert(index, value)
    @menu.insert(index, 'radiobutton', 'variable'=>@variable,
              'label'=>value, 'value'=>value)
    self
  end
invoke(index)

[Source]

# File tk/lib/tk/menu.rb, line 519
  def invoke(index)
    @menu.invoke(index)
  end
menu()

[Source]

# File tk/lib/tk/menu.rb, line 534
  def menu
    @menu
  end
menucget(key)

[Source]

# File tk/lib/tk/menu.rb, line 537
  def menucget(key)
    @menu.cget(key)
  end
menuconfiginfo(key=nil)

[Source]

# File tk/lib/tk/menu.rb, line 544
  def menuconfiginfo(key=nil)
    @menu.configinfo(key)
  end
menuconfigure(key, val=None)

[Source]

# File tk/lib/tk/menu.rb, line 540
  def menuconfigure(key, val=None)
    @menu.configure(key, val)
    self
  end
value()

[Source]

# File tk/lib/tk/menu.rb, line 499
  def value
    @variable.value
  end
value=(val)

[Source]

# File tk/lib/tk/menu.rb, line 503
  def value=(val)
    @variable.value = val
  end
yposition(index)

[Source]

# File tk/lib/tk/menu.rb, line 531
  def yposition(index)
    @menu.yposition(index)
  end


Class: TkOptionMenubutton::OptionMenu

Class | TkOptionMenubutton::OptionMenu
In: | tk/lib/tk/menu.rb
Parent: | TkMenu

Methods

new

Public Class methods

new(path)

[Source]

# File tk/lib/tk/menu.rb, line 448
    def initialize(path)  #==> return value of tk_optionMenu
      @path = path
      #TkComm::Tk_WINDOWS[@path] = self
      TkCore::INTERP.tk_windows[@path] = self
    end


Module: TkPack

Module | TkPack
In: | tk/lib/tk/pack.rb

Methods

configure forget info pack propagate slaves

Included Modules

Tk

Constants

TkCommandNames = ['pack'.freeze].freeze

Public Instance methods

configure(win, *args)

[Source]

# File tk/lib/tk/pack.rb, line 12
  def configure(win, *args)
    if args[-1].kind_of?(Hash)
      opts = args.pop
    else
      opts = {}
    end
    params = []
    # params.push((win.kind_of?(TkObject))? win.epath: win)
    params.push(_epath(win))
    args.each{|win|
      # params.push((win.kind_of?(TkObject))? win.epath: win)
      params.push(_epath(win))
    }
    opts.each{|k, v|
      params.push("-#{k}")
      # params.push((v.kind_of?(TkObject))? v.epath: v)
      params.push(_epath(v))
    }
    tk_call_without_enc("pack", 'configure', *params)
  end
forget(*args)

[Source]

# File tk/lib/tk/pack.rb, line 34
  def forget(*args)
    return '' if args.size == 0
    wins = args.collect{|win|
      # (win.kind_of?(TkObject))? win.epath: win
      _epath(win)
    }
    tk_call_without_enc('pack', 'forget', *wins)
  end
info(slave)

[Source]

# File tk/lib/tk/pack.rb, line 43
  def info(slave)
    # slave = slave.epath if slave.kind_of?(TkObject)
    slave = _epath(slave)
    ilist = list(tk_call_without_enc('pack', 'info', slave))
    info = {}
    while key = ilist.shift
      info[key[1..-1]] = ilist.shift
    end
    return info
  end
pack(win, *args)

Alias for configure

propagate(master, mode=None)

[Source]

# File tk/lib/tk/pack.rb, line 54
  def propagate(master, mode=None)
    # master = master.epath if master.kind_of?(TkObject)
    master = _epath(master)
    if mode == None
      bool(tk_call_without_enc('pack', 'propagate', master))
    else
      tk_call_without_enc('pack', 'propagate', master, mode)
    end
  end
slaves(master)

[Source]

# File tk/lib/tk/pack.rb, line 64
  def slaves(master)
    # master = master.epath if master.kind_of?(TkObject)
    master = _epath(master)
    list(tk_call_without_enc('pack', 'slaves', master))
  end


Module: TkPackage

Module | TkPackage
In: | tk/lib/tk/package.rb

Methods

add_path forget if_needed names present present_exact provide require require_exact unknown_proc vcompare versions vsatisfies

Included Modules

TkCore

Constants

TkCommandNames = ['package'.freeze].freeze

Public Instance methods

add_path(path)

[Source]

# File tk/lib/tk/package.rb, line 12
  def add_path(path)
    Tk::AUTO_PATH.value = Tk::AUTO_PATH.to_a << path
  end
forget(package)

[Source]

# File tk/lib/tk/package.rb, line 16
  def forget(package)
    tk_call('package', 'forget', package)
    nil
  end
if_needed(pkg, ver, *arg, &b)

[Source]

# File tk/lib/tk/package.rb, line 21
  def if_needed(pkg, ver, *arg, &b)
    size = arg.size

    if size==0 && !b
      # proc info
      procedure(tk_call('package', 'ifneeded', pkg, ver))

    elsif size==0 && b
      # set proc
      cmd = proc(&b)
      tk_call('package', 'ifneeded', pkg, ver, cmd)
      cmd

    elsif size==1 && !b
      # set proc
      cmd = arg[0]
      if cmd
        tk_call('package', 'ifneeded', pkg, ver, cmd)
        cmd
      else
        # remove proc
        tk_call('package', 'ifneeded', pkg, ver, '')
        nil
      end

    else
      fail ArgumentError, 'too many arguments'
    end
  end
names()

[Source]

# File tk/lib/tk/package.rb, line 51
  def names
    tk_split_simplelist(tk_call('package', 'names'))
  end
present(package, version=None)

[Source]

# File tk/lib/tk/package.rb, line 66
  def present(package, version=None)
    begin
      tk_call('package', 'present', package, version)
    rescue => e
      fail e.class, 'TkPackage ' << e.message
    end
  end
present_exact(package, version)

[Source]

# File tk/lib/tk/package.rb, line 74
  def present_exact(package, version)
    begin
      tk_call('package', 'present', '-exact', package, version)
    rescue => e
      fail e.class, 'TkPackage ' << e.message
    end
  end
provide(package, version=nil)

[Source]

# File tk/lib/tk/package.rb, line 55
  def provide(package, version=nil)
    if version
      tk_call('package', 'provide', package, version)
    end
    if (ret = tk_call('package', 'provide', package)) == ''
      nil
    else
      ret
    end
  end
require(package, version=None)

[Source]

# File tk/lib/tk/package.rb, line 82
  def require(package, version=None)
    begin
      tk_call('package', 'require', package, version)
    rescue => e
      fail e.class, 'TkPackage ' << e.message
    end
  end
require_exact(package, version)

[Source]

# File tk/lib/tk/package.rb, line 90
  def require_exact(package, version)
    begin
      tk_call('package', 'require', '-exact', package, version)
    rescue => e
      fail e.class, 'TkPackage ' << e.message
    end
  end
unknown_proc(*arg, &b)

[Source]

# File tk/lib/tk/package.rb, line 98
  def unknown_proc(*arg, &b)
    size = arg.size

    if size==0 && !b
      # proc info
      procedure(tk_call('package', 'unknown'))

    elsif size==0 && b
      # set proc
      cmd = proc(&b)
      tk_call('package', 'unknown', cmd)
      cmd

    elsif size==1 && !b
      # set proc
      cmd = arg[0]
      if cmd
        tk_call('package', 'unknown', cmd)
        cmd
      else
        # remove proc
        tk_call('package', 'unknown', '')
        nil
      end

    else
      fail ArgumentError, 'too many arguments'
    end
  end
vcompare(version1, version2)

[Source]

# File tk/lib/tk/package.rb, line 132
  def vcompare(version1, version2)
    number(tk_call('package', 'vcompare', version1, version2))
  end
versions(package)

[Source]

# File tk/lib/tk/package.rb, line 128
  def versions(package)
    tk_split_simplelist(tk_call('package', 'versions', package))
  end
vsatisfies(version1, version2)

[Source]

# File tk/lib/tk/package.rb, line 136
  def vsatisfies(version1, version2)
    bool(tk_call('package', 'vsatisfies', version1, version2))
  end


Module: TkPalette

Module | TkPalette
In: | tk/lib/tk/palette.rb

Methods

bisque darken recolorTree recolorTree set setPalette

Included Modules

Tk

Constants

TkCommandNames = [ 'tk_setPalette'.freeze, 'tk_bisque'.freeze, 'tkDarken'.freeze

Public Class methods

bisque()

[Source]

# File tk/lib/tk/palette.rb, line 25
  def TkPalette.bisque
    tk_call('tk_bisque')
  end
darken(color, percent)

[Source]

# File tk/lib/tk/palette.rb, line 29
  def TkPalette.darken(color, percent)
    tk_call('tkDarken', color, percent)
  end
recolorTree(win, colors)

[Source]

# File tk/lib/tk/palette.rb, line 33
  def TkPalette.recolorTree(win, colors)
    if not colors.kind_of?(Hash)
      fail "2nd arg need to be Hash"
    end

    tk_call('global', "tkPalette")
    colors.each{|key, value|
      begin
        if win.cget(key) == tk_call('set', "tkPalette(#{key})")
          win[key] = colors[key]
        end
      rescue
        # ignore
      end
    }

    TkWinfo.children(win).each{|w| TkPalette.recolorTree(w, colors)}
  end
set(*args)

[Source]

# File tk/lib/tk/palette.rb, line 17
  def TkPalette.set(*args)
    args = args.to_a.flatten if args.kind_of? Hash
    tk_call('tk_setPalette', *args)
  end
setPalette(*args)

[Source]

# File tk/lib/tk/palette.rb, line 21
  def TkPalette.setPalette(*args)
    TkPalette.set(*args)
  end

Public Instance methods

recolorTree(colors)

[Source]

# File tk/lib/tk/palette.rb, line 52
  def recolorTree(colors)
    TkPalette.recolorTree(self, colors)
  end


Class: TkPanedWindow

Class | TkPanedWindow
In: | tk/lib/tk/panedwindow.rb
Parent: | TkWindow

Methods

add current_pane_configinfo current_paneconfiginfo del delete forget identify pane_config pane_configinfo panecget paneconfiginfo paneconfigure panes proxy_coord proxy_forget proxy_place remove sash_coord sash_dragto sash_mark sash_place

Constants

TkCommandNames | = | ['panedwindow'.freeze].freeze
WidgetClassName | = | 'Panedwindow'.freeze

Public Instance methods

add(*args)

def create_self(keys)

  if keys and keys != None
    tk_call_without_enc('panedwindow', @path, *hash_kv(keys, true))
  else
    tk_call_without_enc('panedwindow', @path)
  end

end private :create_self

[Source]

# File tk/lib/tk/panedwindow.rb, line 19
  def add(*args)
    keys = args.pop
    fail ArgumentError, "no window in arguments" unless keys
    if keys && keys.kind_of?(Hash)
      fail ArgumentError, "no window in arguments" if args == []
      # args = args.collect{|w| (w.kind_of?(TkObject))? w.epath: w }
      args = args.collect{|w| _epath(w) }
      #args.push(hash_kv(keys))
      args.concat(hash_kv(keys))
    else
      args.push(keys) if keys
      # args = args.collect{|w| (w.kind_of?(TkObject))? w.epath: w }
      args = args.collect{|w| _epath(w) }
    end
    tk_send_without_enc('add', *args)
    self
  end
current_pane_configinfo(win, key=nil)

Alias for current_paneconfiginfo

current_paneconfiginfo(win, key=nil)

[Source]

# File tk/lib/tk/panedwindow.rb, line 205
  def current_paneconfiginfo(win, key=nil)
    if TkComm::GET_CONFIGINFO_AS_ARRAY
      if key
        conf = paneconfiginfo(win, key)
        {conf[0] => conf[4]}
      else
        ret = {}
        paneconfiginfo(win).each{|conf|
          ret[conf[0]] = conf[4] if conf.size > 2
        }
        ret
      end
    else # ! TkComm::GET_CONFIGINFO_AS_ARRAY
      ret = {}
      paneconfiginfo(win, key).each{|k, conf|
        ret[k] = conf[-1] if conf.kind_of?(Array)
      }
      ret
    end
  end
del(win, *wins)

Alias for forget

delete(win, *wins)

Alias for forget

forget(win, *wins)

[Source]

# File tk/lib/tk/panedwindow.rb, line 37
  def forget(win, *wins)
    wins.unshift(win)
    # tk_send_without_enc('forget', *((w.kind_of?(TkObject))? w.epath: w))
    tk_send_without_enc('forget', *(wins.collect{|w| _epath(w)}))
    self
  end
identify(x, y)

[Source]

# File tk/lib/tk/panedwindow.rb, line 47
  def identify(x, y)
    list(tk_send_without_enc('identify', x, y))
  end
pane_config(win, key, value=nil)

Alias for paneconfigure

pane_configinfo(win, key=nil)

Alias for paneconfiginfo

panecget(win, key)

[Source]

# File tk/lib/tk/panedwindow.rb, line 79
  def panecget(win, key)
    # win = win.epath if win.kind_of?(TkObject)
    win = _epath(win)
    tk_tcl2ruby(tk_send_without_enc('panecget', win, "-#{key}"))
  end
paneconfiginfo(win, key=nil)

[Source]

# File tk/lib/tk/panedwindow.rb, line 105
  def paneconfiginfo(win, key=nil)
    if TkComm::GET_CONFIGINFO_AS_ARRAY
      # win = win.epath if win.kind_of?(TkObject)
      win = _epath(win)
      if key
        #conf = tk_split_list(tk_send_without_enc('paneconfigure',
        #                                         win, "-#{key}"))
        conf = tk_split_list(tk_send_without_enc('paneconfigure',
                                                 win, "-#{key}"),
                             false, true)
        conf[0] = conf[0][1..-1]
        if conf[0] == 'hide'
          conf[3] = bool(conf[3]) unless conf[3].empty?
          conf[4] = bool(conf[4]) unless conf[4].empty?
        end
        conf
      else
        #tk_split_simplelist(tk_send_without_enc('paneconfigure',
        #                                        win)).collect{|conflist|
        #  conf = tk_split_simplelist(conflist)
        tk_split_simplelist(tk_send_without_enc('paneconfigure', win),
                            false, false).collect{|conflist|
          conf = tk_split_simplelist(conflist, false, true)
          conf[0] = conf[0][1..-1]
          if conf[3]
            if conf[0] == 'hide'
              conf[3] = bool(conf[3]) unless conf[3].empty?
            elsif conf[3].index('{')
              conf[3] = tk_split_list(conf[3])
            else
              conf[3] = tk_tcl2ruby(conf[3])
            end
          end
          if conf[4]
            if conf[0] == 'hide'
              conf[4] = bool(conf[4]) unless conf[4].empty?
            elsif conf[4].index('{')
              conf[4] = tk_split_list(conf[4])
            else
              conf[4] = tk_tcl2ruby(conf[4])
            end
          end
          conf[1] = conf[1][1..-1] if conf.size == 2 # alias info
          conf
        }
      end
    else # ! TkComm::GET_CONFIGINFO_AS_ARRAY
      # win = win.epath if win.kind_of?(TkObject)
      win = _epath(win)
      if key
        #conf = tk_split_list(tk_send_without_enc('paneconfigure',
        #                                         win, "-#{key}"))
        conf = tk_split_list(tk_send_without_enc('paneconfigure',
                                                 win, "-#{key}"),
                             false, true)
        key = conf.shift[1..-1]
        if key == 'hide'
          conf[2] = bool(conf[2]) unless conf[2].empty?
          conf[3] = bool(conf[3]) unless conf[3].empty?
        end
        { key => conf }
      else
        ret = {}
        #tk_split_simplelist(tk_send_without_enc('paneconfigure',
        #                                        win)).each{|conflist|
        #  conf = tk_split_simplelist(conflist)
        tk_split_simplelist(tk_send_without_enc('paneconfigure', win),
                            false, false).each{|conflist|
          conf = tk_split_simplelist(conflist, false, true)
          key = conf.shift[1..-1]
          if key
            if key == 'hide'
              conf[2] = bool(conf[2]) unless conf[2].empty?
            elsif conf[2].index('{')
              conf[2] = tk_split_list(conf[2])
            else
              conf[2] = tk_tcl2ruby(conf[2])
            end
          end
          if conf[3]
            if key == 'hide'
              conf[3] = bool(conf[3]) unless conf[3].empty?
            elsif conf[3].index('{')
              conf[3] = tk_split_list(conf[3])
            else
              conf[3] = tk_tcl2ruby(conf[3])
            end
          end
          if conf.size == 1
            ret[key] = conf[0][1..-1]  # alias info
          else
            ret[key] = conf
          end
        }
        ret
      end
    end
  end
paneconfigure(win, key, value=nil)

[Source]

# File tk/lib/tk/panedwindow.rb, line 85
  def paneconfigure(win, key, value=nil)
    # win = win.epath if win.kind_of?(TkObject)
    win = _epath(win)
    if key.kind_of? Hash
      params = []
      key.each{|k, v|
        params.push("-#{k}")
        # params.push((v.kind_of?(TkObject))? v.epath: v)
        params.push(_epath(v))
      }
      tk_send_without_enc('paneconfigure', win, *params)
    else
      # value = value.epath if value.kind_of?(TkObject)
      value = _epath(value)
      tk_send_without_enc('paneconfigure', win, "-#{key}", value)
    end
    self
  end
panes()

[Source]

# File tk/lib/tk/panedwindow.rb, line 228
  def panes
    list(tk_send_without_enc('panes'))
  end
proxy_coord()

[Source]

# File tk/lib/tk/panedwindow.rb, line 51
  def proxy_coord
    list(tk_send_without_enc('proxy', 'coord'))
  end
proxy_forget()

[Source]

# File tk/lib/tk/panedwindow.rb, line 54
  def proxy_forget
    tk_send_without_enc('proxy', 'forget')
    self
  end
proxy_place(x, y)

[Source]

# File tk/lib/tk/panedwindow.rb, line 58
  def proxy_place(x, y)
    tk_send_without_enc('proxy', 'place', x, y)
    self
  end
remove(win, *wins)

Alias for forget

sash_coord(index)

[Source]

# File tk/lib/tk/panedwindow.rb, line 63
  def sash_coord(index)
    list(tk_send('sash', 'coord', index))
  end
sash_dragto(index)

[Source]

# File tk/lib/tk/panedwindow.rb, line 66
  def sash_dragto(index)
    tk_send('sash', 'dragto', index, x, y)
    self
  end
sash_mark(index, x, y)

[Source]

# File tk/lib/tk/panedwindow.rb, line 70
  def sash_mark(index, x, y)
    tk_send('sash', 'mark', index, x, y)
    self
  end
sash_place(index, x, y)

[Source]

# File tk/lib/tk/panedwindow.rb, line 74
  def sash_place(index, x, y)
    tk_send('sash', 'place', index, x, y)
    self
  end


Class: TkPhotoImage

Class | TkPhotoImage
In: | tk/lib/tk/image.rb
Parent: | TkImage

Methods

blank cget copy data get get_transparency new put read redither set_transparency write

Constants

NullArgOptionKeys = [ "shrink", "grayscale" ]

Public Class methods

new(*args)

[Source]

# File tk/lib/tk/image.rb, line 128
  def initialize(*args)
    @type = 'photo'
    super(*args)
  end

Public Instance methods

blank()

[Source]

# File tk/lib/tk/image.rb, line 133
  def blank
    tk_send_without_enc('blank')
    self
  end
cget(option)

[Source]

# File tk/lib/tk/image.rb, line 138
  def cget(option)
    case option.to_s
    when 'data', 'file'
      tk_send 'cget', '-' << option.to_s
    else
      tk_tcl2ruby(tk_send('cget', '-' << option.to_s))
    end
  end
copy(src, *opts)

[Source]

# File tk/lib/tk/image.rb, line 147
  def copy(src, *opts)
    if opts.size == 0
      tk_send('copy', src)
    elsif opts.size == 1 && opts[0].kind_of?(Hash)
      tk_send('copy', src, *_photo_hash_kv(opts[0]))
    else
      # for backward compatibility
      args = opts.collect{|term|
        if term.kind_of?(String) && term.include?(?\s)
          term.split
        else
          term
        end
      }.flatten
      tk_send('copy', src, *args)
    end
    self
  end
data(keys={})

[Source]

# File tk/lib/tk/image.rb, line 166
  def data(keys={})
    #tk_send('data', *_photo_hash_kv(keys))
    tk_split_list(tk_send('data', *_photo_hash_kv(keys)))
  end
get(x, y)

[Source]

# File tk/lib/tk/image.rb, line 171
  def get(x, y)
    tk_send('get', x, y).split.collect{|n| n.to_i}
  end
get_transparency(x, y)

[Source]

# File tk/lib/tk/image.rb, line 211
  def get_transparency(x, y)
    bool(tk_send('transparency', 'get', x, y))
  end
put(data, *opts)

[Source]

# File tk/lib/tk/image.rb, line 175
  def put(data, *opts)
    if opts == []
      tk_send('put', data)
    elsif opts.size == 1 && opts[0].kind_of?(Hash)
      tk_send('put', data, *_photo_hash_kv(opts[0]))
    else
      # for backward compatibility
      tk_send('put', data, '-to', *opts)
    end
    self
  end
read(file, *opts)

[Source]

# File tk/lib/tk/image.rb, line 187
  def read(file, *opts)
    if opts.size == 0
      tk_send('read', file)
    elsif opts.size == 1 && opts[0].kind_of?(Hash)
      tk_send('read', file, *_photo_hash_kv(opts[0]))
    else
      # for backward compatibility
      args = opts.collect{|term|
        if term.kind_of?(String) && term.include?(?\s)
          term.split
        else
          term
        end
      }.flatten
      tk_send('read', file, *args)
    end
    self
  end
redither()

[Source]

# File tk/lib/tk/image.rb, line 206
  def redither
    tk_send 'redither'
    self
  end
set_transparency(x, y, st)

[Source]

# File tk/lib/tk/image.rb, line 214
  def set_transparency(x, y, st)
    tk_send('transparency', 'set', x, y, st)
    self
  end
write(file, *opts)

[Source]

# File tk/lib/tk/image.rb, line 219
  def write(file, *opts)
    if opts.size == 0
      tk_send('write', file)
    elsif opts.size == 1 && opts[0].kind_of?(Hash)
      tk_send('write', file, *_photo_hash_kv(opts[0]))
    else
      # for backward compatibility
      args = opts.collect{|term|
        if term.kind_of?(String) && term.include?(?\s)
          term.split
        else
          term
        end
      }.flatten
      tk_send('write', file, *args)
    end
    self
  end


Class: TkPixmapImage

Class | TkPixmapImage
In: | tk/lib/tkextlib/tkimg/pixmap.rb
Parent: | TkImage

Methods

new version

Public Class methods

new(*args)

[Source]

# File tk/lib/tkextlib/tkimg/pixmap.rb, line 40
  def initialize(*args)
    @type = 'pixmap'
    super(*args)
  end
version()

[Source]

# File tk/lib/tkextlib/tkimg/pixmap.rb, line 36
  def self.version
    Tk::Img::PIXMAP.version
  end


Module: TkPlace

Module | TkPlace
In: | tk/lib/tk/place.rb

Methods

configinfo configure current_configinfo forget info place slaves

Included Modules

Tk

Constants

TkCommandNames = ['place'.freeze].freeze

Public Instance methods

configinfo(win, slot = nil)

[Source]

# File tk/lib/tk/place.rb, line 32
  def configinfo(win, slot = nil)
    # for >= Tk8.4a2 ?
    if TkComm::GET_CONFIGINFOwoRES_AS_ARRAY
      # win = win.epath if win.kind_of?(TkObject)
      win = _epath(win)
      if slot
        #conf = tk_split_list(tk_call_without_enc('place', 'configure',
        #                                        win, "-#{slot}") )
        conf = tk_split_simplelist(tk_call_without_enc('place', 'configure',
                                                       win, "-#{slot}") )
        conf[0] = conf[0][1..-1]
        conf[1] = tk_tcl2ruby(conf[1])
        conf[2] = tk_tcl2ruby(conf[1])
        conf[3] = tk_tcl2ruby(conf[1])
        conf[4] = tk_tcl2ruby(conf[1])
        conf
      else
        tk_split_simplelist(tk_call_without_enc('place', 'configure',
                                                win)).collect{|conflist|
          #conf = list(conflist)
          conf = simplelist(conflist).collect!{|inf| tk_tcl2ruby(inf)}
          conf[0] = conf[0][1..-1]
          conf
        }
      end
    else # ! TkComm::GET_CONFIGINFOwoRES_AS_ARRAY
      current_configinfo(win, slot)
    end
  end
configure(win, slot, value=None)

[Source]

# File tk/lib/tk/place.rb, line 12
  def configure(win, slot, value=None)
    # for >= Tk8.4a2 ?
    # win = win.epath if win.kind_of?(TkObject)
    win = _epath(win)
    if slot.kind_of? Hash
      params = []
      slot.each{|k, v|
        params.push("-#{k}")
        # params.push((v.kind_of?(TkObject))? v.epath: v)
        params.push(_epath(v))
      }
      tk_call_without_enc('place', 'configure', win, *params)
    else
      # value = value.epath if value.kind_of?(TkObject)
      value = _epath(value)
      tk_call_without_enc('place', 'configure', win, "-#{slot}", value)
    end
  end
current_configinfo(win, slot = nil)

[Source]

# File tk/lib/tk/place.rb, line 62
  def current_configinfo(win, slot = nil)
    # win = win.epath if win.kind_of?(TkObject)
    win = _epath(win)
    if slot
      #conf = tk_split_list(tk_call_without_enc('place', 'configure',
      #                                         win, "-#{slot}") )
      conf = tk_split_simplelist(tk_call_without_enc('place', 'configure',
                                                     win, "-#{slot}") )
      # { conf[0][1..-1] => conf[1] }
      { conf[0][1..-1] => tk_tcl2ruby(conf[4]) }
    else
      ret = {}
      #tk_split_list(tk_call_without_enc('place','configure',win)).each{|conf|
      tk_split_simplelist(tk_call_without_enc('place', 'configure',
                                              win)).each{|conf_list|
        #ret[conf[0][1..-1]] = conf[1]
        conf = simplelist(conf_list)
        ret[conf[0][1..-1]] = tk_tcl2ruby(conf[4])
      }
      ret
    end
  end
forget(win)

[Source]

# File tk/lib/tk/place.rb, line 85
  def forget(win)
    # win = win.epath if win.kind_of?(TkObject)
    win = _epath(win)
    tk_call_without_enc('place', 'forget', win)
  end
info(win)

[Source]

# File tk/lib/tk/place.rb, line 91
  def info(win)
    # win = win.epath if win.kind_of?(TkObject)
    win = _epath(win)
    #ilist = list(tk_call_without_enc('place', 'info', win))
    ilist = simplelist(tk_call_without_enc('place', 'info', win))
    info = {}
    while key = ilist.shift
      #info[key[1..-1]] = ilist.shift
      info[key[1..-1]] = tk_tcl2ruby(ilist.shift)
    end
    return info
  end
place(win, slot, value=None)

Alias for configure

slaves(master)

[Source]

# File tk/lib/tk/place.rb, line 104
  def slaves(master)
    # master = master.epath if master.kind_of?(TkObject)
    master = _epath(master)
    list(tk_call('place', 'slaves', master))
  end


Class: TkRTTimer

Class | TkRTTimer
In: | tk/lib/tk/timer.rb
Parent: | TkTimer

Methods

cancel cb_call continue new set_interval set_next_callback start stop

Constants

DEFAULT_OFFSET_LIST_SIZE = 5

Public Class methods

new(*args, &b)

[Source]

# File tk/lib/tk/timer.rb, line 511
  def initialize(*args, &b)
    super(*args, &b)

    @offset_list = Array.new(DEFAULT_OFFSET_LIST_SIZE){ [0, 0] }
    @offset_s = 0
    @offset_u = 0
    @est_time = nil
  end

Public Instance methods

cancel()

[Source]

# File tk/lib/tk/timer.rb, line 527
  def cancel
    super()
    @est_time = nil
    @cb_start_time = Time.now
    self
  end
cb_call()

[Source]

# File tk/lib/tk/timer.rb, line 614
  def cb_call
    if @est_time
      @offset_list.shift

      @cb_start_time = Time.now

      if @current_sleep == 0
        @offset_list.push([
                            @offset_s - @cb_start_time.to_i,
                            @offset_u - @cb_start_time.usec
                          ])
      else
        @offset_list.push([
                            @offset_s + (@est_time.to_i - @cb_start_time.to_i),
                            @offset_u + (@est_time.usec - @cb_start_time.usec)
                          ])
      end
    end

    @cb_cmd.call
  end
continue(wait=nil)

[Source]

# File tk/lib/tk/timer.rb, line 535
  def continue(wait=nil)
    fail RuntimeError, "is already running" if @running
    @cb_start_time = Time.now
    super(wait)
  end
set_interval(interval)

[Source]

# File tk/lib/tk/timer.rb, line 541
  def set_interval(interval)
    super(interval)
    @est_time = nil
  end
set_next_callback(args)

[Source]

# File tk/lib/tk/timer.rb, line 562
  def set_next_callback(args)
    if @running == false || @proc_max == 0 || @do_loop == 0
      Tk_CBTBL.delete(@id) ;# for GC
      @running = false
      @wait_var.value = 0
      return
    end
    if @current_pos >= @proc_max
      if @do_loop < 0 || (@do_loop -= 1) > 0
        @current_pos = 0
      else
        Tk_CBTBL.delete(@id) ;# for GC
        @running = false
        @wait_var.value = 0
        return
      end
    end

    @current_args = args

    cmd, *cmd_args = @loop_proc[@current_pos]
    @current_pos += 1
    @current_proc = cmd

    @offset_s, @offset_u = _offset_ave

    if TkComm._callback_entry?(@sleep_time)
      sleep = @sleep_time.call(self)
    else
      sleep = @sleep_time
    end

    if @est_time
      @est_time = Time.at(@est_time.to_i, @est_time.usec + sleep*1000)
    else
      @est_time = Time.at(@cb_start_time.to_i,
                          @cb_start_time.usec + sleep*1000)
    end

    now = Time.now
    real_sleep = ((@est_time.to_i - now.to_i + @offset_s)*1000.0 +
                  (@est_time.usec - now.usec + @offset_u)/1000.0).round
    if real_sleep <= 0
      real_sleep = 0
      @offset_s = now.to_i
      @offset_u = now.usec
    end
    @current_sleep = real_sleep

    set_callback(real_sleep, cmd_args)
  end
start(*args, &b)

[Source]

# File tk/lib/tk/timer.rb, line 520
  def start(*args, &b)
    return nil if @running
    @est_time = nil
    @cb_start_time = Time.now
    super(*args, &b)
  end
stop()

Alias for cancel


Class: TkRadioButton

Class | TkRadioButton
In: | tk/lib/tk/radiobutton.rb
Parent: | TkButton

Methods

deselect get_value select set_value

Constants

TkCommandNames | = | ['radiobutton'.freeze].freeze
WidgetClassName | = | 'Radiobutton'.freeze

Public Instance methods

deselect()

[Source]

# File tk/lib/tk/radiobutton.rb, line 38
  def deselect
    tk_send_without_enc('deselect')
    self
  end
get_value()

[Source]

# File tk/lib/tk/radiobutton.rb, line 47
  def get_value
    var = tk_send_without_enc('cget', '-variable')
    if TkVariable::USE_TCLs_SET_VARIABLE_FUNCTIONS
      _fromUTF8(INTERP._get_global_var(var))
    else
      INTERP._eval(Kernel.format('global %s; set %s', var, var))
    end
  end
select()

[Source]

# File tk/lib/tk/radiobutton.rb, line 42
  def select
    tk_send_without_enc('select')
    self
  end
set_value(val)

[Source]

# File tk/lib/tk/radiobutton.rb, line 56
  def set_value(val)
    var = tk_send_without_enc('cget', '-variable')
    if TkVariable::USE_TCLs_SET_VARIABLE_FUNCTIONS
      _fromUTF8(INTERP._set_global_var(var, _get_eval_string(val, true)))
    else
      s = '"' + _get_eval_string(val).gsub(/[\[\]$"\\]/, '\\\\\&') + '"'
      INTERP._eval(Kernel.format('global %s; set %s %s', var, var, s))
    end
  end


Class: TkRoot

Class | TkRoot
In: | tk/lib/tkextlib/tktrans/tktrans.rb tk/lib/tk/root.rb
Parent: | Object

Methods

add_menu add_menubar destroy new path tktrans_get_image tktrans_set_image to_eval

Included Modules

Wm TkMenuSpec

Constants

WidgetClassName = 'Tk'.freeze

Public Class methods

destroy()

[Source]

# File tk/lib/tk/root.rb, line 105
  def TkRoot.destroy
    TkCore::INTERP._invoke('destroy', '.')
  end
new(keys=nil, &b)

[Source]

# File tk/lib/tk/root.rb, line 38
  def TkRoot.new(keys=nil, &b)
    unless TkCore::INTERP.tk_windows['.']
      TkCore::INTERP.tk_windows['.'] =
        super(:without_creating=>true, :widgetname=>'.'){}
    end
    root = TkCore::INTERP.tk_windows['.']

    keys = _symbolkey2str(keys)

    # wm commands
    root.instance_eval{
      __methodcall_optkeys.each{|key, method|
        value = keys.delete(key.to_s)
        self.__send__(method, value) if value
      }
    }

    if keys  # wm commands ( for backward comaptibility )
      keys.each{|k,v|
        if v.kind_of? Array
          root.__send__(k,*v)
        else
          root.__send__(k,v)
        end
      }
    end

    root.instance_eval(&b) if block_given?
    root
  end
to_eval()

[Source]

# File tk/lib/tk/root.rb, line 72
  def self.to_eval
    # self::WidgetClassName
    '.'
  end

Public Instance methods

add_menu(menu_info, tearoff=false, opts=nil)

[Source]

# File tk/lib/tk/root.rb, line 86
  def add_menu(menu_info, tearoff=false, opts=nil)
    # See tk/menuspec.rb for menu_info.
    # opts is a hash of default configs for all of cascade menus.
    # Configs of menu_info can override it.
    if tearoff.kind_of?(Hash)
      opts = tearoff
      tearoff = false
    end
    _create_menubutton(self, menu_info, tearoff, opts)
  end
add_menubar(menu_spec, tearoff=false, opts=nil)

[Source]

# File tk/lib/tk/root.rb, line 97
  def add_menubar(menu_spec, tearoff=false, opts=nil)
    # See tk/menuspec.rb for menu_spec.
    # opts is a hash of default configs for all of cascade menus.
    # Configs of menu_spec can override it.
    menu_spec.each{|info| add_menu(info, tearoff, opts)}
    self.menu
  end
path()

[Source]

# File tk/lib/tk/root.rb, line 82
  def path
    "."
  end
tktrans_get_image()

[Source]

# File tk/lib/tkextlib/tktrans/tktrans.rb, line 49
  def tktrans_get_image()
    tk_send('tktrans::settoplevel', @path)
  end
tktrans_set_image(img)

[Source]

# File tk/lib/tkextlib/tktrans/tktrans.rb, line 45
  def tktrans_set_image(img)
    tk_send('tktrans::settoplevel', @path, img)
    self
  end


Class: TkScale

Class | TkScale
In: | tk/lib/tk/scale.rb
Parent: | TkWindow

Methods

command configure configure_cmd coords get identify set value value=

Constants

TkCommandNames | = | ['scale'.freeze].freeze
WidgetClassName | = | 'Scale'.freeze

Public Instance methods

command(cmd=Proc.new)

[Source]

# File tk/lib/tk/scale.rb, line 58
  def command(cmd=Proc.new)
    configure('command'=>cmd)
  end
configure(slot, value=None)

[Source]

# File tk/lib/tk/scale.rb, line 47
  def configure(slot, value=None)
    if (slot == 'command' || slot == :command)
      configure('command'=>value)
    elsif slot.kind_of?(Hash) &&
        (slot.key?('command') || slot.key?(:command))
      slot = _symbolkey2str(slot)
      slot['command'] = _wrap_command_arg(slot.delete('command'))
    end
    super(slot, value)
  end
configure_cmd(slot, value)

[Source]

# File tk/lib/tk/scale.rb, line 43
  def configure_cmd(slot, value)
    configure(slot=>value)
  end
coords(val=None)

[Source]

# File tk/lib/tk/scale.rb, line 66
  def coords(val=None)
    tk_split_list(tk_send_without_enc('coords', val))
  end
get(x=None, y=None)

[Source]

# File tk/lib/tk/scale.rb, line 62
  def get(x=None, y=None)
    number(tk_send_without_enc('get', x, y))
  end
identify(x, y)

[Source]

# File tk/lib/tk/scale.rb, line 70
  def identify(x, y)
    tk_send_without_enc('identify', x, y)
  end
set(val)

[Source]

# File tk/lib/tk/scale.rb, line 74
  def set(val)
    tk_send_without_enc('set', val)
  end
value()

[Source]

# File tk/lib/tk/scale.rb, line 78
  def value
    get
  end
value=(val)

[Source]

# File tk/lib/tk/scale.rb, line 82
  def value= (val)
    set(val)
    val
  end


Class: TkScrollbar

Class | TkScrollbar
In: | tk/lib/tkextlib/tcllib/autoscroll.rb tk/lib/tk/scrollbar.rb
Parent: | Object

Methods

activate assign assigned_list autoscroll configure delta fraction get identify propagate_set set unautoscroll

Constants

TkCommandNames | = | ['scrollbar'.freeze].freeze
WidgetClassName | = | 'Scrollbar'.freeze

Public Instance methods

activate(element=None)

[Source]

# File tk/lib/tk/scrollbar.rb, line 103
  def activate(element=None)
    tk_send_without_enc('activate', element)
  end
assign(*wins)

[Source]

# File tk/lib/tk/scrollbar.rb, line 41
  def assign(*wins)
    begin
      self.command(@scroll_proc) if self.cget('command').cmd != @scroll_proc
    rescue Exception
      self.command(@scroll_proc)
    end
    orient = self.orient
    wins.each{|w|
      @assigned << w unless @assigned.index(w)
      if orient == 'horizontal'
        w.xscrollcommand proc{|first, last| self.propagate_set(w, first, last)}
      else # 'vertical'
        w.yscrollcommand proc{|first, last| self.propagate_set(w, first, last)}
      end
    }
    Tk.update  # avoid scrollbar trouble
    self
  end
assigned_list()

[Source]

# File tk/lib/tk/scrollbar.rb, line 60
  def assigned_list
    begin
      return @assigned.dup if self.cget('command').cmd == @scroll_proc
    rescue Exception
    end
    fail RuntimeError, "not depend on the assigned_list"
  end
autoscroll()

[Source]

# File tk/lib/tkextlib/tcllib/autoscroll.rb, line 112
  def autoscroll
    # Arranges for the already existing scrollbar to be mapped
    # and unmapped as needed.
    #tk_call_without_enc('::autoscroll::autoscroll', @path)
    Tk::Tcllib::Autoscroll.autoscroll(self)
    self
  end
configure(*args)

[Source]

# File tk/lib/tk/scrollbar.rb, line 68
  def configure(*args)
    ret = super(*args)
    # Tk.update  # avoid scrollbar trouble
    ret
  end
delta(deltax, deltay)

def delta(deltax=None, deltay=None)

[Source]

# File tk/lib/tk/scrollbar.rb, line 75
  def delta(deltax, deltay)
    number(tk_send_without_enc('delta', deltax, deltay))
  end
fraction(x, y)

def fraction(x=None, y=None)

[Source]

# File tk/lib/tk/scrollbar.rb, line 80
  def fraction(x, y)
    number(tk_send_without_enc('fraction', x, y))
  end
get()

[Source]

# File tk/lib/tk/scrollbar.rb, line 88
  def get
    #ary1 = tk_send('get').split
    #ary2 = []
    #for i in ary1
    #  ary2.push number(i)
    #end
    #ary2
    list(tk_send_without_enc('get'))
  end
identify(x, y)

[Source]

# File tk/lib/tk/scrollbar.rb, line 84
  def identify(x, y)
    tk_send_without_enc('identify', x, y)
  end
propagate_set(src_win, first, last)

[Source]

# File tk/lib/tk/scrollbar.rb, line 32
  def propagate_set(src_win, first, last)
    self.set(first, last)
    if self.orient == 'horizontal'
      @assigned.each{|w| w.xview('moveto', first) if w != src_win}
    else # 'vertical'
      @assigned.each{|w| w.yview('moveto', first) if w != src_win}
    end
  end
set(first, last)

[Source]

# File tk/lib/tk/scrollbar.rb, line 98
  def set(first, last)
    tk_send_without_enc('set', first, last)
    self
  end
unautoscroll()

[Source]

# File tk/lib/tkextlib/tcllib/autoscroll.rb, line 119
  def unautoscroll
    #     Returns the scrollbar to its original static state.
    #tk_call_without_enc('::autoscroll::unautoscroll', @path)
    Tk::Tcllib::Autoscroll.unautoscroll(self)
    self
  end


Class: TkScrollbox

Class | TkScrollbox
In: | tk/lib/tk/scrollbox.rb
Parent: | TkListbox

Included Modules

TkComposite


Module: TkSelection

Module | TkSelection
In: | tk/lib/tk/selection.rb

Methods

clear clear clear_on_display get get get_on_display get_owner get_owner get_owner_on_display handle handle set_owner set_owner

Included Modules

Tk

Constants

TkCommandNames = ['selection'.freeze].freeze

Public Class methods

clear(sel=nil)

[Source]

# File tk/lib/tk/selection.rb, line 12
  def self.clear(sel=nil)
    if sel
      tk_call_without_enc('selection', 'clear', '-selection', sel)
    else
      tk_call_without_enc('selection', 'clear')
    end
  end
clear_on_display(win, sel=nil)

[Source]

# File tk/lib/tk/selection.rb, line 19
  def self.clear_on_display(win, sel=nil)
    if sel
      tk_call_without_enc('selection', 'clear',
                          '-displayof', win, '-selection', sel)
    else
      tk_call_without_enc('selection', 'clear', '-displayof', win)
    end
  end
get(keys=nil)

[Source]

# File tk/lib/tk/selection.rb, line 32
  def self.get(keys=nil)
    #tk_call('selection', 'get', *hash_kv(keys))
    _fromUTF8(tk_call_without_enc('selection', 'get', *hash_kv(keys)))
  end
get_on_display(win, keys=nil)

[Source]

# File tk/lib/tk/selection.rb, line 36
  def self.get_on_display(win, keys=nil)
    #tk_call('selection', 'get', '-displayof', win, *hash_kv(keys))
    _fromUTF8(tk_call_without_enc('selection', 'get', '-displayof',
                                  win, *hash_kv(keys)))
  end
get_owner(sel=nil)

[Source]

# File tk/lib/tk/selection.rb, line 59
  def self.get_owner(sel=nil)
    if sel
      window(tk_call_without_enc('selection', 'own', '-selection', sel))
    else
      window(tk_call_without_enc('selection', 'own'))
    end
  end
get_owner_on_display(win, sel=nil)

[Source]

# File tk/lib/tk/selection.rb, line 66
  def self.get_owner_on_display(win, sel=nil)
    if sel
      window(tk_call_without_enc('selection', 'own',
                                 '-displayof', win, '-selection', sel))
    else
      window(tk_call_without_enc('selection', 'own', '-displayof', win))
    end
  end
handle(win, func=Proc.new, keys=nil, &b)

[Source]

# File tk/lib/tk/selection.rb, line 45
  def self.handle(win, func=Proc.new, keys=nil, &b)
    if func.kind_of?(Hash) && keys == nil
      keys = func
      func = Proc.new(&b)
    end
    args = ['selection', 'handle']
    args.concat(hash_kv(keys))
    args.concat([win, func])
    tk_call_without_enc(*args)
  end
set_owner(win, keys=nil)

[Source]

# File tk/lib/tk/selection.rb, line 79
  def self.set_owner(win, keys=nil)
    tk_call_without_enc('selection', 'own', *(hash_kv(keys) << win))
  end

Public Instance methods

clear(sel=nil)

[Source]

# File tk/lib/tk/selection.rb, line 27
  def clear(sel=nil)
    TkSelection.clear_on_display(self, sel)
    self
  end
get(keys=nil)

[Source]

# File tk/lib/tk/selection.rb, line 41
  def get(keys=nil)
    TkSelection.get_on_display(self, sel)
  end
get_owner(sel=nil)

[Source]

# File tk/lib/tk/selection.rb, line 74
  def get_owner(sel=nil)
    TkSelection.get_owner_on_display(self, sel)
    self
  end
handle(func=Proc.new, keys=nil, &b)

[Source]

# File tk/lib/tk/selection.rb, line 55
  def handle(func=Proc.new, keys=nil, &b)
    TkSelection.handle(self, func, keys, &b)
  end
set_owner(keys=nil)

[Source]

# File tk/lib/tk/selection.rb, line 82
  def set_owner(keys=nil)
    TkSelection.set_owner(self, keys)
    self
  end


Class: TkSpinbox

Class | TkSpinbox
In: | tk/lib/tk/spinbox.rb
Parent: | TkEntry

Methods

__validation_class_list identify set spindown spinup

Classes and Modules

Class TkSpinbox::SpinCommand

Constants

TkCommandNames | = | ['spinbox'.freeze].freeze
WidgetClassName | = | 'Spinbox'.freeze

Public Instance methods

__validation_class_list()

[Source]

# File tk/lib/tk/spinbox.rb, line 53
  def __validation_class_list
    super() << SpinCommand
  end
identify(x, y)

[Source]

# File tk/lib/tk/spinbox.rb, line 82
  def identify(x, y)
    tk_send_without_enc('identify', x, y)
  end
set(str)

[Source]

# File tk/lib/tk/spinbox.rb, line 96
  def set(str)
    _fromUTF8(tk_send_without_enc('set', _get_eval_enc_str(str)))
  end
spindown()

[Source]

# File tk/lib/tk/spinbox.rb, line 91
  def spindown
    tk_send_without_enc('invoke', 'spindown')
    self
  end
spinup()

[Source]

# File tk/lib/tk/spinbox.rb, line 86
  def spinup
    tk_send_without_enc('invoke', 'spinup')
    self
  end


Class: TkSpinbox::SpinCommand

Class | TkSpinbox::SpinCommand
In: | tk/lib/tk/spinbox.rb
Parent: | TkValidateCommand

Methods

_config_keys

Classes and Modules

Class TkSpinbox::SpinCommand::ValidateArgs

Public Class methods

_config_keys()

[Source]

# File tk/lib/tk/spinbox.rb, line 48
    def self._config_keys
      ['command']
    end


Class: TkSpinbox::SpinCommand::ValidateArgs

Class | TkSpinbox::SpinCommand::ValidateArgs
In: | tk/lib/tk/spinbox.rb
Parent: | TkUtil::CallbackSubst

Methods

ret_val

Constants

KEY_TBL | = | [ [ ?d, ?s, :direction ], [ ?s, ?e, :current ], [ ?W, ?w, :widget ], nil
PROC_TBL | = | [ [ ?s, TkComm.method(:string) ], [ ?w, TkComm.method(:window) ], [ ?e, proc{|val| #enc = Tk.encoding enc = ((Tk.encoding)? Tk.encoding : Tk.encoding_system)

Public Class methods

ret_val(val)

[Source]

# File tk/lib/tk/spinbox.rb, line 43
      def self.ret_val(val)
        (val)? '1': '0'
      end


Class: TkSysMenu_Apple

Class | TkSysMenu_Apple
In: | tk/lib/tk/menu.rb
Parent: | TkMenu

Included Modules

TkSystemMenu

Constants

SYSMENU_NAME = 'apple'


Class: TkSysMenu_Help

Class | TkSysMenu_Help
In: | tk/lib/tk/menu.rb
Parent: | TkMenu

Included Modules

TkSystemMenu

Constants

SYSMENU_NAME = 'help'


Class: TkSysMenu_System

Class | TkSysMenu_System
In: | tk/lib/tk/menu.rb
Parent: | TkMenu

Included Modules

TkSystemMenu

Constants

SYSMENU_NAME = 'system'


Module: TkSystemMenu

Module | TkSystemMenu
In: | tk/lib/tk/menu.rb

Methods

new

Public Class methods

new(parent, keys=nil)

[Source]

# File tk/lib/tk/menu.rb, line 374
  def initialize(parent, keys=nil)
    if parent.kind_of? Hash
      keys = _symbolkey2str(parent)
      parent = keys.delete('parent')
    end
    #unless parent.kind_of? TkMenu
    #  fail ArgumentError, "parent must be a TkMenu object"
    #end
    # @path = Kernel.format("%s.%s", parent.path, self.class::SYSMENU_NAME)
    @path = parent.path + '.' + self.class::SYSMENU_NAME
    #TkComm::Tk_WINDOWS[@path] = self
    TkCore::INTERP.tk_windows[@path] = self
    if self.method(:create_self).arity == 0
      p 'create_self has no arg' if $DEBUG
      create_self
      configure(keys) if keys
    else
      p 'create_self has an arg' if $DEBUG
      create_self(keys)
    end
  end


Class: TkText

Class | TkText
In: | tk/lib/tk/text.rb
Parent: | TkTextWin

Methods

__destroy_hook__ _addcmd _addtag add_tag addtag at at backspace bbox clear compare count count_info current_image_configinfo debug debug= delete_tag deltag destroy dlineinfo dump dump_all dump_image dump_mark dump_tag dump_text dump_window edit_redo edit_reset edit_separator edit_undo erase get_displaychars image_cget image_configinfo image_configure image_names index init_instance_variable insert mark_gravity mark_names mark_next mark_previous mark_set mark_unset modified modified= modified? new next_mark peer_names previous_mark replace rsearch rsearch_with_length search search_with_length set_current set_insert set_mark tag_add tag_bind tag_bind_append tag_bind_remove tag_bindinfo tag_delete tag_lower tag_names tag_nextrange tag_prevrange tag_raise tag_ranges tag_remove tagid2obj text_copy text_cut text_paste tksearch tksearch_with_count unset_mark value value= window_names xview_pickplace yview_pickplace

Included Modules

TkTextTagConfig Scrollable

Classes and Modules

Module TkText::IndexModMethods
Class TkText::IndexString
Class TkText::Peer

Constants

ItemConfCMD | = | ['tag'.freeze, 'configure'.freeze].freeze
TkCommandNames | = | ['text'.freeze].freeze
WidgetClassName | = | 'Text'.freeze

Public Class methods

at(x, y)

[Source]

# File tk/lib/tk/text.rb, line 195
  def self.at(x, y)
    TkText::IndexString.at(x, y)
  end
new(*args) {|| ...}

[Source]

# File tk/lib/tk/text.rb, line 159
  def self.new(*args, &block)
    obj = super(*args){}
    obj.init_instance_variable
    obj.instance_eval(&block) if defined? yield
    obj
  end

Public Instance methods

__destroy_hook__()

[Source]

# File tk/lib/tk/text.rb, line 171
  def __destroy_hook__
    TkTextTag::TTagID_TBL.delete(@path)
    TkTextMark::TMarkID_TBL.delete(@path)
  end
_addcmd(cmd)

[Source]

# File tk/lib/tk/text.rb, line 229
  def _addcmd(cmd)
    @cmdtbl.push cmd
  end
_addtag(name, obj)

[Source]

# File tk/lib/tk/text.rb, line 233
  def _addtag(name, obj)
    @tags[name] = obj
  end
add_tag(tag, index1, index2=None)

Alias for tag_add

addtag(tag, index1, index2=None)

Alias for tag_add

at(x, y)

[Source]

# File tk/lib/tk/text.rb, line 199
  def at(x, y)
    TkText::IndexString.at(x, y)
  end
backspace()

[Source]

# File tk/lib/tk/text.rb, line 487
  def backspace
    self.delete 'insert'
  end
bbox(index)

[Source]

# File tk/lib/tk/text.rb, line 491
  def bbox(index)
    list(tk_send_without_enc('bbox', _get_eval_enc_str(index)))
  end
clear()

[Source]

# File tk/lib/tk/text.rb, line 223
  def clear
    tk_send_without_enc('delete', "1.0", 'end')
    self
  end
compare(idx1, op, idx2)

[Source]

# File tk/lib/tk/text.rb, line 495
  def compare(idx1, op, idx2)
    bool(tk_send_without_enc('compare', _get_eval_enc_str(idx1),
                             op, _get_eval_enc_str(idx2)))
  end
count(idx1, idx2, *opts)

[Source]

# File tk/lib/tk/text.rb, line 500
  def count(idx1, idx2, *opts)
    # opts are Tk8.5 feature
    cnt = 0
    args = opts.collect{|opt|
      str = opt.to_s
      cnt += 1 if str != 'update'
      '-' + str
    }
    args << _get_eval_enc_str(idx1) << _get_eval_enc_str(idx2)
    if cnt <= 1
      number(tk_send_without_enc('count', *opts))
    else
      list(tk_send_without_enc('count', *opts))
    end
  end
count_info(idx1, idx2, update=true)

[Source]

# File tk/lib/tk/text.rb, line 516
  def count_info(idx1, idx2, update=true)
    # Tk8.5 feature
    opts = [
      :chars, :displaychars, :displayindices, :displaylines,
      :indices, :lines, :xpixels, :ypixels
    ]
    if update
      lst = count(idx1, idx2, :update, *opts)
    else
      lst = count(idx1, idx2, *opts)
    end
    info = {}
    opts.each_with_index{|key, idx| info[key] = lst[idx]}
    info
  end
current_image_configinfo(index, slot = nil)

[Source]

# File tk/lib/tk/text.rb, line 422
  def current_image_configinfo(index, slot = nil)
    if TkComm::GET_CONFIGINFO_AS_ARRAY
      if slot
        conf = image_configinfo(index, slot)
        {conf[0] => conf[4]}
      else
        ret = {}
        image_configinfo(index).each{|conf|
          ret[conf[0]] = conf[4] if conf.size > 2
        }
        ret
      end
    else # ! TkComm::GET_CONFIGINFO_AS_ARRAY
      ret = {}
      image_configinfo(index, slot).each{|k, conf|
        ret[k] = conf[-1] if conf.kind_of?(Array)
      }
      ret
    end
  end
debug()

[Source]

# File tk/lib/tk/text.rb, line 542
  def debug
    bool(tk_send_without_enc('debug'))
  end
debug=(boolean)

[Source]

# File tk/lib/tk/text.rb, line 545
  def debug=(boolean)
    tk_send_without_enc('debug', boolean)
    #self
    boolean
  end
delete_tag(*tags)

Alias for tag_delete

deltag(*tags)

Alias for tag_delete

destroy()

[Source]

# File tk/lib/tk/text.rb, line 479
  def destroy
    @tags = {} unless @tags
    @tags.each_value do |t|
      t.destroy
    end
    super()
  end
dlineinfo(index)

[Source]

# File tk/lib/tk/text.rb, line 551
  def dlineinfo(index)
    list(tk_send_without_enc('dlineinfo', _get_eval_enc_str(index)))
  end
dump(type_info, *index, &block)

[Source]

# File tk/lib/tk/text.rb, line 1299
  def dump(type_info, *index, &block)
    if type_info.kind_of?(Symbol)
      type_info = [ type_info.to_s ]
    elsif type_info.kind_of?(String)
      type_info = [ type_info ]
    end
    args = type_info.collect{|inf| '-' + inf}
    args << '-command' << block if block
    str = tk_send('dump', *(args + index))
    result = []
    sel = nil
    i = 0
    while i < str.size
      # retrieve key
      idx = str.index(/ /, i)
      result.push str[i..(idx-1)]
      i = idx + 1

      # retrieve value
      case result[-1]
      when 'text'
        if str[i] == ?{
          # text formed as {...}
          val, i = _retrieve_braced_text(str, i)
          result.push val
        else
          # text which may contain backslahes
          val, i = _retrieve_backslashed_text(str, i)
          result.push val
        end
      else
        idx = str.index(/ /, i)
        val = str[i..(idx-1)]
        case result[-1]
        when 'mark'
          case val
          when 'insert'
            result.push TkTextMarkInsert.new(self)
          when 'current'
            result.push TkTextMarkCurrent.new(self)
          when 'anchor'
            result.push TkTextMarkAnchor.new(self)
          else
            result.push tk_tcl2ruby(val)
          end
        when 'tagon'
          if val == 'sel'
            if sel
              result.push sel
            else
              result.push TkTextTagSel.new(self)
            end
          else
            result.push tk_tcl2ruby(val)
          end
        when 'tagoff'
            result.push tk_tcl2ruby(val)
        when 'window'
          result.push tk_tcl2ruby(val)
        when 'image'
          result.push tk_tcl2ruby(val)
        end
        i = idx + 1
      end

      # retrieve index
      idx = str.index(/ /, i)
      if idx
        result.push(TkText::IndexString.new(str[i..(idx-1)]))
        i = idx + 1
      else
        result.push(TkText::IndexString.new(str[i..-1]))
        break
      end
    end

    kvis = []
    until result.empty?
      kvis.push [result.shift, result.shift, result.shift]
    end
    kvis  # result is [[key1, value1, index1], [key2, value2, index2], ...]
  end
dump_all(*index, &block)

[Source]

# File tk/lib/tk/text.rb, line 1418
  def dump_all(*index, &block)
    dump(['all'], *index, &block)
  end
dump_image(*index, &block)

[Source]

# File tk/lib/tk/text.rb, line 1433
  def dump_image(*index, &block)
    dump(['image'], *index, &block)
  end
dump_mark(*index, &block)

[Source]

# File tk/lib/tk/text.rb, line 1421
  def dump_mark(*index, &block)
    dump(['mark'], *index, &block)
  end
dump_tag(*index, &block)

[Source]

# File tk/lib/tk/text.rb, line 1424
  def dump_tag(*index, &block)
    dump(['tag'], *index, &block)
  end
dump_text(*index, &block)

[Source]

# File tk/lib/tk/text.rb, line 1427
  def dump_text(*index, &block)
    dump(['text'], *index, &block)
  end
dump_window(*index, &block)

[Source]

# File tk/lib/tk/text.rb, line 1430
  def dump_window(*index, &block)
    dump(['window'], *index, &block)
  end
edit_redo()

[Source]

# File tk/lib/tk/text.rb, line 567
  def edit_redo
    tk_send_without_enc('edit', 'redo')
    self
  end
edit_reset()

[Source]

# File tk/lib/tk/text.rb, line 571
  def edit_reset
    tk_send_without_enc('edit', 'reset')
    self
  end
edit_separator()

[Source]

# File tk/lib/tk/text.rb, line 575
  def edit_separator
    tk_send_without_enc('edit', 'separator')
    self
  end
edit_undo()

[Source]

# File tk/lib/tk/text.rb, line 579
  def edit_undo
    tk_send_without_enc('edit', 'undo')
    self
  end
erase()

Alias for clear

get_displaychars(*index)

[Source]

# File tk/lib/tk/text.rb, line 208
  def get_displaychars(*index)
    # Tk8.5 feature
    get('-displaychars', *index)
  end
image_cget(index, slot)

[Source]

# File tk/lib/tk/text.rb, line 307
  def image_cget(index, slot)
    case slot.to_s
    when 'text', 'label', 'show', 'data', 'file'
      _fromUTF8(tk_send_without_enc('image', 'cget',
                                    _get_eval_enc_str(index), "-#{slot}"))
    else
      tk_tcl2ruby(_fromUTF8(tk_send_without_enc('image', 'cget',
                                                _get_eval_enc_str(index),
                                                "-#{slot}")))
    end
  end
image_configinfo(index, slot = nil)

[Source]

# File tk/lib/tk/text.rb, line 333
  def image_configinfo(index, slot = nil)
    if TkComm::GET_CONFIGINFO_AS_ARRAY
      if slot
        case slot.to_s
        when 'text', 'label', 'show', 'data', 'file'
          #conf = tk_split_simplelist(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}")))
          conf = tk_split_simplelist(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}"), false, true)
        else
          #conf = tk_split_list(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}")))
          conf = tk_split_list(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}"), 0, false, true)
        end
        conf[0] = conf[0][1..-1]
        conf
      else
        # tk_split_simplelist(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index)))).collect{|conflist|
        #  conf = tk_split_simplelist(conflist)
        tk_split_simplelist(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index)), false, false).collect{|conflist|
          conf = tk_split_simplelist(conflist, false, true)
          conf[0] = conf[0][1..-1]
          case conf[0]
          when 'text', 'label', 'show', 'data', 'file'
          else
            if conf[3]
              if conf[3].index('{')
                conf[3] = tk_split_list(conf[3])
              else
                conf[3] = tk_tcl2ruby(conf[3])
              end
            end
            if conf[4]
              if conf[4].index('{')
                conf[4] = tk_split_list(conf[4])
              else
                conf[4] = tk_tcl2ruby(conf[4])
              end
            end
          end
          conf[1] = conf[1][1..-1] if conf.size == 2 # alias info
          conf
        }
      end
    else # ! TkComm::GET_CONFIGINFO_AS_ARRAY
      if slot
        case slot.to_s
        when 'text', 'label', 'show', 'data', 'file'
          #conf = tk_split_simplelist(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}")))
          conf = tk_split_simplelist(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}"), false, true)
        else
          #conf = tk_split_list(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}")))
          conf = tk_split_list(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}"), 0, false, true)
        end
        key = conf.shift[1..-1]
        { key => conf }
      else
        ret = {}
        #tk_split_simplelist(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index)))).each{|conflist|
        #  conf = tk_split_simplelist(conflist)
        tk_split_simplelist(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index)), false, false).each{|conflist|
          conf = tk_split_simplelist(conflist, false, true)
          key = conf.shift[1..-1]
          case key
          when 'text', 'label', 'show', 'data', 'file'
          else
            if conf[2]
              if conf[2].index('{')
                conf[2] = tk_split_list(conf[2])
              else
                conf[2] = tk_tcl2ruby(conf[2])
              end
            end
            if conf[3]
              if conf[3].index('{')
                conf[3] = tk_split_list(conf[3])
              else
                conf[3] = tk_tcl2ruby(conf[3])
              end
            end
          end
          if conf.size == 1
            ret[key] = conf[0][1..-1]  # alias info
          else
            ret[key] = conf
          end
        }
        ret
      end
    end
  end
image_configure(index, slot, value=None)

[Source]

# File tk/lib/tk/text.rb, line 319
  def image_configure(index, slot, value=None)
    if slot.kind_of?(Hash)
      _fromUTF8(tk_send_without_enc('image', 'configure',
                                    _get_eval_enc_str(index),
                                    *hash_kv(slot, true)))
    else
      _fromUTF8(tk_send_without_enc('image', 'configure',
                                    _get_eval_enc_str(index),
                                    "-#{slot}",
                                    _get_eval_enc_str(value)))
    end
    self
  end
image_names()

[Source]

# File tk/lib/tk/text.rb, line 443
  def image_names
    #tk_split_simplelist(_fromUTF8(tk_send_without_enc('image', 'names'))).collect{|elt|
    tk_split_simplelist(tk_send_without_enc('image', 'names'), false, true).collect{|elt|
      tagid2obj(elt)
    }
  end
index(idx)

[Source]

# File tk/lib/tk/text.rb, line 203
  def index(idx)
    TkText::IndexString.new(tk_send_without_enc('index',
                                                _get_eval_enc_str(idx)))
  end
init_instance_variable()

[Source]

# File tk/lib/tk/text.rb, line 166
  def init_instance_variable
    @cmdtbl = []
    @tags = {}
  end
insert(index, chars, *tags)

[Source]

# File tk/lib/tk/text.rb, line 460
  def insert(index, chars, *tags)
    if tags[0].kind_of?(Array)
      # multiple chars-taglist argument :: str, [tag,...], str, [tag,...], ...
      args = [chars]
      while tags.size > 0
        args << tags.shift.collect{|x|_get_eval_string(x)}.join(' ')  # taglist
        args << tags.shift if tags.size > 0                           # chars
      end
      super(index, *args)
    else
      # single chars-taglist argument :: str, tag, tag, ...
      if tags.size == 0
        super(index, chars)
      else
        super(index, chars, tags.collect{|x|_get_eval_string(x)}.join(' '))
      end
    end
  end
mark_gravity(mark, direction=nil)

[Source]

# File tk/lib/tk/text.rb, line 271
  def mark_gravity(mark, direction=nil)
    if direction
      tk_send_without_enc('mark', 'gravity',
                          _get_eval_enc_str(mark), direction)
      self
    else
      tk_send_without_enc('mark', 'gravity', _get_eval_enc_str(mark))
    end
  end
mark_names()

[Source]

# File tk/lib/tk/text.rb, line 264
  def mark_names
    #tk_split_simplelist(_fromUTF8(tk_send_without_enc('mark', 'names'))).collect{|elt|
    tk_split_simplelist(tk_send_without_enc('mark', 'names'), false, true).collect{|elt|
      tagid2obj(elt)
    }
  end
mark_next(index)

[Source]

# File tk/lib/tk/text.rb, line 295
  def mark_next(index)
    tagid2obj(_fromUTF8(tk_send_without_enc('mark', 'next',
                                            _get_eval_enc_str(index))))
  end
mark_previous(index)

[Source]

# File tk/lib/tk/text.rb, line 301
  def mark_previous(index)
    tagid2obj(_fromUTF8(tk_send_without_enc('mark', 'previous',
                                            _get_eval_enc_str(index))))
  end
mark_set(mark, index)

[Source]

# File tk/lib/tk/text.rb, line 281
  def mark_set(mark, index)
    tk_send_without_enc('mark', 'set', _get_eval_enc_str(mark),
                        _get_eval_enc_str(index))
    self
  end
mark_unset(*marks)

[Source]

# File tk/lib/tk/text.rb, line 288
  def mark_unset(*marks)
    tk_send_without_enc('mark', 'unset',
                        *(marks.collect{|mark| _get_eval_enc_str(mark)}))
    self
  end
modified(mode)

[Source]

# File tk/lib/tk/text.rb, line 558
  def modified(mode)
    tk_send_without_enc('edit', 'modified', mode)
    self
  end
modified=(mode)

[Source]

# File tk/lib/tk/text.rb, line 562
  def modified=(mode)
    modified(mode)
    mode
  end
modified?()

[Source]

# File tk/lib/tk/text.rb, line 555
  def modified?
    bool(tk_send_without_enc('edit', 'modified'))
  end
next_mark(index)

Alias for mark_next

peer_names()

[Source]

# File tk/lib/tk/text.rb, line 532
  def peer_names()
    # Tk8.5 feature
    list(tk_send_without_enc('peer', 'names'))
  end
previous_mark(index)

Alias for mark_previous

replace(idx1, idx2, *opts)

[Source]

# File tk/lib/tk/text.rb, line 537
  def replace(idx1, idx2, *opts)
    tk_send('replace', idx1, idx2, *opts)
    self
  end
rsearch(pat,start,stop=None)

[Source]

# File tk/lib/tk/text.rb, line 1295
  def rsearch(pat,start,stop=None)
    rsearch_with_length(pat,start,stop)[0]
  end
rsearch_with_length(pat,start,stop=None)

[Source]

# File tk/lib/tk/text.rb, line 1243
  def rsearch_with_length(pat,start,stop=None)
    pat = pat.chr if pat.kind_of?(Integer)
    if stop != None
      return ["", 0] if compare(start,'<=',stop)
      txt = get(stop,start)
      if (pos = txt.rindex(pat))
        match = $&
        #pos = txt[0..(pos-1)].split('').length if pos > 0
        pos = _ktext_length(txt[0..(pos-1)]) if pos > 0
        if pat.kind_of?(String)
          #return [index(stop + " + #{pos} chars"), pat.split('').length]
          return [index(stop + " + #{pos} chars"), _ktext_length(pat), pat.dup]
        else
          #return [index(stop + " + #{pos} chars"), $&.split('').length]
          return [index(stop + " + #{pos} chars"), _ktext_length(match), match]
        end
      else
        return ["", 0]
      end
    else
      txt = get('1.0',start)
      if (pos = txt.rindex(pat))
        match = $&
        #pos = txt[0..(pos-1)].split('').length if pos > 0
        pos = _ktext_length(txt[0..(pos-1)]) if pos > 0
        if pat.kind_of?(String)
          #return [index("1.0 + #{pos} chars"), pat.split('').length]
          return [index("1.0 + #{pos} chars"), _ktext_length(pat), pat.dup]
        else
          #return [index("1.0 + #{pos} chars"), $&.split('').length]
          return [index("1.0 + #{pos} chars"), _ktext_length(match), match]
        end
      else
        txt = get('1.0','end - 1 char')
        if (pos = txt.rindex(pat))
          match = $&
          #pos = txt[0..(pos-1)].split('').length if pos > 0
          pos = _ktext_length(txt[0..(pos-1)]) if pos > 0
          if pat.kind_of?(String)
            #return [index("1.0 + #{pos} chars"), pat.split('').length]
            return [index("1.0 + #{pos} chars"), _ktext_length(pat), pat.dup]
          else
            #return [index("1.0 + #{pos} chars"), $&.split('').length]
            return [index("1.0 + #{pos} chars"), _ktext_length(match), match]
          end
        else
          return ["", 0]
        end
      end
    end
  end
search(pat,start,stop=None)

[Source]

# File tk/lib/tk/text.rb, line 1239
  def search(pat,start,stop=None)
    search_with_length(pat,start,stop)[0]
  end
search_with_length(pat,start,stop=None)

[Source]

# File tk/lib/tk/text.rb, line 1182
  def search_with_length(pat,start,stop=None)
    pat = pat.chr if pat.kind_of?(Integer)
    if stop != None
      return ["", 0] if compare(start,'>=',stop)
      txt = get(start,stop)
      if (pos = txt.index(pat))
        match = $&
        #pos = txt[0..(pos-1)].split('').length if pos > 0
        pos = _ktext_length(txt[0..(pos-1)]) if pos > 0
        if pat.kind_of?(String)
          #return [index(start + " + #{pos} chars"), pat.split('').length]
          return [index(start + " + #{pos} chars"),
                  _ktext_length(pat), pat.dup]
        else
          #return [index(start + " + #{pos} chars"), $&.split('').length]
          return [index(start + " + #{pos} chars"),
                  _ktext_length(match), match]
        end
      else
        return ["", 0]
      end
    else
      txt = get(start,'end - 1 char')
      if (pos = txt.index(pat))
        match = $&
        #pos = txt[0..(pos-1)].split('').length if pos > 0
        pos = _ktext_length(txt[0..(pos-1)]) if pos > 0
        if pat.kind_of?(String)
          #return [index(start + " + #{pos} chars"), pat.split('').length]
          return [index(start + " + #{pos} chars"),
                  _ktext_length(pat), pat.dup]
        else
          #return [index(start + " + #{pos} chars"), $&.split('').length]
          return [index(start + " + #{pos} chars"),
                  _ktext_length(match), match]
        end
      else
        txt = get('1.0','end - 1 char')
        if (pos = txt.index(pat))
          match = $&
          #pos = txt[0..(pos-1)].split('').length if pos > 0
          pos = _ktext_length(txt[0..(pos-1)]) if pos > 0
          if pat.kind_of?(String)
            #return [index("1.0 + #{pos} chars"), pat.split('').length]
            return [index("1.0 + #{pos} chars"),
                    _ktext_length(pat), pat.dup]
          else
            #return [index("1.0 + #{pos} chars"), $&.split('').length]
            return [index("1.0 + #{pos} chars"), _ktext_length(match), match]
          end
        else
          return ["", 0]
        end
      end
    end
  end
set_current(index)

[Source]

# File tk/lib/tk/text.rb, line 455
  def set_current(index)
    tk_send_without_enc('mark','set','current', _get_eval_enc_str(index))
    self
  end
set_insert(index)

[Source]

# File tk/lib/tk/text.rb, line 450
  def set_insert(index)
    tk_send_without_enc('mark','set','insert', _get_eval_enc_str(index))
    self
  end
set_mark(mark, index)

Alias for mark_set

tag_add(tag, index1, index2=None)

[Source]

# File tk/lib/tk/text.rb, line 612
  def tag_add(tag, index1, index2=None)
    tk_send_without_enc('tag', 'add', _get_eval_enc_str(tag),
                        _get_eval_enc_str(index1),
                        _get_eval_enc_str(index2))
    self
  end
tag_bind(tag, seq, *args)

def tag_bind(tag, seq, cmd=Proc.new, *args)

  _bind([@path, 'tag', 'bind', tag], seq, cmd, *args)
  self

end

[Source]

# File tk/lib/tk/text.rb, line 642
  def tag_bind(tag, seq, *args)
    # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    _bind([@path, 'tag', 'bind', tag], seq, cmd, *args)
    self
  end
tag_bind_append(tag, seq, *args)

def tag_bind_append(tag, seq, cmd=Proc.new, *args)

  _bind_append([@path, 'tag', 'bind', tag], seq, cmd, *args)
  self

end

[Source]

# File tk/lib/tk/text.rb, line 657
  def tag_bind_append(tag, seq, *args)
    # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    _bind_append([@path, 'tag', 'bind', tag], seq, cmd, *args)
    self
  end
tag_bind_remove(tag, seq)

[Source]

# File tk/lib/tk/text.rb, line 668
  def tag_bind_remove(tag, seq)
    _bind_remove([@path, 'tag', 'bind', tag], seq)
    self
  end
tag_bindinfo(tag, context=nil)

[Source]

# File tk/lib/tk/text.rb, line 673
  def tag_bindinfo(tag, context=nil)
    _bindinfo([@path, 'tag', 'bind', tag], context)
  end
tag_delete(*tags)

[Source]

# File tk/lib/tk/text.rb, line 621
  def tag_delete(*tags)
    tk_send_without_enc('tag', 'delete',
                        *(tags.collect{|tag| _get_eval_enc_str(tag)}))
    if TkTextTag::TTagID_TBL[@path]
      tags.each{|tag|
        if tag.kind_of?(TkTextTag)
          TkTextTag::TTagID_TBL[@path].delete(tag.id)
        else
          TkTextTag::TTagID_TBL[@path].delete(tag)
        end
      }
    end
    self
  end
tag_lower(tag, below=None)

[Source]

# File tk/lib/tk/text.rb, line 859
  def tag_lower(tag, below=None)
    tk_send_without_enc('tag', 'lower', _get_eval_enc_str(tag),
                        _get_eval_enc_str(below))
    self
  end
tag_names(index=None)

[Source]

# File tk/lib/tk/text.rb, line 257
  def tag_names(index=None)
    #tk_split_simplelist(_fromUTF8(tk_send_without_enc('tag', 'names', _get_eval_enc_str(index)))).collect{|elt|
    tk_split_simplelist(tk_send_without_enc('tag', 'names', _get_eval_enc_str(index)), false, true).collect{|elt|
      tagid2obj(elt)
    }
  end
tag_nextrange(tag, first, last=None)

[Source]

# File tk/lib/tk/text.rb, line 884
  def tag_nextrange(tag, first, last=None)
    simplelist(tk_send_without_enc('tag', 'nextrange',
                                   _get_eval_enc_str(tag),
                                   _get_eval_enc_str(first),
                                   _get_eval_enc_str(last))).collect{|idx|
      TkText::IndexString.new(idx)
    }
  end
tag_prevrange(tag, first, last=None)

[Source]

# File tk/lib/tk/text.rb, line 893
  def tag_prevrange(tag, first, last=None)
    simplelist(tk_send_without_enc('tag', 'prevrange',
                                   _get_eval_enc_str(tag),
                                   _get_eval_enc_str(first),
                                   _get_eval_enc_str(last))).collect{|idx|
      TkText::IndexString.new(idx)
    }
  end
tag_raise(tag, above=None)

[Source]

# File tk/lib/tk/text.rb, line 853
  def tag_raise(tag, above=None)
    tk_send_without_enc('tag', 'raise', _get_eval_enc_str(tag),
                        _get_eval_enc_str(above))
    self
  end
tag_ranges(tag)

[Source]

# File tk/lib/tk/text.rb, line 871
  def tag_ranges(tag)
    #l = tk_split_simplelist(tk_send_without_enc('tag', 'ranges',
    #                                            _get_eval_enc_str(tag)))
    l = tk_split_simplelist(tk_send_without_enc('tag', 'ranges',
                                                _get_eval_enc_str(tag)),
                            false, true)
    r = []
    while key=l.shift
      r.push [TkText::IndexString.new(key), TkText::IndexString.new(l.shift)]
    end
    r
  end
tag_remove(tag, *indices)

[Source]

# File tk/lib/tk/text.rb, line 865
  def tag_remove(tag, *indices)
    tk_send_without_enc('tag', 'remove', _get_eval_enc_str(tag),
                        *(indices.collect{|idx| _get_eval_enc_str(idx)}))
    self
  end
tagid2obj(tagid)

[Source]

# File tk/lib/tk/text.rb, line 249
  def tagid2obj(tagid)
    if @tags[tagid]
      @tags[tagid]
    else
      tagid
    end
  end
text_copy()

[Source]

# File tk/lib/tk/text.rb, line 594
  def text_copy
    # Tk8.4 feature
    tk_call_without_enc('tk_textCopy', @path)
    self
  end
text_cut()

[Source]

# File tk/lib/tk/text.rb, line 600
  def text_cut
    # Tk8.4 feature
    tk_call_without_enc('tk_textCut', @path)
    self
  end
text_paste()

[Source]

# File tk/lib/tk/text.rb, line 606
  def text_paste
    # Tk8.4 feature
    tk_call_without_enc('tk_textPaste', @path)
    self
  end
tksearch(*args)

[Source]

# File tk/lib/tk/text.rb, line 1114
  def tksearch(*args)
    # call 'search' subcommand of text widget
    #   args ::= [<array_of_opts>] <pattern> <start_index> [<stop_index>]
    # If <pattern> is regexp, then it must be a regular expression of Tcl
    nocase = false
    if args[0].kind_of?(Array)
      opts = args.shift.collect{|opt|
        s_opt = opt.to_s
        nocase = true if s_opt == 'nocase'
        '-' + s_opt
      }
    else
      opts = []
    end

    if args[0].kind_of?(Regexp)
      regexp = args.shift
      if !nocase && (regexp.options & Regexp::IGNORECASE) != 0
        opts << '-nocase'
      end
      args.unshift(regexp.source)
    end

    opts << '--'

    ret = tk_send('search', *(opts + args))
    if ret == ""
      nil
    else
      TkText::IndexString.new(ret)
    end
  end
tksearch_with_count(*args)

[Source]

# File tk/lib/tk/text.rb, line 1147
  def tksearch_with_count(*args)
    # call 'search' subcommand of text widget
    #   args ::= [<array_of_opts>] <var> <pattern> <start_index> [<stop_index>]
    # If <pattern> is regexp, then it must be a regular expression of Tcl
    nocase = false
    if args[0].kind_of?(Array)
      opts = args.shift.collect{|opt|
        s_opt = opt.to_s
        nocase = true if s_opt == 'nocase'
        '-' + s_opt
      }
    else
      opts = []
    end

    opts << '-count' << args.shift

    if args[0].kind_of?(Regexp)
      regexp = args.shift
      if !nocase && (regexp.options & Regexp::IGNORECASE) != 0
        opts << '-nocase'
      end
      args.unshift(regexp.source)
    end

    opts << '--'

    ret = tk_send('search', *(opts + args))
    if ret == ""
      nil
    else
      TkText::IndexString.new(ret)
    end
  end
unset_mark(*marks)

Alias for mark_unset

value()

[Source]

# File tk/lib/tk/text.rb, line 213
  def value
    _fromUTF8(tk_send_without_enc('get', "1.0", "end - 1 char"))
  end
value=(val)

[Source]

# File tk/lib/tk/text.rb, line 217
  def value= (val)
    tk_send_without_enc('delete', "1.0", 'end')
    tk_send_without_enc('insert', "1.0", _get_eval_enc_str(val))
    val
  end
window_names()

[Source]

# File tk/lib/tk/text.rb, line 1086
  def window_names
    # tk_split_simplelist(_fromUTF8(tk_send_without_enc('window', 'names'))).collect{|elt|
    tk_split_simplelist(tk_send_without_enc('window', 'names'), false, true).collect{|elt|
      tagid2obj(elt)
    }
  end
xview_pickplace(index)

[Source]

# File tk/lib/tk/text.rb, line 584
  def xview_pickplace(index)
    tk_send_without_enc('xview', '-pickplace', _get_eval_enc_str(index))
    self
  end
yview_pickplace(index)

[Source]

# File tk/lib/tk/text.rb, line 589
  def yview_pickplace(index)
    tk_send_without_enc('yview', '-pickplace', _get_eval_enc_str(index))
    self
  end


Module: TkText::IndexModMethods

Module | TkText::IndexModMethods
In: | tk/lib/tk/text.rb

Methods

+ - char chars line lineend lines linestart wordend wordstart

Public Instance methods

+(mod)

[Source]

# File tk/lib/tk/text.rb, line 72
    def +(mod)
      return chars(mod) if mod.kind_of?(Numeric)

      mod = mod.to_s
      if mod =~ /^\s*[+-]?\d/
        TkText::IndexString.new(String.new(id) << ' + ' << mod)
      else
        TkText::IndexString.new(String.new(id) << ' ' << mod)
      end
    end
-(mod)

[Source]

# File tk/lib/tk/text.rb, line 83
    def -(mod)
      return chars(-mod) if mod.kind_of?(Numeric)

      mod = mod.to_s
      if mod =~ /^\s*[+-]?\d/
        TkText::IndexString.new(String.new(id) << ' - ' << mod)
      elsif mod =~ /^\s*[-]\s+(\d.*)$/
        TkText::IndexString.new(String.new(id) << ' - -' << $1)
      else
        TkText::IndexString.new(String.new(id) << ' ' << mod)
      end
    end
char(mod)

Alias for chars

chars(mod)

[Source]

# File tk/lib/tk/text.rb, line 96
    def chars(mod)
      fail ArgumentError, 'expect Integer'  unless mod.kind_of?(Integer)
      if mod < 0
        TkText::IndexString.new(String.new(id) << ' ' << mod.to_s << ' chars')
      else
        TkText::IndexString.new(String.new(id) << ' + ' << mod.to_s << ' chars')
      end
    end
line(mod)

Alias for lines

lineend()

[Source]

# File tk/lib/tk/text.rb, line 119
    def lineend
      TkText::IndexString.new(String.new(id) << ' lineend')
    end
lines(mod)

[Source]

# File tk/lib/tk/text.rb, line 106
    def lines(mod)
      fail ArgumentError, 'expect Integer'  unless mod.kind_of?(Integer)
      if mod < 0
        TkText::IndexString.new(String.new(id) << ' ' << mod.to_s << ' lines')
      else
        TkText::IndexString.new(String.new(id) << ' + ' << mod.to_s << ' lines')
      end
    end
linestart()

[Source]

# File tk/lib/tk/text.rb, line 116
    def linestart
      TkText::IndexString.new(String.new(id) << ' linestart')
    end
wordend()

[Source]

# File tk/lib/tk/text.rb, line 126
    def wordend
      TkText::IndexString.new(String.new(id) << ' wordend')
    end
wordstart()

[Source]

# File tk/lib/tk/text.rb, line 123
    def wordstart
      TkText::IndexString.new(String.new(id) << ' wordstart')
    end


Class: TkText::IndexString

Class | TkText::IndexString
In: | tk/lib/tk/text.rb
Parent: | String

Methods

at id new

Included Modules

IndexModMethods

Public Class methods

at(x,y)

[Source]

# File tk/lib/tk/text.rb, line 134
    def self.at(x,y)
      self.new("@#{x},#{y}")
    end
new(str)

[Source]

# File tk/lib/tk/text.rb, line 138
    def self.new(str)
      if str.kind_of?(String)
        super(str)
      elsif str.kind_of?(Symbol)
        super(str.to_s)
      else
        str
      end
    end

Public Instance methods

id()

[Source]

# File tk/lib/tk/text.rb, line 148
    def id
      self
    end


Class: TkText::Peer

Class | TkText::Peer
In: | tk/lib/tk/text.rb
Parent: | TkText

Methods

new

Public Class methods

new(text, parent=nil, keys={})

Tk8.5 feature

[Source]

# File tk/lib/tk/text.rb, line 1442
  def initialize(text, parent=nil, keys={})
    unless text.kind_of?(TkText)
      fail ArgumentError, "TkText is expected for 1st argument"
    end
    @src_text = text
    super(parent, keys)
  end


Class: TkTextImage

Class | TkTextImage
In: | tk/lib/tk/textimage.rb
Parent: | TkObject

Methods

[] []= cget configinfo configure current_configinfo id image image= mark new

Included Modules

TkText::IndexModMethods

Public Class methods

new(parent, index, keys)

[Source]

# File tk/lib/tk/textimage.rb, line 10
  def initialize(parent, index, keys)
    #unless parent.kind_of?(TkText)
    #  fail ArgumentError, "expect TkText for 1st argument"
    #end
    @t = parent
    if index == 'end' || index == :end
      @path = TkTextMark.new(@t, tk_call(@t.path, 'index', 'end - 1 chars'))
    elsif index.kind_of? TkTextMark
      if tk_call_without_enc(@t.path,'index',index.path) == tk_call_without_enc(@t.path,'index','end')
        @path = TkTextMark.new(@t, tk_call_without_enc(@t.path, 'index',
                                                       'end - 1 chars'))
      else
        @path = TkTextMark.new(@t, tk_call_without_enc(@t.path, 'index',
                                                       index.path))
      end
    else
      @path = TkTextMark.new(@t, tk_call_without_enc(@t.path, 'index',
                                                     _get_eval_enc_str(index)))
    end
    @path.gravity = 'left'
    @index = @path.path
    @id = tk_call_without_enc(@t.path, 'image', 'create', @index,
                              *hash_kv(keys, true)).freeze
    @path.gravity = 'right'
  end

Public Instance methods

[](slot)

[Source]

# File tk/lib/tk/textimage.rb, line 43
  def [](slot)
    cget(slot)
  end
[]=(slot, value)

[Source]

# File tk/lib/tk/textimage.rb, line 46
  def []=(slot, value)
    configure(slot, value)
    value
  end
cget(slot)

[Source]

# File tk/lib/tk/textimage.rb, line 51
  def cget(slot)
    @t.image_cget(@index, slot)
  end
configinfo(slot = nil)

def configure(slot, value)

  tk_call @t.path, 'image', 'configure', @index, "-#{slot}", value

end

[Source]

# File tk/lib/tk/textimage.rb, line 63
  def configinfo(slot = nil)
    @t.image_configinfo(@index, slot)
  end
configure(slot, value=None)

[Source]

# File tk/lib/tk/textimage.rb, line 55
  def configure(slot, value=None)
    @t.image_configure(@index, slot, value)
    self
  end
current_configinfo(slot = nil)

[Source]

# File tk/lib/tk/textimage.rb, line 67
  def current_configinfo(slot = nil)
    @t.current_image_configinfo(@index, slot)
  end
id()

[Source]

# File tk/lib/tk/textimage.rb, line 36
  def id
    TkText::IndexString.new(@id)
  end
image()

[Source]

# File tk/lib/tk/textimage.rb, line 71
  def image
    img = tk_call_without_enc(@t.path, 'image', 'cget', @index, '-image')
    TkImage::Tk_IMGTBL[img]? TkImage::Tk_IMGTBL[img] : img
  end
image=(value)

[Source]

# File tk/lib/tk/textimage.rb, line 76
  def image=(value)
    tk_call_without_enc(@t.path, 'image', 'configure', @index, '-image',
                        _get_eval_enc_str(value))
    #self
    value
  end
mark()

[Source]

# File tk/lib/tk/textimage.rb, line 39
  def mark
    @path
  end


Class: TkTextMark

Class | TkTextMark
In: | tk/lib/tk/textmark.rb
Parent: | TkObject

Methods

destroy exist? gravity gravity= id id2obj new next pos pos= previous set unset

Included Modules

TkText::IndexModMethods

Constants

TMarkID_TBL | = | TkCore::INTERP.create_table
Tk_TextMark_ID | = | ['mark'.freeze, '00000'.taint].freeze

Public Class methods

id2obj(text, id)

[Source]

# File tk/lib/tk/textmark.rb, line 15
  def TkTextMark.id2obj(text, id)
    tpath = text.path
    return id unless TMarkID_TBL[tpath]
    TMarkID_TBL[tpath][id]? TMarkID_TBL[tpath][id]: id
  end
new(parent, index)

[Source]

# File tk/lib/tk/textmark.rb, line 21
  def initialize(parent, index)
    #unless parent.kind_of?(TkText)
    #  fail ArgumentError, "expect TkText for 1st argument"
    #end
    @parent = @t = parent
    @tpath = parent.path
    # @path = @id = Tk_TextMark_ID.join('')
    @path = @id = Tk_TextMark_ID.join(TkCore::INTERP._ip_id_).freeze
    TMarkID_TBL[@id] = self
    TMarkID_TBL[@tpath] = {} unless TMarkID_TBL[@tpath]
    TMarkID_TBL[@tpath][@id] = self
    Tk_TextMark_ID[1].succ!
    tk_call_without_enc(@t.path, 'mark', 'set', @id,
                        _get_eval_enc_str(index))
    @t._addtag id, self
  end

Public Instance methods

destroy()

Alias for unset

exist?()

[Source]

# File tk/lib/tk/textmark.rb, line 42
  def exist?
    #if ( tk_split_simplelist(_fromUTF8(tk_call_without_enc(@t.path, 'mark', 'names'))).find{|id| id == @id } )
    if ( tk_split_simplelist(tk_call_without_enc(@t.path, 'mark', 'names'), false, true).find{|id| id == @id } )
      true
    else
      false
    end
  end
gravity()

[Source]

# File tk/lib/tk/textmark.rb, line 98
  def gravity
    tk_call_without_enc(@t.path, 'mark', 'gravity', @id)
  end
gravity=(direction)

[Source]

# File tk/lib/tk/textmark.rb, line 102
  def gravity=(direction)
    tk_call_without_enc(@t.path, 'mark', 'gravity', @id, direction)
    #self
    direction
  end
id()

[Source]

# File tk/lib/tk/textmark.rb, line 38
  def id
    TkText::IndexString.new(@id)
  end
next(index = nil)

[Source]

# File tk/lib/tk/textmark.rb, line 108
  def next(index = nil)
    if index
      @t.tagid2obj(_fromUTF8(tk_call_without_enc(@t.path, 'mark', 'next', _get_eval_enc_str(index))))
    else
      @t.tagid2obj(_fromUTF8(tk_call_without_enc(@t.path, 'mark', 'next', @id)))
    end
  end
pos()

[Source]

# File tk/lib/tk/textmark.rb, line 78
  def pos
    @t.index(@id)
  end
pos=(where)

[Source]

# File tk/lib/tk/textmark.rb, line 82
  def pos=(where)
    set(where)
  end
previous(index = nil)

[Source]

# File tk/lib/tk/textmark.rb, line 116
  def previous(index = nil)
    if index
      @t.tagid2obj(_fromUTF8(tk_call_without_enc(@t.path, 'mark', 'previous', _get_eval_enc_str(index))))
    else
      @t.tagid2obj(_fromUTF8(tk_call_without_enc(@t.path, 'mark', 'previous', @id)))
    end
  end
set(where)

[Source]

# File tk/lib/tk/textmark.rb, line 86
  def set(where)
    tk_call_without_enc(@t.path, 'mark', 'set', @id,
                        _get_eval_enc_str(where))
    self
  end
unset()

[Source]

# File tk/lib/tk/textmark.rb, line 92
  def unset
    tk_call_without_enc(@t.path, 'mark', 'unset', @id)
    self
  end


Class: TkTextMarkAnchor

Class | TkTextMarkAnchor
In: | tk/lib/tk/textmark.rb
Parent: | TkTextNamedMark

Methods

new

Public Class methods

new(parent,*args)

[Source]

# File tk/lib/tk/textmark.rb, line 163
  def self.new(parent,*args)
    super(parent, 'anchor', *args)
  end


Class: TkTextMarkCurrent

Class | TkTextMarkCurrent
In: | tk/lib/tk/textmark.rb
Parent: | TkTextNamedMark

Methods

new

Public Class methods

new(parent,*args)

[Source]

# File tk/lib/tk/textmark.rb, line 157
  def self.new(parent,*args)
    super(parent, 'current', *args)
  end


Class: TkTextMarkInsert

Class | TkTextMarkInsert
In: | tk/lib/tk/textmark.rb
Parent: | TkTextNamedMark

Methods

new

Public Class methods

new(parent,*args)

[Source]

# File tk/lib/tk/textmark.rb, line 151
  def self.new(parent,*args)
    super(parent, 'insert', *args)
  end


Class: TkTextNamedMark

Class | TkTextNamedMark
In: | tk/lib/tk/textmark.rb
Parent: | TkTextMark

Methods

new new

Public Class methods

new(parent, name, *args)

[Source]

# File tk/lib/tk/textmark.rb, line 126
  def self.new(parent, name, *args)
    if TMarkID_TBL[parent.path] && TMarkID_TBL[parent.path][name]
      return TMarkID_TBL[parent.path][name]
    else
      super(parent, name, *args)
    end
  end
new(parent, name, index=nil)

[Source]

# File tk/lib/tk/textmark.rb, line 134
  def initialize(parent, name, index=nil)
    #unless parent.kind_of?(TkText)
    #  fail ArgumentError, "expect TkText for 1st argument"
    #end
    @parent = @t = parent
    @tpath = parent.path
    @path = @id = name
    TMarkID_TBL[@id] = self
    TMarkID_TBL[@tpath] = {} unless TMarkID_TBL[@tpath]
    TMarkID_TBL[@tpath][@id] = self unless TMarkID_TBL[@tpath][@id]
    tk_call_without_enc(@t.path, 'mark', 'set', @id,
                        _get_eval_enc_str(index)) if index
    @t._addtag id, self
  end


Class: TkTextNamedTag

Class | TkTextNamedTag
In: | tk/lib/tk/texttag.rb
Parent: | TkTextTag

Methods

new new

Public Class methods

new(parent, name, *args)

[Source]

# File tk/lib/tk/texttag.rb, line 230
  def self.new(parent, name, *args)
    if TTagID_TBL[parent.path] && TTagID_TBL[parent.path][name]
      tagobj = TTagID_TBL[parent.path][name]
      if args != []
        keys = args.pop
        if keys.kind_of?(Hash)
          tagobj.add(*args) if args != []
          tagobj.configure(keys)
        else
          args.push keys
          tagobj.add(*args)
        end
      end
      return tagobj
    else
      super(parent, name, *args)
    end
  end
new(parent, name, *args)

[Source]

# File tk/lib/tk/texttag.rb, line 249
  def initialize(parent, name, *args)
    #unless parent.kind_of?(TkText)
    #  fail ArgumentError, "expect TkText for 1st argument"
    #end
    @parent = @t = parent
    @tpath = parent.path
    @path = @id = name
    TTagID_TBL[@tpath] = {} unless TTagID_TBL[@tpath]
    TTagID_TBL[@tpath][@id] = self unless TTagID_TBL[@tpath][@id]
    #if mode
    #  tk_call @t.path, "addtag", @id, *args
    #end
    if args != []
      keys = args.pop
      if keys.kind_of?(Hash)
        add(*args) if args != []
        configure(keys)
      else
        args.push keys
        add(*args)
      end
    end
    @t._addtag id, self
  end


Class: TkTextTag

Class | TkTextTag
In: | tk/lib/tk/texttag.rb
Parent: | TkObject

Methods

[] []= add bind bind_append bind_remove bindinfo cget configinfo configure current_configinfo destroy exist? first id id2obj last lower new nextrange prevrange raise ranges remove

Included Modules

TkTreatTagFont TkText::IndexModMethods

Constants

TTagID_TBL | = | TkCore::INTERP.create_table
Tk_TextTag_ID | = | ['tag'.freeze, '00000'.taint].freeze

Public Class methods

id2obj(text, id)

[Source]

# File tk/lib/tk/texttag.rb, line 17
  def TkTextTag.id2obj(text, id)
    tpath = text.path
    return id unless TTagID_TBL[tpath]
    TTagID_TBL[tpath][id]? TTagID_TBL[tpath][id]: id
  end
new(parent, *args)

[Source]

# File tk/lib/tk/texttag.rb, line 23
  def initialize(parent, *args)
    #unless parent.kind_of?(TkText)
    #  fail ArgumentError, "expect TkText for 1st argument"
    #end
    @parent = @t = parent
    @tpath = parent.path
    # @path = @id = Tk_TextTag_ID.join('')
    @path = @id = Tk_TextTag_ID.join(TkCore::INTERP._ip_id_).freeze
    # TTagID_TBL[@id] = self
    TTagID_TBL[@tpath] = {} unless TTagID_TBL[@tpath]
    TTagID_TBL[@tpath][@id] = self
    Tk_TextTag_ID[1].succ!
    #tk_call @t.path, "tag", "configure", @id, *hash_kv(keys)
    if args != []
      keys = args.pop
      if keys.kind_of?(Hash)
        add(*args) if args != []
        configure(keys)
      else
        args.push keys
        add(*args)
      end
    end
    @t._addtag id, self
  end

Public Instance methods

[](key)

[Source]

# File tk/lib/tk/texttag.rb, line 107
  def [](key)
    cget key
  end
[]=(key,val)

[Source]

# File tk/lib/tk/texttag.rb, line 111
  def []=(key,val)
    configure key, val
    val
  end
add(*indices)

[Source]

# File tk/lib/tk/texttag.rb, line 70
  def add(*indices)
    tk_call_without_enc(@t.path, 'tag', 'add', @id,
                        *(indices.collect{|idx| _get_eval_enc_str(idx)}))
    self
  end
bind(seq, *args)

def bind(seq, cmd=Proc.new, *args)

  _bind([@t.path, 'tag', 'bind', @id], seq, cmd, *args)
  self

end

[Source]

# File tk/lib/tk/texttag.rb, line 175
  def bind(seq, *args)
    # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    _bind([@t.path, 'tag', 'bind', @id], seq, cmd, *args)
    self
  end
bind_append(seq, *args)

def bind_append(seq, cmd=Proc.new, *args)

  _bind_append([@t.path, 'tag', 'bind', @id], seq, cmd, *args)
  self

end

[Source]

# File tk/lib/tk/texttag.rb, line 190
  def bind_append(seq, *args)
    # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    _bind_append([@t.path, 'tag', 'bind', @id], seq, cmd, *args)
    self
  end
bind_remove(seq)

[Source]

# File tk/lib/tk/texttag.rb, line 201
  def bind_remove(seq)
    _bind_remove([@t.path, 'tag', 'bind', @id], seq)
    self
  end
bindinfo(context=nil)

[Source]

# File tk/lib/tk/texttag.rb, line 206
  def bindinfo(context=nil)
    _bindinfo([@t.path, 'tag', 'bind', @id], context)
  end
cget(key)

[Source]

# File tk/lib/tk/texttag.rb, line 116
  def cget(key)
    @t.tag_cget @id, key
  end
configinfo(key=nil)

def configure(key, val=None)

  if key.kind_of?(Hash)
    tk_call @t.path, 'tag', 'configure', @id, *hash_kv(key)
  else
    tk_call @t.path, 'tag', 'configure', @id, "-#{key}", val
  end

end def configure(key, value)

  if value == FALSE
    value = "0"
  elsif value.kind_of?(Proc)
    value = install_cmd(value)
  end
  tk_call @t.path, 'tag', 'configure', @id, "-#{key}", value

end

[Source]

# File tk/lib/tk/texttag.rb, line 163
  def configinfo(key=nil)
    @t.tag_configinfo @id, key
  end
configure(key, val=None)

[Source]

# File tk/lib/tk/texttag.rb, line 144
  def configure(key, val=None)
    @t.tag_configure @id, key, val
  end
current_configinfo(key=nil)

[Source]

# File tk/lib/tk/texttag.rb, line 167
  def current_configinfo(key=nil)
    @t.current_tag_configinfo @id, key
  end
destroy()

[Source]

# File tk/lib/tk/texttag.rb, line 222
  def destroy
    tk_call_without_enc(@t.path, 'tag', 'delete', @id)
    TTagID_TBL[@tpath].delete(@id) if TTagID_TBL[@tpath]
    self
  end
exist?()

[Source]

# File tk/lib/tk/texttag.rb, line 53
  def exist?
    #if ( tk_split_simplelist(_fromUTF8(tk_call_without_enc(@t.path, 'tag', 'names'))).find{|id| id == @id } )
    if ( tk_split_simplelist(tk_call_without_enc(@t.path, 'tag', 'names'), false, true).find{|id| id == @id } )
      true
    else
      false
    end
  end
first()

[Source]

# File tk/lib/tk/texttag.rb, line 62
  def first
    TkText::IndexString.new(@id + '.first')
  end
id()

[Source]

# File tk/lib/tk/texttag.rb, line 49
  def id
    TkText::IndexString.new(@id)
  end
last()

[Source]

# File tk/lib/tk/texttag.rb, line 66
  def last
    TkText::IndexString.new(@id + '.last')
  end
lower(below=None)

[Source]

# File tk/lib/tk/texttag.rb, line 216
  def lower(below=None)
    tk_call_without_enc(@t.path, 'tag', 'lower', @id,
                        _get_eval_enc_str(below))
    self
  end
nextrange(first, last=None)

[Source]

# File tk/lib/tk/texttag.rb, line 91
  def nextrange(first, last=None)
    simplelist(tk_call_without_enc(@t.path, 'tag', 'nextrange', @id,
                                   _get_eval_enc_str(first),
                                   _get_eval_enc_str(last))).collect{|idx|
      TkText::IndexString.new(idx)
    }
  end
prevrange(first, last=None)

[Source]

# File tk/lib/tk/texttag.rb, line 99
  def prevrange(first, last=None)
    simplelist(tk_call_without_enc(@t.path, 'tag', 'prevrange', @id,
                                   _get_eval_enc_str(first),
                                   _get_eval_enc_str(last))).collect{|idx|
      TkText::IndexString.new(idx)
    }
  end
raise(above=None)

[Source]

# File tk/lib/tk/texttag.rb, line 210
  def raise(above=None)
    tk_call_without_enc(@t.path, 'tag', 'raise', @id,
                        _get_eval_enc_str(above))
    self
  end
ranges()

[Source]

# File tk/lib/tk/texttag.rb, line 82
  def ranges
    l = tk_split_simplelist(tk_call_without_enc(@t.path, 'tag', 'ranges', @id))
    r = []
    while key=l.shift
      r.push [TkText::IndexString.new(key), TkText::IndexString.new(l.shift)]
    end
    r
  end
remove(*indices)

[Source]

# File tk/lib/tk/texttag.rb, line 76
  def remove(*indices)
    tk_call_without_enc(@t.path, 'tag', 'remove', @id,
                        *(indices.collect{|idx| _get_eval_enc_str(idx)}))
    self
  end


Module: TkTextTagConfig

Module | TkTextTagConfig
In: | tk/lib/tk/text.rb

Methods

current_tag_configinfo current_window_configinfo tag_cget tag_configinfo tag_configure window_cget window_configinfo window_configure

Included Modules

TkTreatItemFont TkItemConfigMethod

Public Instance methods

current_tag_configinfo(tagOrId, slot=nil)

[Source]

# File tk/lib/tk/text.rb, line 42
  def current_tag_configinfo(tagOrId, slot=nil)
    itemconfigure(['tag', tagOrId], slot)
  end
current_window_configinfo(tagOrId, slot=nil)

[Source]

# File tk/lib/tk/text.rb, line 55
  def current_window_configinfo(tagOrId, slot=nil)
    itemconfigure(['window', tagOrId], slot)
  end
tag_cget(tagOrId, option)

[Source]

# File tk/lib/tk/text.rb, line 33
  def tag_cget(tagOrId, option)
    itemcget(['tag', tagOrId], option)
  end
tag_configinfo(tagOrId, slot=nil)

[Source]

# File tk/lib/tk/text.rb, line 39
  def tag_configinfo(tagOrId, slot=nil)
    itemconfigure(['tag', tagOrId], slot)
  end
tag_configure(tagOrId, slot, value=None)

[Source]

# File tk/lib/tk/text.rb, line 36
  def tag_configure(tagOrId, slot, value=None)
    itemconfigure(['tag', tagOrId], slot, value)
  end
window_cget(tagOrId, option)

[Source]

# File tk/lib/tk/text.rb, line 46
  def window_cget(tagOrId, option)
    itemcget(['window', tagOrId], option)
  end
window_configinfo(tagOrId, slot=nil)

[Source]

# File tk/lib/tk/text.rb, line 52
  def window_configinfo(tagOrId, slot=nil)
    itemconfigure(['window', tagOrId], slot)
  end
window_configure(tagOrId, slot, value=None)

[Source]

# File tk/lib/tk/text.rb, line 49
  def window_configure(tagOrId, slot, value=None)
    itemconfigure(['window', tagOrId], slot, value)
  end


Class: TkTextTagSel

Class | TkTextTagSel
In: | tk/lib/tk/texttag.rb
Parent: | TkTextNamedTag

Methods

new

Public Class methods

new(parent, *args)

[Source]

# File tk/lib/tk/texttag.rb, line 276
  def self.new(parent, *args)
    super(parent, 'sel', *args)
  end


Class: TkTextWin

Class | TkTextWin
In: | tk/lib/tk/txtwin_abst.rb
Parent: | TkWindow

Methods

bbox delete get insert scan_dragto scan_mark see

Constants

TkCommnadNames = [].freeze

Public Instance methods

bbox(index)

def create_self

  fail RuntimeError, "TkTextWin is an abstract class"

end private :create_self

[Source]

# File tk/lib/tk/txtwin_abst.rb, line 13
  def bbox(index)
    list(tk_send_without_enc('bbox', index))
  end
delete(first, last=None)

[Source]

# File tk/lib/tk/txtwin_abst.rb, line 16
  def delete(first, last=None)
    tk_send_without_enc('delete', first, last)
    self
  end
get(*index)

[Source]

# File tk/lib/tk/txtwin_abst.rb, line 20
  def get(*index)
    _fromUTF8(tk_send_without_enc('get', *index))
  end
insert(index, *args)

[Source]

# File tk/lib/tk/txtwin_abst.rb, line 23
  def insert(index, *args)
    tk_send('insert', index, *args)
    self
  end
scan_dragto(x, y)

[Source]

# File tk/lib/tk/txtwin_abst.rb, line 31
  def scan_dragto(x, y)
    tk_send_without_enc('scan', 'dragto', x, y)
    self
  end
scan_mark(x, y)

[Source]

# File tk/lib/tk/txtwin_abst.rb, line 27
  def scan_mark(x, y)
    tk_send_without_enc('scan', 'mark', x, y)
    self
  end
see(index)

[Source]

# File tk/lib/tk/txtwin_abst.rb, line 35
  def see(index)
    tk_send_without_enc('see', index)
    self
  end


Class: TkTextWindow

Class | TkTextWindow
In: | tk/lib/tk/textwindow.rb
Parent: | TkObject

Methods

[] []= cget configinfo configure create create= current_configinfo id mark new window window=

Included Modules

TkText::IndexModMethods

Public Class methods

new(parent, index, keys = {})

[Source]

# File tk/lib/tk/textwindow.rb, line 10
  def initialize(parent, index, keys = {})
    #unless parent.kind_of?(TkText)
    #  fail ArgumentError, "expect TkText for 1st argument"
    #end
    @t = parent
    if index == 'end' || index == :end
      @path = TkTextMark.new(@t, tk_call_without_enc(@t.path, 'index',
                                                     'end - 1 chars'))
    elsif index.kind_of?(TkTextMark)
      if tk_call_without_enc(@t.path,'index',index.path) == tk_call_without_enc(@t.path,'index','end')
        @path = TkTextMark.new(@t, tk_call_without_enc(@t.path, 'index',
                                                       'end - 1 chars'))
      else
        @path = TkTextMark.new(@t, tk_call_without_enc(@t.path, 'index',
                                                       index.path))
      end
    else
      @path = TkTextMark.new(@t, tk_call_without_enc(@t.path, 'index', _get_eval_enc_str(index)))
    end
    @path.gravity = 'left'
    @index = @path.path
    keys = _symbolkey2str(keys)
    @id = keys['window']
    # keys['window'] = @id.epath if @id.kind_of?(TkWindow)
    keys['window'] = _epath(@id) if @id
    if keys['create']
      @p_create = keys['create']
      # if @p_create.kind_of?(Proc)
      if TkComm._callback_entry?(@p_create)
??
        keys['create'] = install_cmd(proc{@id = @p_create.call; _epath(@id)})
      end
    end
    tk_call_without_enc(@t.path, 'window', 'create', @index,
                        *hash_kv(keys, true))
    @path.gravity = 'right'
  end

Public Instance methods

[](slot)

[Source]

# File tk/lib/tk/textwindow.rb, line 64
  def [](slot)
    cget(slot)
  end
[]=(slot, value)

[Source]

# File tk/lib/tk/textwindow.rb, line 67
  def []=(slot, value)
    configure(slot, value)
    value
  end
cget(slot)

[Source]

# File tk/lib/tk/textwindow.rb, line 72
  def cget(slot)
    @t.window_cget(@index, slot)
  end
configinfo(slot = nil)

[Source]

# File tk/lib/tk/textwindow.rb, line 107
  def configinfo(slot = nil)
    @t.window_configinfo(@index, slot)
  end
configure(slot, value=None)

[Source]

# File tk/lib/tk/textwindow.rb, line 76
  def configure(slot, value=None)
    if slot.kind_of?(Hash)
      slot = _symbolkey2str(slot)
      if slot['window']
        @id = slot['window']
        # slot['window'] = @id.epath if @id.kind_of?(TkWindow)
        slot['window'] = _epath(@id) if @id
      end
      if slot['create']
        self.create=slot.delete('create')
      end
      if slot.size > 0
        tk_call_without_enc(@t.path, 'window', 'configure', @index,
                            *hash_kv(slot, true))
      end
    else
      if slot == 'window' || slot == :window
        @id = value
        # value = @id.epath if @id.kind_of?(TkWindow)
        value = _epath(@id) if @id
      end
      if slot == 'create' || slot == :create
        self.create=value
      else
        tk_call_without_enc(@t.path, 'window', 'configure', @index,
                            "-#{slot}", _get_eval_enc_str(value))
      end
    end
    self
  end
create()

[Source]

# File tk/lib/tk/textwindow.rb, line 128
  def create
    @p_create
  end
create=(value)

[Source]

# File tk/lib/tk/textwindow.rb, line 132
  def create=(value)
    @p_create = value
    # if @p_create.kind_of?(Proc)
    if TkComm._callback_entry?(@p_create)
      value = install_cmd(proc{
                            @id = @p_create.call
                            if @id.kind_of?(TkWindow)
                              @id.epath
                            else
                              @id
                            end
                          })
    end
    tk_call_without_enc(@t.path, 'window', 'configure', @index,
                        '-create', _get_eval_enc_str(value))
    value
  end
current_configinfo(slot = nil)

[Source]

# File tk/lib/tk/textwindow.rb, line 111
  def current_configinfo(slot = nil)
    @t.current_window_configinfo(@index, slot)
  end
id()

[Source]

# File tk/lib/tk/textwindow.rb, line 57
  def id
    TkText::IndexString.new(_epath(@id))
  end
mark()

[Source]

# File tk/lib/tk/textwindow.rb, line 60
  def mark
    @path
  end
window()

[Source]

# File tk/lib/tk/textwindow.rb, line 115
  def window
    @id
  end
window=(value)

[Source]

# File tk/lib/tk/textwindow.rb, line 119
  def window=(value)
    @id = value
    # value = @id.epath if @id.kind_of?(TkWindow)
    value = _epath(@id) if @id
    tk_call_without_enc(@t.path, 'window', 'configure', @index,
                        '-window', _get_eval_enc_str(value))
    value
  end


Class: TkTimer

Class | TkTimer
In: | tk/lib/tk/timer.rb
Parent: | Object

Methods

add_procs callback cancel cancel_on_exception= cancel_on_exception? cb_call continue current_status delete_at delete_procs do_callback eventloop_tkwait eventloop_wait get_procs info info loop_rest loop_rest= new reset restart running? set_callback set_interval set_next_callback set_procs set_start_proc skip start start stop thread_tkwait thread_wait tkwait wait

Included Modules

TkCore

Constants

TkCommandNames | = | ['after'.freeze].freeze
Tk_CBID | = | ['a'.freeze, '00000'.taint].freeze
Tk_CBTBL | = | {}.taint
DEFAULT_IGNORE_EXCEPTIONS | = | [ NameError, RuntimeError ].freeze

External Aliases

current_sleep -> current_interval

Attributes

after_id | [R]
after_script | [R]
current_args | [R]
current_proc | [R]
current_sleep | [R]
loop_exec | [RW]
return_value | [R]

Public Class methods

callback(obj_id)

[Source]

# File tk/lib/tk/timer.rb, line 35
  def self.callback(obj_id)
    ex_obj = Tk_CBTBL[obj_id]
    return "" if ex_obj == nil; # canceled
    ex_obj.cb_call
  end
info(obj = nil)

[Source]

# File tk/lib/tk/timer.rb, line 41
  def self.info(obj = nil)
    if obj
      if obj.kind_of?(TkTimer)
        if obj.after_id
          inf = tk_split_list(tk_call_without_enc('after','info',obj.after_id))
          [Tk_CBTBL[inf[0][1]], inf[1]]
        else
          nil
        end
      else
        fail ArgumentError, "TkTimer object is expected"
      end
    else
      tk_call_without_enc('after', 'info').split(' ').collect!{|id|
        ret = Tk_CBTBL.find{|key,val| val.after_id == id}
        (ret == nil)? id: ret[1]
      }
    end
  end
new(*args, &b)

[Source]

# File tk/lib/tk/timer.rb, line 141
  def initialize(*args, &b)
    # @id = Tk_CBID.join('')
    @id = Tk_CBID.join(TkCore::INTERP._ip_id_)
    Tk_CBID[1].succ!

    @wait_var = TkVariable.new(0)

    @cb_cmd = TkCore::INTERP.get_cb_entry(self.method(:do_callback))

    @set_next = true

    @init_sleep = 0
    @init_proc = nil
    @init_args = []

    @current_script = []
    @current_proc = nil
    @current_args = nil
    @return_value = nil

    @sleep_time = 0
    @current_sleep = 0
    @loop_exec = 0
    @do_loop = 0
    @loop_proc = []
    @proc_max = 0
    @current_pos = 0

    @after_id = nil
    @after_script = nil

    @cancel_on_exception = DEFAULT_IGNORE_EXCEPTIONS
    # Unless @cancel_on_exception, Ruby/Tk shows an error dialog box when
    # an excepsion is raised on TkTimer callback procedure.
    # If @cancel_on_exception is an array of exception classes and the raised
    # exception is included in the array, Ruby/Tk cancels executing TkTimer
    # callback procedures silently (TkTimer#cancel is called and no dialog is
    # shown).

    if b
      case args.size
      when 0
        add_procs(b)
      when 1
        args << -1 << b
      else
        args << b
      end
    end

    set_procs(*args) if args != []

    @running = false
    @in_callback = false
  end
start(*args, &b)

class methods

[Source]

# File tk/lib/tk/timer.rb, line 31
  def self.start(*args, &b)
    self.new(*args, &b).start
  end

Public Instance methods

add_procs(*procs)

[Source]

# File tk/lib/tk/timer.rb, line 296
  def add_procs(*procs)
    procs.each{|e|
      # if e.kind_of?(Proc)
      if TkComm._callback_entry?(e)
        @loop_proc.push([e])
      else
        @loop_proc.push(e)
      end
    }
    @proc_max = @loop_proc.size

    self
  end
cancel()

[Source]

# File tk/lib/tk/timer.rb, line 422
  def cancel
    @running = false
    @wait_var.value = 0
    tk_call 'after', 'cancel', @after_id if @after_id
    @after_id = nil

    Tk_CBTBL.delete(@id) ;# for GC
    self
  end
cancel_on_exception=(mode)

[Source]

# File tk/lib/tk/timer.rb, line 224
  def cancel_on_exception=(mode)
    if mode.kind_of?(Array)
      @cancel_on_exception = mode
    elsif mode
      @cancel_on_exception = DEFAULT_IGNORE_EXCEPTIONS
    else
      @cancel_on_exception = false
    end
    #self
  end
cancel_on_exception?()

[Source]

# File tk/lib/tk/timer.rb, line 220
  def cancel_on_exception?
    @cancel_on_exception
  end
cb_call()

[Source]

# File tk/lib/tk/timer.rb, line 207
  def cb_call
    @cb_cmd.call
  end
continue(wait=nil)

[Source]

# File tk/lib/tk/timer.rb, line 433
  def continue(wait=nil)
    fail RuntimeError, "is already running" if @running
    return restart() if @current_script.empty?
    sleep, cmd = @current_script
    fail RuntimeError, "no procedure to continue" unless cmd
    if wait
      unless wait.kind_of?(Integer)
        fail ArgumentError, "expect Integer for 1st argument"
      end
      sleep = wait
    end
    Tk_CBTBL[@id] = self
    @running = true
    @after_id = tk_call_without_enc('after', sleep, cmd)
    self
  end
current_status()

[Source]

# File tk/lib/tk/timer.rb, line 215
  def current_status
    [@running, @current_sleep, @current_proc, @current_args,
      @do_loop, @cancel_on_exception]
  end
delete_at(n)

[Source]

# File tk/lib/tk/timer.rb, line 326
  def delete_at(n)
    @loop_proc.delete_at(n)
    @proc_max = @loop_proc.size
    cancel if @proc_max == 0
    self
  end
delete_procs(*procs)

[Source]

# File tk/lib/tk/timer.rb, line 310
  def delete_procs(*procs)
    procs.each{|e|
      # if e.kind_of?(Proc)
      if TkComm._callback_entry?(e)
        @loop_proc.delete([e])
      else
        @loop_proc.delete(e)
      end
    }
    @proc_max = @loop_proc.size

    cancel if @proc_max == 0

    self
  end
do_callback()

instance methods

[Source]

# File tk/lib/tk/timer.rb, line 65
  def do_callback
    @in_callback = true
    @after_id = nil
    begin
      @return_value = @current_proc.call(self)
    rescue SystemExit
      exit(0)
    rescue Interrupt
      exit!(1)
    rescue Exception => e
      if @cancel_on_exception &&
          @cancel_on_exception.find{|exc| e.kind_of?(exc)}
        cancel
        @return_value = e
        @in_callback = false
        return e
      else
        fail e
      end
    end
    if @set_next
      set_next_callback(@current_args)
    else
      @set_next = true
    end
    @in_callback = false
    @return_value
  end
eventloop_tkwait()

[Source]

# File tk/lib/tk/timer.rb, line 497
  def eventloop_tkwait
    wait(false, true)
  end
eventloop_wait(check_root = false)

[Source]

# File tk/lib/tk/timer.rb, line 488
  def eventloop_wait(check_root = false)
    wait(false, check_root)
  end
get_procs()

[Source]

# File tk/lib/tk/timer.rb, line 211
  def get_procs
    [@init_sleep, @init_proc, @init_args, @sleep_time, @loop_exec, @loop_proc]
  end
info()

[Source]

# File tk/lib/tk/timer.rb, line 459
  def info
    if @after_id
      inf = tk_split_list(tk_call_without_enc('after', 'info', @after_id))
      [Tk_CBTBL[inf[0][1]], inf[1]]
    else
      nil
    end
  end
loop_rest()

[Source]

# File tk/lib/tk/timer.rb, line 239
  def loop_rest
    @do_loop
  end
loop_rest=(rest)

[Source]

# File tk/lib/tk/timer.rb, line 243
  def loop_rest=(rest)
    @do_loop = rest
    #self
  end
reset(*reset_args)

[Source]

# File tk/lib/tk/timer.rb, line 395
  def reset(*reset_args)
    restart() if @running

    if @init_proc
      @return_value = @init_proc.call(self)
    else
      @return_value = nil
    end

    @current_pos   = 0
    @current_args  = @init_args
    @current_script = []

    @set_next = false if @in_callback

    self
  end
restart(*restart_args, &b)

[Source]

# File tk/lib/tk/timer.rb, line 413
  def restart(*restart_args, &b)
    cancel if @running
    if restart_args == [] && !b
      start(@init_sleep, @init_proc, *@init_args)
    else
      start(*restart_args, &b)
    end
  end
running?()

[Source]

# File tk/lib/tk/timer.rb, line 235
  def running?
    @running
  end
set_callback(sleep, args=nil)

[Source]

# File tk/lib/tk/timer.rb, line 94
  def set_callback(sleep, args=nil)
    if TkCore::INTERP.deleted?
      self.cancel
      return self
    end
    @after_script = "rb_after #{@id}"
    @after_id = tk_call_without_enc('after', sleep, @after_script)
    @current_args = args
    @current_script = [sleep, @after_script]
    self
  end
set_interval(interval)

[Source]

# File tk/lib/tk/timer.rb, line 248
  def set_interval(interval)
    #if interval != 'idle' && interval != :idle      #  && !interval.kind_of?(Integer) && !interval.kind_of?(Proc)
    if interval != 'idle' && interval != :idle \
      && !interval.kind_of?(Integer) && !TkComm._callback_entry?(interval)
      fail ArgumentError, "expect Integer or Proc"
    end
    @sleep_time = interval
  end
set_next_callback(args)

[Source]

# File tk/lib/tk/timer.rb, line 106
  def set_next_callback(args)
    if @running == false || @proc_max == 0 || @do_loop == 0
      Tk_CBTBL.delete(@id) ;# for GC
      @running = false
      @wait_var.value = 0
      return
    end
    if @current_pos >= @proc_max
      if @do_loop < 0 || (@do_loop -= 1) > 0
        @current_pos = 0
      else
        Tk_CBTBL.delete(@id) ;# for GC
        @running = false
        @wait_var.value = 0
        return
      end
    end

    @current_args = args

    # if @sleep_time.kind_of?(Proc)
    if TkComm._callback_entry?(@sleep_time)
      sleep = @sleep_time.call(self)
    else
      sleep = @sleep_time
    end
    @current_sleep = sleep

    cmd, *cmd_args = @loop_proc[@current_pos]
    @current_pos += 1
    @current_proc = cmd

    set_callback(sleep, cmd_args)
  end
set_procs(interval, loop_exec, *procs)

[Source]

# File tk/lib/tk/timer.rb, line 258
  def set_procs(interval, loop_exec, *procs)
    #if interval != 'idle' && interval != :idle      #   && !interval.kind_of?(Integer) && !interval.kind_of?(Proc)
    if interval != 'idle' && interval != :idle \
      && !interval.kind_of?(Integer) && !TkComm._callback_entry?(interval)
      fail ArgumentError, "expect Integer or Proc for 1st argument"
    end
    @sleep_time = interval

    @loop_proc = []
    procs.each{|e|
      # if e.kind_of?(Proc)
      if TkComm._callback_entry?(e)
        @loop_proc.push([e])
      else
        @loop_proc.push(e)
      end
    }
    @proc_max = @loop_proc.size
    @current_pos = 0

    if loop_exec.kind_of?(Integer) && loop_exec < 0
      @loop_exec = -1
    elsif loop_exec == true
      @loop_exec = -1
    elsif loop_exec == nil || loop_exec == false || loop_exec == 0
      @loop_exec = 0
    else
      if not loop_exec.kind_of?(Integer)
        fail ArgumentError, "expect Integer for 2nd argument"
      end
      @loop_exec = loop_exec
    end
    @do_loop = @loop_exec

    self
  end
set_start_proc(sleep=nil, init_proc=nil, *init_args, &b)

[Source]

# File tk/lib/tk/timer.rb, line 333
  def set_start_proc(sleep=nil, init_proc=nil, *init_args, &b)
    # set parameters for 'restart'
    sleep = @init_sleep unless sleep

    if sleep != 'idle' && sleep != :idle && !sleep.kind_of?(Integer)
      fail ArgumentError, "expect Integer or 'idle' for 1st argument"
    end

    @init_sleep = sleep
    @init_proc = init_proc
    @init_args = init_args

    @init_proc = b if !@init_proc && b
    @init_proc = proc{|*args| } if @init_sleep > 0 && !@init_proc

    self
  end
skip()

[Source]

# File tk/lib/tk/timer.rb, line 450
  def skip
    fail RuntimeError, "is not running now" unless @running
    cancel
    Tk_CBTBL[@id] = self
    @running = true
    set_next_callback(@current_args)
    self
  end
start(*init_args, &b)

[Source]

# File tk/lib/tk/timer.rb, line 351
  def start(*init_args, &b)
    return nil if @running

    Tk_CBTBL[@id] = self
    @do_loop = @loop_exec
    @current_pos = 0
    @return_value = nil
    @after_id = nil

    @init_sleep = 0
    @init_proc  = nil
    @init_args  = nil

    argc = init_args.size
    if argc > 0
      sleep = init_args.shift
      if sleep != 'idle' && sleep != :idle && !sleep.kind_of?(Integer)
        fail ArgumentError, "expect Integer or 'idle' for 1st argument"
      end
      @init_sleep = sleep
    end
    @init_proc = init_args.shift if argc > 1
    @init_args = init_args if argc > 2

    @init_proc = b if !@init_proc && b
    @init_proc = proc{|*args| } if @init_sleep > 0 && !@init_proc

    @current_sleep = @init_sleep
    @running = true
    if @init_proc
      # if not @init_proc.kind_of?(Proc)
      if !TkComm._callback_entry?(@init_proc)
        fail ArgumentError, "Argument '#{@init_proc}' need to be Proc"
      end
      @current_proc = @init_proc
      set_callback(@init_sleep, @init_args)
      @set_next = false if @in_callback
    else
      set_next_callback(@init_args)
    end

    self
  end
stop()

Alias for cancel

thread_tkwait()

[Source]

# File tk/lib/tk/timer.rb, line 500
  def thread_tkwait
    wait(true, true)
  end
thread_wait(check_root = false)

[Source]

# File tk/lib/tk/timer.rb, line 491
  def thread_wait(check_root = false)
    wait(true, check_root)
  end
tkwait(on_thread = true)

[Source]

# File tk/lib/tk/timer.rb, line 494
  def tkwait(on_thread = true)
    wait(on_thread, true)
  end
wait(on_thread = true, check_root = false)

[Source]

# File tk/lib/tk/timer.rb, line 468
  def wait(on_thread = true, check_root = false)
    if $SAFE >= 4
      fail SecurityError, "can't wait timer at $SAFE >= 4"
    end

    unless @running
      if @return_value.kind_of?(Exception)
        fail @return_value
      else
        return @return_value
      end
    end

    @wait_var.wait(on_thread, check_root)
    if @return_value.kind_of?(Exception)
      fail @return_value
    else
      @return_value
    end
  end


Class: TkToplevel

Class | TkToplevel
In: | tk/lib/tkextlib/tktrans/tktrans.rb tk/lib/tk/toplevel.rb
Parent: | Object

Methods

add_menu add_menubar bind bind_append bind_remove bindinfo database_class database_classname new specific_class tktrans_get_image tktrans_set_image

Included Modules

Wm TkMenuSpec

Constants

TkCommandNames | = | ['toplevel'.freeze].freeze
WidgetClassName | = | 'Toplevel'.freeze

Public Class methods

bind(*args, &b)

[Source]

# File tk/lib/tk/toplevel.rb, line 229
  def self.bind(*args, &b)
    if self == WidgetClassNames[WidgetClassName] || self.name == ''
      super(*args, &b)
    else
      TkDatabaseClass.new(self.name).bind(*args, &b)
    end
  end
bind_append(*args, &b)

[Source]

# File tk/lib/tk/toplevel.rb, line 236
  def self.bind_append(*args, &b)
    if self == WidgetClassNames[WidgetClassName] || self.name == ''
      super(*args, &b)
    else
      TkDatabaseClass.new(self.name).bind_append(*args, &b)
    end
  end
bind_remove(*args)

[Source]

# File tk/lib/tk/toplevel.rb, line 243
  def self.bind_remove(*args)
    if self == WidgetClassNames[WidgetClassName] || self.name == ''
      super(*args)
    else
      TkDatabaseClass.new(self.name).bind_remove(*args)
    end
  end
bindinfo(*args)

[Source]

# File tk/lib/tk/toplevel.rb, line 250
  def self.bindinfo(*args)
    if self == WidgetClassNames[WidgetClassName] || self.name == ''
      super(*args)
    else
      TkDatabaseClass.new(self.name).bindinfo(*args)
    end
  end
database_class()

[Source]

# File tk/lib/tk/toplevel.rb, line 218
  def self.database_class
    if self == WidgetClassNames[WidgetClassName] || self.name == ''
      self
    else
      TkDatabaseClass.new(self.name)
    end
  end
database_classname()

[Source]

# File tk/lib/tk/toplevel.rb, line 225
  def self.database_classname
    self.database_class.name
  end
new(parent=nil, screen=nil, classname=nil, keys=nil)

[Source]

# File tk/lib/tk/toplevel.rb, line 98
  def initialize(parent=nil, screen=nil, classname=nil, keys=nil)
    my_class_name = nil
    if self.class < WidgetClassNames[WidgetClassName]
      my_class_name = self.class.name
      my_class_name = nil if my_class_name == ''
    end
    if parent.kind_of? Hash
      keys = _symbolkey2str(parent)
      if keys.key?('classname')
        keys['class'] = keys.delete('classname')
      end
      @classname = keys['class']
      @colormap  = keys['colormap']
      @container = keys['container']
      @screen    = keys['screen']
      @use       = keys['use']
      @visual    = keys['visual']
      if !@classname && my_class_name
        keys['class'] = @classname = my_class_name
      end
      if @classname.kind_of? TkBindTag
        @db_class = @classname
        @classname = @classname.id
      elsif @classname
        @db_class = TkDatabaseClass.new(@classname)
      else
        @db_class = self.class
        @classname = @db_class::WidgetClassName
      end
      keys, cmds = _wm_command_option_chk(keys)
      super(keys)
      cmds.each{|k,v|
        if v.kind_of? Array
          self.__send__(k,*v)
        else
          self.__send__(k,v)
        end
      }
      return
    end

    if screen.kind_of? Hash
      keys = screen
    else
      @screen = screen
      if classname.kind_of? Hash
        keys = classname
      else
        @classname = classname
      end
    end
    if keys.kind_of? Hash
      keys = _symbolkey2str(keys)
      if keys.key?('classname')
        keys['class'] = keys.delete('classname')
      end
      @classname = keys['class']  unless @classname
      @colormap  = keys['colormap']
      @container = keys['container']
      @screen    = keys['screen'] unless @screen
      @use       = keys['use']
      @visual    = keys['visual']
    else
      keys = {}
    end
    if !@classname && my_class_name
      keys['class'] = @classname = my_class_name
    end
    if @classname.kind_of? TkBindTag
      @db_class = @classname
      @classname = @classname.id
    elsif @classname
      @db_class = TkDatabaseClass.new(@classname)
    else
      @db_class = self.class
      @classname = @db_class::WidgetClassName
    end
    keys, cmds = _wm_command_option_chk(keys)
    super(parent, keys)
    cmds.each{|k,v|
      if v.kind_of? Array
        self.send(k,*v)
      else
        self.send(k,v)
      end
    }
  end

Public Instance methods

add_menu(menu_info, tearoff=false, opts=nil)

[Source]

# File tk/lib/tk/toplevel.rb, line 199
  def add_menu(menu_info, tearoff=false, opts=nil)
    # See tk/menuspec.rb for menu_info.
    # opts is a hash of default configs for all of cascade menus.
    # Configs of menu_info can override it.
    if tearoff.kind_of?(Hash)
      opts = tearoff
      tearoff = false
    end
    _create_menubutton(self, menu_info, tearoff, opts)
  end
add_menubar(menu_spec, tearoff=false, opts=nil)

[Source]

# File tk/lib/tk/toplevel.rb, line 210
  def add_menubar(menu_spec, tearoff=false, opts=nil)
    # See tk/menuspec.rb for menu_spec.
    # opts is a hash of default configs for all of cascade menus.
    # Configs of menu_spec can override it.
    menu_spec.each{|info| add_menu(info, tearoff, opts)}
    self.menu
  end
specific_class()

def create_self(keys)

  if keys and keys != None
    tk_call_without_enc('toplevel', @path, *hash_kv(keys, true))
  else
    tk_call_without_enc('toplevel', @path)
  end

end private :create_self

[Source]

# File tk/lib/tk/toplevel.rb, line 195
  def specific_class
    @classname
  end
tktrans_get_image()

[Source]

# File tk/lib/tkextlib/tktrans/tktrans.rb, line 61
  def tktrans_get_image()
    tk_send('tktrans::settoplevel', @path)
  end
tktrans_set_image(img)

[Source]

# File tk/lib/tkextlib/tktrans/tktrans.rb, line 57
  def tktrans_set_image(img)
    tk_send('tktrans::settoplevel', @path, img)
    self
  end


Module: TkTreatFont

Module | TkTreatFont
In: | tk/lib/tk.rb

Methods

asciifont_configure asciifont_copy font_configinfo font_configure font_copy fontobj kanjifont_configure kanjifont_copy latinfont_configure latinfont_copy

Public Instance methods

asciifont_configure(ltn, keys=nil)

Alias for latinfont_configure

asciifont_copy(win, wintag=nil, winkey=nil, targetkey=nil)

Alias for latinfont_copy

font_configinfo(key = nil)

[Source]

# File tk/lib/tk.rb, line 2392
  def font_configinfo(key = nil)
    optkeys = __font_optkeys
    if key && !optkeys.find{|opt| opt.to_s == key.to_s}
      fail ArgumentError, "unknown font option name `#{key}'"
    end

    win, tag = __pathname.split(':')

    if key
      pathname = [win, tag, key].join(';')
      TkFont.used_on(pathname) ||
        TkFont.init_widget_font(pathname, *__confinfo_cmd)
    elsif optkeys.size == 1
      pathname = [win, tag, optkeys[0]].join(';')
      TkFont.used_on(pathname) ||
        TkFont.init_widget_font(pathname, *__confinfo_cmd)
    else
      fonts = {}
      optkeys.each{|key|
        key = key.to_s
        pathname = [win, tag, key].join(';')
        fonts[key] =
          TkFont.used_on(pathname) ||
          TkFont.init_widget_font(pathname, *__confinfo_cmd)
      }
      fonts
    end
  end
font_configure(slot)

[Source]

# File tk/lib/tk.rb, line 2422
  def font_configure(slot)
    pathname = __pathname

    slot = _symbolkey2str(slot)

    __font_optkeys.each{|optkey|
      optkey = optkey.to_s
      l_optkey = 'latin' << optkey
      a_optkey = 'ascii' << optkey
      k_optkey = 'kanji' << optkey

      if slot.key?(optkey)
        fnt = slot.delete(optkey)
        if fnt.kind_of?(TkFont)
          slot.delete(l_optkey)
          slot.delete(a_optkey)
          slot.delete(k_optkey)

          fnt.call_font_configure([pathname, optkey], *(__config_cmd << {}))
          next
        else
          if fnt
            if (slot.key?(l_optkey) ||
                slot.key?(a_optkey) ||
                slot.key?(k_optkey))
              fnt = TkFont.new(fnt)

              lfnt = slot.delete(l_optkey)
              lfnt = slot.delete(a_optkey) if slot.key?(a_optkey)
              kfnt = slot.delete(k_optkey)

              fnt.latin_replace(lfnt) if lfnt
              fnt.kanji_replace(kfnt) if kfnt

              fnt.call_font_configure([pathname, optkey],
                                      *(__config_cmd << {}))
              next
            else
              fnt = hash_kv(fnt) if fnt.kind_of?(Hash)
              tk_call(*(__config_cmd << "-#{optkey}" << fnt))
            end
          end
          next
        end
      end

      lfnt = slot.delete(l_optkey)
      lfnt = slot.delete(a_optkey) if slot.key?(a_optkey)
      kfnt = slot.delete(k_optkey)

      if lfnt && kfnt
        TkFont.new(lfnt, kfnt).call_font_configure([pathname, optkey],
                                                   *(__config_cmd << {}))
      elsif lfnt
        latinfont_configure([lfnt, optkey])
      elsif kfnt
        kanjifont_configure([kfnt, optkey])
      end
    }

    # configure other (without font) options
    tk_call(*(__config_cmd.concat(hash_kv(slot)))) if slot != {}
    self
  end
font_copy(win, wintag=nil, winkey=nil, targetkey=nil)

[Source]

# File tk/lib/tk.rb, line 2590
  def font_copy(win, wintag=nil, winkey=nil, targetkey=nil)
    if wintag
      if winkey
        fnt = win.tagfontobj(wintag, winkey).dup
      else
        fnt = win.tagfontobj(wintag).dup
      end
    else
      if winkey
        fnt = win.fontobj(winkey).dup
      else
        fnt = win.fontobj.dup
      end
    end

    if targetkey
      fnt.call_font_configure([__pathname, targetkey], *(__config_cmd << {}))
    else
      fnt.call_font_configure(__pathname, *(__config_cmd << {}))
    end
    self
  end
fontobj(key = nil)

Alias for font_configinfo

kanjifont_configure(knj, keys=nil)

[Source]

# File tk/lib/tk.rb, line 2539
  def kanjifont_configure(knj, keys=nil)
    if knj.kind_of?(Array)
      key = knj[1]
      knj = knj[0]
    else
      key = nil
    end

    optkeys = __font_optkeys
    if key && !optkeys.find{|opt| opt.to_s == key.to_s}
      fail ArgumentError, "unknown font option name `#{key}'"
    end

    win, tag = __pathname.split(':')

    optkeys = [key] if key

    optkeys.each{|optkey|
      optkey = optkey.to_s

      pathname = [win, tag, optkey].join(';')

      if (fobj = TkFont.used_on(pathname))
        fobj = TkFont.new(fobj) # create a new TkFont object
      elsif Tk::JAPANIZED_TK
        fobj = fontobj          # create a new TkFont object
      else
        knj = hash_kv(knj) if knj.kind_of?(Hash)
        tk_call(*(__config_cmd << "-#{optkey}" << knj))
        next
      end

      if fobj.kind_of?(TkFont)
        if knj.kind_of?(TkFont)
          conf = {}
          knj.kanji_configinfo.each{|key,val| conf[key] = val}
          if keys
            fobj.kanji_configure(conf.update(keys))
          else
            fobj.kanji_configure(conf)
          end
        else
          fobj.kanji_replace(knj)
        end
      end

      fobj.call_font_configure([pathname, optkey], *(__config_cmd << {}))
    }
    self
  end
kanjifont_copy(win, wintag=nil, winkey=nil, targetkey=nil)

[Source]

# File tk/lib/tk.rb, line 2638
  def kanjifont_copy(win, wintag=nil, winkey=nil, targetkey=nil)
    if targetkey
      fontobj(targetkey).dup.call_font_configure([__pathname, targetkey],
                                                 *(__config_cmd << {}))
    else
        fontobj.dup.call_font_configure(__pathname, *(__config_cmd << {}))
    end

    if wintag
      if winkey
        fontobj.kanji_replace(win.tagfontobj(wintag, winkey).kanji_font_id)
      else
        fontobj.kanji_replace(win.tagfontobj(wintag).kanji_font_id)
      end
    else
      if winkey
        fontobj.kanji_replace(win.fontobj(winkey).kanji_font_id)
      else
        fontobj.kanji_replace(win.fontobj.kanji_font_id)
      end
    end
    self
  end
latinfont_configure(ltn, keys=nil)

[Source]

# File tk/lib/tk.rb, line 2487
  def latinfont_configure(ltn, keys=nil)
    if ltn.kind_of?(Array)
      key = ltn[1]
      ltn = ltn[0]
    else
      key = nil
    end

    optkeys = __font_optkeys
    if key && !optkeys.find{|opt| opt.to_s == key.to_s}
      fail ArgumentError, "unknown font option name `#{key}'"
    end

    win, tag = __pathname.split(':')

    optkeys = [key] if key

    optkeys.each{|optkey|
      optkey = optkey.to_s

      pathname = [win, tag, optkey].join(';')

      if (fobj = TkFont.used_on(pathname))
        fobj = TkFont.new(fobj) # create a new TkFont object
      elsif Tk::JAPANIZED_TK
        fobj = fontobj          # create a new TkFont object
      else
        ltn = hash_kv(ltn) if ltn.kind_of?(Hash)
        tk_call(*(__config_cmd << "-#{optkey}" << ltn))
        next
      end

      if fobj.kind_of?(TkFont)
        if ltn.kind_of?(TkFont)
          conf = {}
          ltn.latin_configinfo.each{|key,val| conf[key] = val}
          if keys
            fobj.latin_configure(conf.update(keys))
          else
            fobj.latin_configure(conf)
          end
        else
          fobj.latin_replace(ltn)
        end
      end

      fobj.call_font_configure([pathname, optkey], *(__config_cmd << {}))
    }
    self
  end
latinfont_copy(win, wintag=nil, winkey=nil, targetkey=nil)

[Source]

# File tk/lib/tk.rb, line 2613
  def latinfont_copy(win, wintag=nil, winkey=nil, targetkey=nil)
    if targetkey
      fontobj(targetkey).dup.call_font_configure([__pathname, targetkey],
                                                 *(__config_cmd << {}))
    else
      fontobj.dup.call_font_configure(__pathname, *(__config_cmd << {}))
    end

    if wintag
      if winkey
        fontobj.latin_replace(win.tagfontobj(wintag, winkey).latin_font_id)
      else
        fontobj.latin_replace(win.tagfontobj(wintag).latin_font_id)
      end
    else
      if winkey
        fontobj.latin_replace(win.fontobj(winkey).latin_font_id)
      else
        fontobj.latin_replace(win.fontobj.latin_font_id)
      end
    end
    self
  end


Module: TkTreatItemFont

Module | TkTreatItemFont
In: | tk/lib/tk/itemfont.rb

Methods

asciitagfont_configure asciitagfont_copy kanjifont_copy kanjitagfont_configure latintagfont_configure latintagfont_copy tagfont_configinfo tagfont_configure tagfont_copy tagfontobj

Included Modules

TkItemFontOptkeys

Public Instance methods

asciitagfont_configure(tagOrId, ltn, keys=nil)

Alias for latintagfont_configure

asciitagfont_copy(tagOrId, win, wintag=nil, winkey=nil, targetkey=nil)

Alias for latintagfont_copy

kanjifont_copy(tagOrId, win, wintag=nil, winkey=nil, targetkey=nil)

[Source]

# File tk/lib/tk/itemfont.rb, line 276
  def kanjifont_copy(tagOrId, win, wintag=nil, winkey=nil, targetkey=nil)
    if targetkey
      fontobj(targetkey).dup.call_font_configure([__item_pathname(tagid(tagOrId)), targetkey],
                                                 *(__item_config_cmd(tagid(tagOrId)) << {}))
    else
        fontobj.dup.call_font_configure(__item_pathname(tagid(tagOrId)),
                                        *(__item_config_cmd(tagid(tagOrId)) << {}))
    end

    if wintag
      if winkey
        fontobj.kanji_replace(win.tagfontobj(wintag, winkey).kanji_font_id)
      else
        fontobj.kanji_replace(win.tagfontobj(wintag).kanji_font_id)
      end
    else
      if winkey
        fontobj.kanji_replace(win.fontobj(winkey).kanji_font_id)
      else
        fontobj.kanji_replace(win.fontobj.kanji_font_id)
      end
    end
    self
  end
kanjitagfont_configure(tagOrId, knj, keys=nil)

[Source]

# File tk/lib/tk/itemfont.rb, line 174
  def kanjitagfont_configure(tagOrId, knj, keys=nil)
    if knj.kind_of?(Array)
      key = knj[1]
      knj = knj[0]
    else
      key = nil
    end

    optkeys = __item_font_optkeys(tagid(tagOrId))
    if key && !optkeys.find{|opt| opt.to_s == key.to_s}
      fail ArgumentError, "unknown font option name `#{key}'"
    end

    win, tag = __item_pathname(tagid(tagOrId)).split(';')

    optkeys = [key] if key

    optkeys.each{|optkey|
      optkey = optkey.to_s

      pathname = [win, tag, optkey].join(';')

      if (fobj = TkFont.used_on(pathname))
        fobj = TkFont.new(fobj) # create a new TkFont object
      elsif Tk::JAPANIZED_TK
        fobj = fontobj          # create a new TkFont object
      else
        tk_call(*(__item_config_cmd(tagid(tagOrId)) << "-#{optkey}" << knj))
        next
      end

      if fobj.kind_of?(TkFont)
        if knj.kind_of?(TkFont)
          conf = {}
          knj.kanji_configinfo.each{|key,val| conf[key] = val}
          if keys
            fobj.kanji_configure(conf.update(keys))
          else
            fobj.kanji_configure(conf)
          end
        else
          fobj.kanji_replace(knj)
        end
      end

      fobj.call_font_configure([pathname, optkey], *(__item_config_cmd(tagid(tagOrId)) << {}))
    }
    self
  end
latintagfont_configure(tagOrId, ltn, keys=nil)

[Source]

# File tk/lib/tk/itemfont.rb, line 123
  def latintagfont_configure(tagOrId, ltn, keys=nil)
    if ltn.kind_of?(Array)
      key = ltn[1]
      ltn = ltn[0]
    else
      key = nil
    end

    optkeys = __item_font_optkeys(tagid(tagOrId))
    if key && !optkeys.find{|opt| opt.to_s == key.to_s}
      fail ArgumentError, "unknown font option name `#{key}'"
    end

    win, tag = __item_pathname(tagid(tagOrId)).split(';')

    optkeys = [key] if key

    optkeys.each{|optkey|
      optkey = optkey.to_s

      pathname = [win, tag, optkey].join(';')

      if (fobj = TkFont.used_on(pathname))
        fobj = TkFont.new(fobj) # create a new TkFont object
      elsif Tk::JAPANIZED_TK
        fobj = fontobj          # create a new TkFont object
      else
        tk_call(*(__item_config_cmd(tagid(tagOrId)) << "-#{optkey}" << ltn))
        next
      end

      if fobj.kind_of?(TkFont)
        if ltn.kind_of?(TkFont)
          conf = {}
          ltn.latin_configinfo.each{|key,val| conf[key] = val}
          if keys
            fobj.latin_configure(conf.update(keys))
          else
            fobj.latin_configure(conf)
          end
        else
          fobj.latin_replace(ltn)
        end
      end

      fobj.call_font_configure([pathname, optkey], *(__item_config_cmd(tagid(tagOrId)) << {}))
    }
    self
  end
latintagfont_copy(tagOrId, win, wintag=nil, winkey=nil, targetkey=nil)

[Source]

# File tk/lib/tk/itemfont.rb, line 250
  def latintagfont_copy(tagOrId, win, wintag=nil, winkey=nil, targetkey=nil)
    if targetkey
      fontobj(targetkey).dup.call_font_configure([__item_pathname(tagid(tagOrId)), targetkey],
                                                 *(__item_config_cmd(tagid(tagOrId)) << {}))
    else
      fontobj.dup.call_font_configure(__item_pathname(tagid(tagOrId)),
                                      *(__item_config_cmd(tagid(tagOrId)) << {}))
    end

    if wintag
      if winkey
        fontobj.latin_replace(win.tagfontobj(wintag, winkey).latin_font_id)
      else
        fontobj.latin_replace(win.tagfontobj(wintag).latin_font_id)
      end
    else
      if winkey
        fontobj.latin_replace(win.fontobj(winkey).latin_font_id)
      else
        fontobj.latin_replace(win.fontobj.latin_font_id)
      end
    end
    self
  end
tagfont_configinfo(tagOrId, key = nil)

[Source]

# File tk/lib/tk/itemfont.rb, line 25
  def tagfont_configinfo(tagOrId, key = nil)
    optkeys = __item_font_optkeys(tagid(tagOrId))
    if key && !optkeys.find{|opt| opt.to_s == key.to_s}
      fail ArgumentError, "unknown font option name `#{key}'"
    end

    win, tag = __item_pathname(tagid(tagOrId)).split(';')

    if key
      pathname = [win, tag, key].join(';')
      TkFont.used_on(pathname) ||
        TkFont.init_widget_font(pathname,
                                *(__item_confinfo_cmd(tagid(tagOrId))))
    elsif optkeys.size == 1
      pathname = [win, tag, optkeys[0]].join(';')
      TkFont.used_on(pathname) ||
        TkFont.init_widget_font(pathname,
                                *(__item_confinfo_cmd(tagid(tagOrId))))
    else
      fonts = {}
      optkeys.each{|key|
        key = key.to_s
        pathname = [win, tag, key].join(';')
        fonts[key] =
          TkFont.used_on(pathname) ||
          TkFont.init_widget_font(pathname,
                                  *(__item_confinfo_cmd(tagid(tagOrId))))
      }
      fonts
    end
  end
tagfont_configure(tagOrId, slot)

[Source]

# File tk/lib/tk/itemfont.rb, line 58
  def tagfont_configure(tagOrId, slot)
    pathname = __item_pathname(tagid(tagOrId))

    slot = _symbolkey2str(slot)

    __item_font_optkeys(tagid(tagOrId)).each{|optkey|
      optkey = optkey.to_s
      l_optkey = 'latin' << optkey
      a_optkey = 'ascii' << optkey
      k_optkey = 'kanji' << optkey

      if slot.key?(optkey)
        fnt = slot.delete(optkey)
        if fnt.kind_of?(TkFont)
          slot.delete(l_optkey)
          slot.delete(a_optkey)
          slot.delete(k_optkey)

          fnt.call_font_configure([pathname, optkey],
                                  *(__item_config_cmd(tagid(tagOrId)) << {}))
          next
        else
          if fnt
            if (slot.key?(l_optkey) ||
                slot.key?(a_optkey) ||
                slot.key?(k_optkey))
              fnt = TkFont.new(fnt)

              lfnt = slot.delete(l_optkey)
              lfnt = slot.delete(a_optkey) if slot.key?(a_optkey)
              kfnt = slot.delete(k_optkey)

              fnt.latin_replace(lfnt) if lfnt
              fnt.kanji_replace(kfnt) if kfnt

              fnt.call_font_configure([pathname, optkey],
                                      *(__item_config_cmd(tagid(tagOrId)) << {}))
              next
            else
              tk_call(*(__item_config_cmd(tagid(tagOrId)) << "-#{optkey}" << fnt))
            end
          end
          next
        end
      end

      lfnt = slot.delete(l_optkey)
      lfnt = slot.delete(a_optkey) if slot.key?(a_optkey)
      kfnt = slot.delete(k_optkey)

      if lfnt && kfnt
        TkFont.new(lfnt, kfnt).call_font_configure([pathname, optkey],
                                                   *(__item_config_cmd(tagid(tagOrId)) << {}))
      elsif lfnt
        latintagfont_configure([lfnt, optkey])
      elsif kfnt
        kanjitagfont_configure([kfnt, optkey])
      end
    }

    # configure other (without font) options
    tk_call(*(__item_config_cmd(tagid(tagOrId)).concat(hash_kv(slot)))) if slot != {}
    self
  end
tagfont_copy(tagOrId, win, wintag=nil, winkey=nil, targetkey=nil)

[Source]

# File tk/lib/tk/itemfont.rb, line 224
  def tagfont_copy(tagOrId, win, wintag=nil, winkey=nil, targetkey=nil)
    if wintag
      if winkey
        fnt = win.tagfontobj(wintag, winkey).dup
      else
        fnt = win.tagfontobj(wintag).dup
      end
    else
      if winkey
        fnt = win.fontobj(winkey).dup
      else
        fnt = win.fontobj.dup
      end
    end

    if targetkey
      fnt.call_font_configure([__item_pathname(tagid(tagOrId)), targetkey],
                              *(__item_config_cmd(tagid(tagOrId)) << {}))
    else
      fnt.call_font_configure(__item_pathname(tagid(tagOrId)),
                              *(__item_config_cmd(tagid(tagOrId)) << {}))
    end
    self
  end
tagfontobj(tagOrId, key = nil)

Alias for tagfont_configinfo


Module: TkTreatTagFont

Module | TkTreatTagFont
In: | tk/lib/tk/tagfont.rb

Methods

asciifont_configure asciifont_copy font_configinfo font_configure font_copy kanjifont_configure kanjifont_copy latinfont_configure latinfont_copy

Public Instance methods

asciifont_configure(ltn, keys=nil)

Alias for latinfont_configure

asciifont_copy(win, wintag=nil)

Alias for latinfont_copy

font_configinfo()

[Source]

# File tk/lib/tk/tagfont.rb, line 7
  def font_configinfo
    @parent.tagfont_configinfo(@id)
  end
font_configure(slot)

alias font font_configinfo

[Source]

# File tk/lib/tk/tagfont.rb, line 12
  def font_configure(slot)
    @parent.tagfont_configure(@id, slot)
    self
  end
font_copy(win, wintag=nil)

[Source]

# File tk/lib/tk/tagfont.rb, line 28
  def font_copy(win, wintag=nil)
    @parent.tagfont_copy(@id, win, wintag)
    self
  end
kanjifont_configure(knj, keys=nil)

[Source]

# File tk/lib/tk/tagfont.rb, line 23
  def kanjifont_configure(knj, keys=nil)
    @parent.kanjitagfont_configure(@id, ltn, keys)
    self
  end
kanjifont_copy(win, wintag=nil)

[Source]

# File tk/lib/tk/tagfont.rb, line 39
  def kanjifont_copy(win, wintag=nil)
    @parent.kanjitagfont_copy(@id, win, wintag)
    self
  end
latinfont_configure(ltn, keys=nil)

[Source]

# File tk/lib/tk/tagfont.rb, line 17
  def latinfont_configure(ltn, keys=nil)
    @parent.latintagfont_configure(@id, ltn, keys)
    self
  end
latinfont_copy(win, wintag=nil)

[Source]

# File tk/lib/tk/tagfont.rb, line 33
  def latinfont_copy(win, wintag=nil)
    @parent.latintagfont_copy(@id, win, wintag)
    self
  end


Module: TkUtil

Module | TkUtil
In: | tk/tkutil.c

Methods

_conv_args _conv_args _fromUTF8 _get_eval_enc_str _get_eval_enc_str _get_eval_string _get_eval_string _symbolkey2str _symbolkey2str _toUTF8 bool bool callback eval_cmd hash_kv hash_kv install_cmd num_or_str num_or_str number number string string uninstall_cmd

Classes and Modules

Class TkUtil::CallbackSubst

Public Class methods

_conv_args(...)
_get_eval_enc_str(p1)
_get_eval_string(...)
_symbolkey2str(p1)
bool(p1)

/

[Source]

/*************************************/

static VALUE
tcl2rb_bool(self, value)
    VALUE self;
    VALUE value;
{
    if (TYPE(value) == T_FIXNUM) {
        if (NUM2INT(value) == 0) {
            return Qfalse;
        } else {
            return Qtrue;
        }
    }

    if (TYPE(value) == T_TRUE || TYPE(value) == T_FALSE) {
        return value;
    }

    rb_check_type(value, T_STRING);

    value = rb_funcall(value, ID_downcase, 0);

    if (RSTRING(value)->ptr == (char*)NULL) return Qnil;

    if (RSTRING(value)->ptr[0] == '\0'
        || strcmp(RSTRING(value)->ptr, "0") == 0
        || strcmp(RSTRING(value)->ptr, "no") == 0
        || strcmp(RSTRING(value)->ptr, "off") == 0
        || strcmp(RSTRING(value)->ptr, "false") == 0) {
        return Qfalse;
    } else {
        return Qtrue;
    }
}
callback(...)
eval_cmd(...)

/

[Source]

/*************************************/

static VALUE
tk_eval_cmd(argc, argv, self)
    int argc;
    VALUE argv[];
    VALUE self;
{
    volatile VALUE cmd, rest, arg;
    volatile VALUE ret;
    int status;

    rb_scan_args(argc, argv, "1*", &cmd, &rest);
    return rb_eval_cmd(cmd, rest, 0);
}
hash_kv(...)
install_cmd(...)
num_or_str(p1)
number(p1)
string(p1)
uninstall_cmd(p1)

Public Instance methods

_conv_args(...)
_fromUTF8(...)
_get_eval_enc_str(p1)
_get_eval_string(...)
_symbolkey2str(p1)
_toUTF8(...)
bool(p1)

/

[Source]

/*************************************/

static VALUE
tcl2rb_bool(self, value)
    VALUE self;
    VALUE value;
{
    if (TYPE(value) == T_FIXNUM) {
        if (NUM2INT(value) == 0) {
            return Qfalse;
        } else {
            return Qtrue;
        }
    }

    if (TYPE(value) == T_TRUE || TYPE(value) == T_FALSE) {
        return value;
    }

    rb_check_type(value, T_STRING);

    value = rb_funcall(value, ID_downcase, 0);

    if (RSTRING(value)->ptr == (char*)NULL) return Qnil;

    if (RSTRING(value)->ptr[0] == '\0'
        || strcmp(RSTRING(value)->ptr, "0") == 0
        || strcmp(RSTRING(value)->ptr, "no") == 0
        || strcmp(RSTRING(value)->ptr, "off") == 0
        || strcmp(RSTRING(value)->ptr, "false") == 0) {
        return Qfalse;
    } else {
        return Qtrue;
    }
}
hash_kv(...)
num_or_str(p1)
number(p1)
string(p1)


Class: TkUtil::CallbackSubst

Class | TkUtil::CallbackSubst
In: | tk/tkutil.c
Parent: | Object

Methods

_define_attribute_aliases _get_all_subst_keys _get_extra_args_tbl _get_subst_key _setup_subst_table inspect new ret_val scan_args subst_arg

Classes and Modules

Class TkUtil::CallbackSubst::Info

Public Class methods

_define_attribute_aliases(p1)
_get_all_subst_keys()
_get_extra_args_tbl()
_get_subst_key(p1)
_setup_subst_table(p1, p2)
inspect()
new(...)
ret_val(p1)
scan_args(p1, p2)
subst_arg(...)


Class: TkUtil::CallbackSubst::Info

Class | TkUtil::CallbackSubst::Info
In: | tk/tkutil.c
Parent: | Object

Methods

inspect

Public Class methods

inspect()


Class: TkValidateCommand

Class | TkValidateCommand
In: | tk/lib/tk/validation.rb
Parent: | Object

Methods

_config_keys _initialize_for_cb_class new to_eval

Included Modules

TkComm

Classes and Modules

Class TkValidateCommand::ValidateArgs

Public Class methods

_config_keys()

[Source]

# File tk/lib/tk/validation.rb, line 271
  def self._config_keys
    # array of config-option key (string or symbol)
    ['vcmd', 'validatecommand', 'invcmd', 'invalidcommand']
  end
new(cmd = Proc.new, *args)

[Source]

# File tk/lib/tk/validation.rb, line 313
  def initialize(cmd = Proc.new, *args)
    _initialize_for_cb_class(self.class::ValidateArgs, cmd, *args)
  end

Public Instance methods

_initialize_for_cb_class(klass, cmd = Proc.new, *args)

[Source]

# File tk/lib/tk/validation.rb, line 276
  def _initialize_for_cb_class(klass, cmd = Proc.new, *args)
    extra_args_tbl = klass._get_extra_args_tbl

    if args.compact.size > 0
      args = args.join(' ')
      keys = klass._get_subst_key(args)
      if cmd.kind_of?(String)
        id = cmd
      elsif cmd.kind_of?(TkCallbackEntry)
        @id = install_cmd(cmd)
      else
        @id = install_cmd(proc{|*arg|
             ex_args = []
             extra_args_tbl.reverse_each{|conv| ex_args << conv.call(arg.pop)}
             klass.ret_val(cmd.call(
               *(ex_args.concat(klass.scan_args(keys, arg)))
             ))
        }) + ' ' + args
      end
    else
      keys, args = klass._get_all_subst_keys
      if cmd.kind_of?(String)
        id = cmd
      elsif cmd.kind_of?(TkCallbackEntry)
        @id = install_cmd(cmd)
      else
        @id = install_cmd(proc{|*arg|
             ex_args = []
             extra_args_tbl.reverse_each{|conv| ex_args << conv.call(arg.pop)}
             klass.ret_val(cmd.call(
               *(ex_args << klass.new(*klass.scan_args(keys, arg)))
             ))
        }) + ' ' + args
      end
    end
  end
to_eval()

[Source]

# File tk/lib/tk/validation.rb, line 317
  def to_eval
    @id
  end


Class: TkValidateCommand::ValidateArgs

Class | TkValidateCommand::ValidateArgs
In: | tk/lib/tk/validation.rb
Parent: | TkUtil::CallbackSubst

Methods

ret_val

Constants

KEY_TBL | = | [ [ ?d, ?n, :action ], [ ?i, ?x, :index ], [ ?s, ?e, :current ], [ ?v, ?s, :type ], [ ?P, ?e, :value ], [ ?S, ?e, :string ], [ ?V, ?s, :triggered ], [ ?W, ?w, :widget ], nil
PROC_TBL | = | [ [ ?n, TkComm.method(:number) ], [ ?s, TkComm.method(:string) ], [ ?w, TkComm.method(:window) ], [ ?e, proc{|val| #enc = Tk.encoding enc = ((Tk.encoding)? Tk.encoding : Tk.encoding_system)

Public Class methods

ret_val(val)

def self._get_extra_args_tbl

  # return an array of convert procs
  []

end

[Source]

# File tk/lib/tk/validation.rb, line 264
    def self.ret_val(val)
      (val)? '1': '0'
    end


Module: TkValidation

Module | TkValidation
In: | tk/lib/tk/validation.rb

Methods

__validation_class_list

Included Modules

Tk::ValidateConfigure

Classes and Modules

Class TkValidation::ValidateCmd

Public Instance methods

__validation_class_list()

[Source]

# File tk/lib/tk/validation.rb, line 339
  def __validation_class_list
    super() << ValidateCmd
  end


Class: TkValidation::ValidateCmd

Class | TkValidation::ValidateCmd
In: | tk/lib/tk/validation.rb
Parent: | TkValidateCommand

Classes and Modules

Module TkValidation::ValidateCmd::Action


Module: TkValidation::ValidateCmd::Action

Module | TkValidation::ValidateCmd::Action
In: | tk/lib/tk/validation.rb

Constants

Insert | = | 1
Delete | = | 0
Others | = | -1
Focus | = | -1
Forced | = | -1
Textvariable | = | -1
TextVariable | = | -1


Class: TkVarAccess

Class | TkVarAccess
In: | tk/lib/tk/variable.rb
Parent: | TkVariable

Methods

new new new_hash

Public Class methods

new(name, *args)

[Source]

# File tk/lib/tk/variable.rb, line 1532
  def self.new(name, *args)
    if name.kind_of?(TkVariable)
      name.value = args[0] unless args.empty?
      return name
    end

    if v = TkVar_ID_TBL[name]
      v.value = args[0] unless args.empty?
      return v
    end

    super(name, *args)
  end
new(varname, val=nil)

[Source]

# File tk/lib/tk/variable.rb, line 1571
  def initialize(varname, val=nil)
    @id = varname
    TkVar_ID_TBL[@id] = self

    @var  = @id
    @elem = nil

    @def_default = false
    @default_val = nil

    @trace_var  = nil
    @trace_elem = nil
    @trace_opts = nil

    @type = nil
    var = self
    @element_type = Hash.new{|k,v| var.default_value_type }

    # is an element?
    if @id =~ /^([^(]+)\((.+)\)$/
      # is an element --> var == $1, elem == $2
      @var  = $1
      @elem = $2
    end

    # teach Tk-ip that @id is global var
    INTERP._invoke_without_enc('global', @var)
??

    if val
      if val.kind_of?(Hash)
        # assoc-array variable
        self[''] = 0
        self.clear
      end
      #s = '"' + _get_eval_string(val).gsub(/[\[\]$"]/, '\\\\\&') + '"' #"
      #s = '"' + _get_eval_string(val).gsub(/[\[\]$"\\]/, '\\\\\&') + '"' #"
      #INTERP._eval(Kernel.format('global %s; set %s %s', @id, @id, s))
      #INTERP._set_global_var(@id, _toUTF8(_get_eval_string(val)))
      self.value = val
    end
  end
new_hash(name, *args)

[Source]

# File tk/lib/tk/variable.rb, line 1546
  def self.new_hash(name, *args)
    if name.kind_of?(TkVariable)
      unless name.is_hash?
        fail ArgumentError, "already exist as a scalar variable"
      end
      name.value = args[0] unless args.empty?
      return name
    end

    if v = TkVar_ID_TBL[name]
      unless v.is_hash?
        fail ArgumentError, "already exist as a scalar variable"
      end
      v.value = args[0] unless args.empty?
      return v
    end

    INTERP._invoke_without_enc('global', name)
    if args.empty? && INTERP._invoke_without_enc('array', 'exist', name) == '0'
      self.new(name, {})  # force creating
    else
      self.new(name, *args)
    end
  end


Class: TkVariable

Class | TkVariable
In: | tk/lib/tk/variable.rb
Parent: | Object

Methods

% & * ** + - / <=> == =~ [] []= []= _trace_vinfo_for_element bool bool= bool_element bool_type= callback clear coerce default_element_value_type default_proc default_value default_value= default_value_type default_value_type= element_lappend element_lget element_lget_f element_lget_i element_lindex element_lset element_to_a element_to_f element_to_i element_to_s element_to_sym eventloop_tkwait eventloop_wait exist? id inspect is_hash? is_scalar? keys lappend lget lget_f lget_i lindex list list= list_element list_type= lset new new_hash nonzero? numeric numeric= numeric_element numeric_type= numlist numlist= numlist_element numlist_type= procedure procedure= procedure_element procedure_type= ref remove remove set_bool set_bool_element set_bool_element_type set_bool_type set_default_element_value_type set_default_value set_default_value_type set_element_value set_element_value_type set_list set_list_element set_list_element_type set_list_type set_numeric set_numeric_element set_numeric_element_type set_numeric_type set_numlist set_numlist_element set_numlist_element_type set_numlist_type set_procedure set_procedure_element set_procedure_element_type set_procedure_type set_string set_string_element set_string_element_type set_string_type set_symbol set_symbol_element set_symbol_element_type set_symbol_type set_value set_value_type set_variable set_variable_element set_variable_element_type set_variable_type set_window set_window_element set_window_element_type set_window_type size string string= string_element string_type= symbol symbol= symbol_element symbol_type= thread_tkwait thread_wait tkwait to_a to_eval to_f to_i to_s to_sym trace trace_callback trace_element trace_vdelete trace_vdelete_for_element trace_vinfo undef_default unset unset update value value= value= value_type= variable variable= variable_element variable_type= wait window window= window_element window_type= zero? |

Included Modules

Tk Comparable

Constants

TkCommandNames | = | ['vwait'.freeze].freeze | TkCommandNames = [‘tkwait’.freeze].freeze
TkVar_CB_TBL | = | TkCore::INTERP.create_table | TkVar_CB_TBL = {} TkVar_ID_TBL = {}
TkVar_ID_TBL | = | TkCore::INTERP.create_table
Tk_VARIABLE_ID | = | ["v".freeze, "00000".taint].freeze
USE_TCLs_SET_VARIABLE_FUNCTIONS | = | true

Public Class methods

callback(id, name1, name2, op)

def TkVariable.callback(args)

[Source]

# File tk/lib/tk/variable.rb, line 45
  def TkVariable.callback(id, name1, name2, op)
    #name1,name2,op = tk_split_list(args)
    #name1,name2,op = tk_split_simplelist(args)
    if TkVar_CB_TBL[id]
      #_get_eval_string(TkVar_CB_TBL[name1].trace_callback(name2,op))
      begin
        _get_eval_string(TkVar_CB_TBL[id].trace_callback(name2, op))
      rescue SystemExit
        exit(0)
      rescue Interrupt
        exit!(1)
      rescue Exception => e
        begin
          msg = _toUTF8(e.class.inspect) + ': ' +
                _toUTF8(e.message) + "\n" +
                "\n---< backtrace of Ruby side >-----\n" +
                _toUTF8(e.backtrace.join("\n")) +
                "\n---< backtrace of Tk side >-------"
          msg.instance_variable_set(:@encoding, 'utf-8')
        rescue Exception
          msg = e.class.inspect + ': ' + e.message + "\n" +
                "\n---< backtrace of Ruby side >-----\n" +
                e.backtrace.join("\n") +
                "\n---< backtrace of Tk side >-------"
        end
        fail(e, msg)
      end
??
    else
      ''
    end
  end
new(val="", type=nil)

[Source]

# File tk/lib/tk/variable.rb, line 268
  def initialize(val="", type=nil)
    # @id = Tk_VARIABLE_ID.join('')
    @id = Tk_VARIABLE_ID.join(TkCore::INTERP._ip_id_)
    Tk_VARIABLE_ID[1].succ!
    TkVar_ID_TBL[@id] = self

    @var  = @id
    @elem = nil

    @def_default = false
    @default_val = nil

    @trace_var  = nil
    @trace_elem = nil
    @trace_opts = nil

    @type = nil
    var = self
    @element_type = Hash.new{|k,v| var.default_value_type }

    self.default_value_type = type

    begin
      INTERP._unset_global_var(@id)
    rescue
    end

    # teach Tk-ip that @id is global var
    INTERP._invoke_without_enc('global', @id)
    #INTERP._invoke('global', @id)

    # create and init
    if val.kind_of?(Hash)
      # assoc-array variable
      self[''] = 0
      self.clear
    end
    self.value = val

??
??
  end
new_hash(val = {})

[Source]

# File tk/lib/tk/variable.rb, line 92
  def self.new_hash(val = {})
    if val.kind_of?(Hash)
      self.new(val)
    else
      fail ArgumentError, 'Hash is expected'
    end
  end

Public Instance methods

%(other)

[Source]

# File tk/lib/tk/variable.rb, line 1187
  def %(other)
    num_or_str(self._value) % other.to_i
    #begin
    #  number(self._value) % other
    #rescue
    #  self._value % other
    #end
  end
&(other)

[Source]

# File tk/lib/tk/variable.rb, line 1141
  def &(other)
    if other.kind_of?(Array)
      self.to_a & other.to_a
    else
      self.to_i & other.to_i
    end
  end
*(other)

[Source]

# File tk/lib/tk/variable.rb, line 1176
  def *(other)
    num_or_str(self._value) * other.to_i
    #begin
    #  number(self._value) * other
    #rescue
    #  self._value * other
    #end
  end
**(other)

[Source]

# File tk/lib/tk/variable.rb, line 1195
  def **(other)
    number(self._value) ** other
  end
+(other)

[Source]

# File tk/lib/tk/variable.rb, line 1155
  def +(other)
    case other
    when Array
      self.to_a + other
    when String
      self._value + other
    else
      begin
        number(self._value) + other
      rescue
        self._value + other.to_s
      end
    end
  end
-(other)

[Source]

# File tk/lib/tk/variable.rb, line 1169
  def -(other)
    if other.kind_of?(Array)
      self.to_a - other
    else
      number(self._value) - other
    end
  end
/(other)

[Source]

# File tk/lib/tk/variable.rb, line 1184
  def /(other)
    number(self._value) / other
  end
<=>(other)

[Source]

# File tk/lib/tk/variable.rb, line 1233
  def <=>(other)
    if other.kind_of?(TkVariable)
      begin
        val = other.numeric
        other = val
      rescue
        other = other._value
      end
    elsif other.kind_of?(Numeric)
      begin
        return self.numeric <=> other
      rescue
        return self._value <=> other.to_s
      end
    elsif other.kind_of?(Array)
      return self.list <=> other
    else
      return self._value <=> other
    end
  end
==(other)

[Source]

# File tk/lib/tk/variable.rb, line 1202
  def ==(other)
    case other
    when TkVariable
      #self.equal?(other)
      self._value == other._value
    when String
      self.to_s == other
    when Symbol
      self.to_sym == other
    when Integer
      self.to_i == other
    when Float
      self.to_f == other
    when Array
      self.to_a == other
    when Hash
      # false if self is not an assoc array
      self._value == other
    else
      # false
      self._value == _get_eval_string(other)
    end
  end
=~(other)

[Source]

# File tk/lib/tk/variable.rb, line 1198
  def =~(other)
    self._value =~ other
  end
[](*idxs)

[Source]

# File tk/lib/tk/variable.rb, line 672
  def [](*idxs)
    _to_default_element_type(idxs, _element_value(*idxs))
  end
[]=(*args)

[Source]

# File tk/lib/tk/variable.rb, line 516
  def []=(*args)
    val = args.pop
    type = default_element_value_type(args)
    val = val._value if !type && type != :variable && val.kind_of?(TkVariable)
    index = args.collect{|idx| _get_eval_string(idx, true)}.join(',')
    _fromUTF8(INTERP._set_global_var2(@id, index, _get_eval_string(val, true)))
    #_fromUTF8(INTERP._set_global_var2(@id, _toUTF8(_get_eval_string(index)),
    #                                 _toUTF8(_get_eval_string(val))))
    #_fromUTF8(INTERP._set_global_var2(@id, _get_eval_string(index, true),
    #                                 _get_eval_string(val, true)))
  end
[]=(*args)

[Source]

# File tk/lib/tk/variable.rb, line 633
  def []=(*args)
    val = args.pop
    type = default_element_value_type(args)
    val = val._value if !type && type != :variable && val.kind_of?(TkVariable)
    index = args.collect{|idx| _get_eval_string(idx)}.join(',')
    INTERP._eval(Kernel.format('global %s; set %s(%s) %s', @id, @id,
                              index, _get_eval_string(val)))
    #INTERP._eval(Kernel.format('global %s; set %s(%s) %s', @id, @id,
    #                          _get_eval_string(index), _get_eval_string(val)))
    #INTERP._eval(Kernel.format('set %s(%s) %s', @id,
    #                          _get_eval_string(index), _get_eval_string(val)))
    #INTERP._eval('set ' + @id + '(' + _get_eval_string(index) + ') ' +
    #            _get_eval_string(val))
  end
_trace_vinfo_for_element(elem)

[Source]

# File tk/lib/tk/variable.rb, line 1385
  def _trace_vinfo_for_element(elem)
    if @elem
      fail(RuntimeError,
           "invalid for a TkVariable which denotes an element of Tcl's array")
    end
    return [] unless @trace_elem
    return [] unless @trace_elem[elem]
    @trace_elem[elem].dup
  end
bool()

[Source]

# File tk/lib/tk/variable.rb, line 753
  def bool
    TkComm.bool(_value)
??
  end
bool=(val)

Alias for set_bool

bool_element(*idxs)

[Source]

# File tk/lib/tk/variable.rb, line 765
  def bool_element(*idxs)
    TkComm.bool(_element_value(*idxs))
  end
bool_type=(val)

Alias for set_bool_type

clear()

[Source]

# File tk/lib/tk/variable.rb, line 429
  def clear
    if (is_scalar?)
      fail RuntimeError, 'cannot clear a scalar variable'
    end
    keys.each{|k| unset(k)}
    self
  end
coerce(other)

[Source]

# File tk/lib/tk/variable.rb, line 1122
  def coerce(other)
    case other
    when TkVariable
      [other._value, self._value]
    when String
      [other, self.to_s]
    when Symbol
      [other, self.to_sym]
    when Integer
      [other, self.to_i]
    when Float
      [other, self.to_f]
    when Array
      [other, self.to_a]
    else
      [other, self._value]
    end
  end
default_element_value_type(idxs)

[Source]

# File tk/lib/tk/variable.rb, line 134
  def default_element_value_type(idxs)
    if idxs.kind_of?(Array)
      index = idxs.collect{|idx| _get_eval_string(idx, true)}.join(',')
    else
      index = _get_eval_string(idxs, true)
    end
    @element_type[index]
  end
default_proc(cmd = Proc.new)

[Source]

# File tk/lib/tk/variable.rb, line 119
  def default_proc(cmd = Proc.new)
    @def_default = :proc
    @default_val = cmd
    self
  end
default_value(val=nil, &b)

default_value is available only when the variable is an assoc array.

[Source]

# File tk/lib/tk/variable.rb, line 103
  def default_value(val=nil, &b)
    if b
      @def_default = :proc
      @default_val = proc(&b)
    else
      @def_default = :val
      @default_val = val
    end
    self
  end
default_value=(val)

Alias for set_default_value

default_value_type()

[Source]

# File tk/lib/tk/variable.rb, line 131
  def default_value_type
    @type
  end
default_value_type=(type)

Alias for set_default_value_type

element_lappend(idxs, *elems)

[Source]

# File tk/lib/tk/variable.rb, line 1069
  def element_lappend(idxs, *elems)
    if idxs.kind_of?(Array)
      idxs = idxs.collect{|idx| _get_eval_string(idx, true)}.join(',')
    end
    tk_call('lappend', "#{@id}(#{idxs})", *elems)
    self
  end
element_lget(elem_idxs, idx)

Alias for element_lindex

element_lget_f(elem_idxs, idx)

[Source]

# File tk/lib/tk/variable.rb, line 1101
  def element_lget_f(elem_idxs, idx)
    number(element_lget(elem_idxs, idx)).to_f
  end
element_lget_i(elem_idxs, idx)

[Source]

# File tk/lib/tk/variable.rb, line 1094
  def element_lget_i(elem_idxs, idx)
    number(element_lget(elem_idxs, idx)).to_i
  end
element_lindex(elem_idxs, idx)

[Source]

# File tk/lib/tk/variable.rb, line 1081
  def element_lindex(elem_idxs, idx)
    if elem_idxs.kind_of?(Array)
      val = _element_value(*elem_idxs)
    else
      val = _element_value(elem_idxs)
    end
    tk_call('lindex', val, idx)
  end
element_lset(elem_idxs, idx, val)

[Source]

# File tk/lib/tk/variable.rb, line 1109
  def element_lset(elem_idxs, idx, val)
    if elem_idxs.kind_of?(Array)
      idxs = elem_idxs.collect{|i| _get_eval_string(i, true)}.join(',')
    end
    tk_call('lset', "#{@id}(#{idxs})", idx, val)
    self
  end
element_to_a(*idxs)

Alias for list_element

element_to_f(*idxs)

[Source]

# File tk/lib/tk/variable.rb, line 918
  def element_to_f(*idxs)
    number(_element_value(*idxs)).to_f
  end
element_to_i(*idxs)

[Source]

# File tk/lib/tk/variable.rb, line 911
  def element_to_i(*idxs)
    number(_element_value(*idxs)).to_i
  end
element_to_s(*idxs)

[Source]

# File tk/lib/tk/variable.rb, line 927
  def element_to_s(*idxs)
    _element_value(*idxs)
  end
element_to_sym(*idxs)

[Source]

# File tk/lib/tk/variable.rb, line 963
  def element_to_sym(*idxs)
    _element_value(*idxs).intern
  end
eventloop_tkwait()

[Source]

# File tk/lib/tk/variable.rb, line 374
  def eventloop_tkwait
    wait(false, true)
  end
eventloop_wait(check_root = false)

[Source]

# File tk/lib/tk/variable.rb, line 365
  def eventloop_wait(check_root = false)
    wait(false, check_root)
  end
exist?(*elems)

[Source]

# File tk/lib/tk/variable.rb, line 401
  def exist?(*elems)
    INTERP._invoke_without_enc('global', @id)
    if elems.empty?
      TkComm.bool(tk_call('info', 'exist', @id))
    else
      # array
      index = elems.collect{|idx| _get_eval_string(idx, true)}.join(',')
      TkComm.bool(tk_call('info', 'exist', "#{@id}")) &&
        TkComm.bool(tk_call('info', 'exist', "#{@id}(#{index})"))
    end
  end
id()

[Source]

# File tk/lib/tk/variable.rb, line 381
  def id
    @id
  end
inspect()

[Source]

# File tk/lib/tk/variable.rb, line 1117
  def inspect
    #Kernel.format "#<TkVariable: %s>", @id
    '#<TkVariable: ' + @id + '>'
  end
is_hash?()

[Source]

# File tk/lib/tk/variable.rb, line 390
  def is_hash?
    #ITNERP._eval("global #{@id}; array exist #{@id}") == '1'
    INTERP._invoke_without_enc('global', @id)
    # INTERP._invoke_without_enc('array', 'exist', @id) == '1'
    TkComm.bool(INTERP._invoke_without_enc('array', 'exist', @id))
  end
is_scalar?()

[Source]

# File tk/lib/tk/variable.rb, line 397
  def is_scalar?
    ! is_hash?
  end
keys()

[Source]

# File tk/lib/tk/variable.rb, line 413
  def keys
    if (is_scalar?)
      fail RuntimeError, 'cannot get keys from a scalar variable'
    end
    #tk_split_simplelist(INTERP._eval("global #{@id}; array get #{@id}"))
    INTERP._invoke_without_enc('global', @id)
    #tk_split_simplelist(INTERP._fromUTF8(INTERP._invoke_without_enc('array', 'names', @id)))
    tk_split_simplelist(INTERP._invoke_without_enc('array', 'names', @id),
                        false, true)
  end
lappend(*elems)

[Source]

# File tk/lib/tk/variable.rb, line 1065
  def lappend(*elems)
    tk_call('lappend', @id, *elems)
    self
  end
lget(idx)

Alias for lindex

lget_f(idx)

[Source]

# File tk/lib/tk/variable.rb, line 1098
  def lget_f(idx)
    number(lget(idx)).to_f
  end
lget_i(idx)

[Source]

# File tk/lib/tk/variable.rb, line 1091
  def lget_i(idx)
    number(lget(idx)).to_i
  end
lindex(idx)

[Source]

# File tk/lib/tk/variable.rb, line 1077
  def lindex(idx)
    tk_call('lindex', self._value, idx)
  end
list()

[Source]

# File tk/lib/tk/variable.rb, line 993
  def list
    #tk_split_list(value)
    tk_split_simplelist(_value)
  end
list=(val)

Alias for set_list

list_element(*idxs)

[Source]

# File tk/lib/tk/variable.rb, line 998
  def list_element(*idxs)
    tk_split_simplelist(_element_value(*idxs))
  end
list_type=(val)

Alias for set_list_type

lset(idx, val)

[Source]

# File tk/lib/tk/variable.rb, line 1105
  def lset(idx, val)
    tk_call('lset', @id, idx, val)
    self
  end
nonzero?()

[Source]

# File tk/lib/tk/variable.rb, line 1229
  def nonzero?
    !(numeric.zero?)
  end
numeric()

[Source]

# File tk/lib/tk/variable.rb, line 708
  def numeric
    number(_value)
  end
numeric=(val)

Alias for set_numeric

numeric_element(*idxs)

[Source]

# File tk/lib/tk/variable.rb, line 711
  def numeric_element(*idxs)
    number(_element_value(*idxs))
  end
numeric_type=(val)

Alias for set_numeric_type

numlist()

[Source]

# File tk/lib/tk/variable.rb, line 1003
  def numlist
    list.collect!{|val| number(val)}
  end
numlist=(val)

Alias for set_numlist

numlist_element(*idxs)

[Source]

# File tk/lib/tk/variable.rb, line 1006
  def numlist_element(*idxs)
    list_element(*idxs).collect!{|val| number(val)}
  end
numlist_type=(val)

Alias for set_numlist_type

procedure()

[Source]

# File tk/lib/tk/variable.rb, line 877
  def procedure
    TkComm.procedure(self._value)
  end
procedure=(cmd)

Alias for set_procedure

procedure_element(*idxs)

[Source]

# File tk/lib/tk/variable.rb, line 880
  def procedure_element(*idxs)
    TkComm.procedure(_element_value(*idxs))
  end
procedure_type=(cmd)

Alias for set_procedure_type

ref(*idxs)

[Source]

# File tk/lib/tk/variable.rb, line 385
  def ref(*idxs)
    # "#{@id}(#{idxs.collect{|idx| _get_eval_string(idx)}.join(',')})"
    TkVarAccess.new("#{@id}(#{idxs.collect{|idx| _get_eval_string(idx)}.join(',')})")
  end
remove(*elems)

Alias for unset

remove(*elems)

Alias for unset

set_bool(val)

[Source]

# File tk/lib/tk/variable.rb, line 768
  def set_bool(val)
    if ! val
      self.value = '0'
    else
      case val.to_s.downcase
      when 'false', '0', 'no', 'off'
        self.value = '0'
      else
        self.value = '1'
      end
    end
    self
  end
set_bool_element(idxs, val)

[Source]

# File tk/lib/tk/variable.rb, line 782
  def set_bool_element(idxs, val)
    if ! val
      val = '0'
    else
      case val.to_s.downcase
      when 'false', '0', 'no', 'off'
        val = '0'
      else
        val = '1'
      end
    end
    if idxs.kind_of?(Array)
      self[*idxs]=val
    else
      self[idxs]=val
    end
    self
  end
set_bool_element_type(idxs, val)

[Source]

# File tk/lib/tk/variable.rb, line 806
  def set_bool_element_type(idxs, val)
    self.set_default_element_value_type(idxs, :bool)
    self.set_bool_element(idxs, val)
  end
set_bool_type(val)

[Source]

# File tk/lib/tk/variable.rb, line 800
  def set_bool_type(val)
    @type = :bool
    self.bool=(val)
    self
  end
set_default_element_value_type(idxs, type)

[Source]

# File tk/lib/tk/variable.rb, line 212
  def set_default_element_value_type(idxs, type)
    _set_default_value_type_core(type, idxs)
    self
  end
set_default_value(val)

[Source]

# File tk/lib/tk/variable.rb, line 113
  def set_default_value(val)
    @def_default = :val
    @default_val = val
    self
  end
set_default_value_type(type)

[Source]

# File tk/lib/tk/variable.rb, line 206
  def set_default_value_type(type)
    _set_default_value_type_core(type, nil)
    self
  end
set_element_value(idxs, val)

[Source]

# File tk/lib/tk/variable.rb, line 681
  def set_element_value(idxs, val)
    if idxs.kind_of?(Array)
      self[*idxs]=val
    else
      self[idxs]=val
    end
    self
  end
set_element_value_type(idxs, val)

[Source]

# File tk/lib/tk/variable.rb, line 698
  def set_element_value_type(idxs, val)
    self.set_default_element_value_type(idxs, val.class)
    if idxs.kind_of?(Array)
      self[*idxs]=val
    else
      self[idxs]=val
    end
    self
  end
set_list(val)

[Source]

# File tk/lib/tk/variable.rb, line 1010
  def set_list(val)
    case val
    when Array
      self.value=(val)
    when TkVariable
      self.value=(val.list)
    else
      raise ArgumentError, "Array is expected"
    end
    self
  end
set_list_element(idxs, val)

[Source]

# File tk/lib/tk/variable.rb, line 1026
  def set_list_element(idxs, val)
    case val
    when Array
      val
    when TkVariable
      val = val.list
    else
      raise ArgumentError, "Array is expected"
    end
    if idxs.kind_of?(Array)
      self[*idxs]=val
    else
      self[idxs]=val
    end
    self
  end
set_list_element_type(idxs, val)

[Source]

# File tk/lib/tk/variable.rb, line 1050
  def set_list_element_type(idxs, val)
    self.set_default_element_value_type(idxs, :list)
    self.set_list_element(idxs, val)
  end
set_list_type(val)

[Source]

# File tk/lib/tk/variable.rb, line 1044
  def set_list_type(val)
    @type = :list
    self.list=(val)
    self
  end
set_numeric(val)

[Source]

# File tk/lib/tk/variable.rb, line 714
  def set_numeric(val)
    case val
    when Numeric
      self.value=(val)
    when TkVariable
      self.value=(val.numeric)
    else
      raise ArgumentError, "Numeric is expected"
    end
    self
  end
set_numeric_element(idxs, val)

[Source]

# File tk/lib/tk/variable.rb, line 726
  def set_numeric_element(idxs, val)
    case val
    when Numeric
      val
    when TkVariable
      val = val.numeric
    else
      raise ArgumentError, "Numeric is expected"
    end
    if idxs.kind_of?(Array)
      self[*idxs]=val
    else
      self[idxs]=val
    end
    self
  end
set_numeric_element_type(idxs, val)

[Source]

# File tk/lib/tk/variable.rb, line 748
  def set_numeric_element_type(idxs, val)
    self.set_default_element_value_type(idxs, :numeric)
    self.set_numeric_element(idxs, val)
  end
set_numeric_type(val)

[Source]

# File tk/lib/tk/variable.rb, line 742
  def set_numeric_type(val)
    @type = :numeric
    self.numeric=(val)
    self
  end
set_numlist(val)

Alias for set_list

set_numlist_element(idxs, val)

Alias for set_list_element

set_numlist_element_type(idxs, val)

[Source]

# File tk/lib/tk/variable.rb, line 1060
  def set_numlist_element_type(idxs, val)
    self.set_default_element_value_type(idxs, :numlist)
    self.set_numlist_element(idxs, val)
  end
set_numlist_type(val)

[Source]

# File tk/lib/tk/variable.rb, line 1054
  def set_numlist_type(val)
    @type = :numlist
    self.numlist=(val)
    self
  end
set_procedure(cmd)

[Source]

# File tk/lib/tk/variable.rb, line 883
  def set_procedure(cmd)
    self.value = cmd
    self
  end
set_procedure_element(idxs, cmd)

[Source]

# File tk/lib/tk/variable.rb, line 888
  def set_procedure_element(idxs, cmd)
    cmd = cmd._value if cmd.kind_of?(TkVariable)
    if idxs.kind_of?(Array)
      self[*idxs]=cmd
    else
      self[idxs]=cmd
    end
    self
  end
set_procedure_element_type(idxs, cmd)

[Source]

# File tk/lib/tk/variable.rb, line 903
  def set_procedure_element_type(idxs, cmd)
    self.set_default_element_value_type(idxs, :procedure)
    self.set_proceure_element(idxs, cmd)
  end
set_procedure_type(cmd)

[Source]

# File tk/lib/tk/variable.rb, line 897
  def set_procedure_type(cmd)
    @type = :procedure
    self.procedure=(cmd)
    self
  end
set_string(val)

[Source]

# File tk/lib/tk/variable.rb, line 933
  def set_string(val)
    val = val._value if val.kind_of?(TkVariable)
    self.value=val
    self
  end
set_string_element(idxs, val)

[Source]

# File tk/lib/tk/variable.rb, line 939
  def set_string_element(idxs, val)
    val = val._value if val.kind_of?(TkVariable)
    if idxs.kind_of?(Array)
      self[*idxs]=val
    else
      self[idxs]=val
    end
    self
  end
set_string_element_type(idxs, val)

[Source]

# File tk/lib/tk/variable.rb, line 954
  def set_string_element_type(idxs, val)
    self.set_default_element_value_type(idxs, :string)
    self.set_string_element(idxs, val)
  end
set_string_type(val)

[Source]

# File tk/lib/tk/variable.rb, line 948
  def set_string_type(val)
    @type = :string
    self.string=(val)
    self
  end
set_symbol(val)

[Source]

# File tk/lib/tk/variable.rb, line 967
  def set_symbol(val)
    val = val._value if val.kind_of?(TkVariable)
    self.value=val
    self
  end
set_symbol_element(idxs, val)

[Source]

# File tk/lib/tk/variable.rb, line 973
  def set_symbol_element(idxs, val)
    val = val._value if val.kind_of?(TkVariable)
    if idxs.kind_of?(Array)
      self[*idxs]=val
    else
      self[idxs]=val
    end
    self
  end
set_symbol_element_type(idxs, val)

[Source]

# File tk/lib/tk/variable.rb, line 988
  def set_symbol_element_type(idxs, val)
    self.set_default_element_value_type(idxs, :symbol)
    self.set_symbol_element(idxs, val)
  end
set_symbol_type(val)

[Source]

# File tk/lib/tk/variable.rb, line 982
  def set_symbol_type(val)
    @type = :symbol
    self.value=(val)
    self
  end
set_value(val)

[Source]

# File tk/lib/tk/variable.rb, line 676
  def set_value(val)
    self.value = val
    self
  end
set_value_type(val)

[Source]

# File tk/lib/tk/variable.rb, line 690
  def set_value_type(val)
    self.default_value_type = val.class
    self.value = val
    self
  end
set_variable(var)

[Source]

# File tk/lib/tk/variable.rb, line 818
  def set_variable(var)
    var = var.id if var.kind_of?(TkVariable)
    self.value = var
    self
  end
set_variable_element(idxs, var)

[Source]

# File tk/lib/tk/variable.rb, line 824
  def set_variable_element(idxs, var)
    var = var.id if var.kind_of?(TkVariable)
    if idxs.kind_of?(Array)
      self[*idxs]=var
    else
      self[idxs]=var
    end
    self
  end
set_variable_element_type(idxs, var)

[Source]

# File tk/lib/tk/variable.rb, line 840
  def set_variable_element_type(idxs, var)
    self.set_default_element_value_type(idxs, :variable)
    self.set_variable_element(idxs, var)
  end
set_variable_type(var)

[Source]

# File tk/lib/tk/variable.rb, line 833
  def set_variable_type(var)
    @type = :variable
    var = var.id if var.kind_of?(TkVariable)
    self.value = var
    self
  end
set_window(win)

[Source]

# File tk/lib/tk/variable.rb, line 851
  def set_window(win)
    win = win._value if win.kind_of?(TkVariable)
    self.value = win
    self
  end
set_window_element(idxs, win)

[Source]

# File tk/lib/tk/variable.rb, line 857
  def set_window_element(idxs, win)
    win = win._value if win.kind_of?(TkVariable)
    if idxs.kind_of?(Array)
      self[*idxs]=win
    else
      self[idxs]=win
    end
    self
  end
set_window_element_type(idxs, win)

[Source]

# File tk/lib/tk/variable.rb, line 872
  def set_window_element_type(idxs, win)
    self.set_default_element_value_type(idxs, :window)
    self.set_window_element(idxs, win)
  end
set_window_type(win)

[Source]

# File tk/lib/tk/variable.rb, line 866
  def set_window_type(win)
    @type = :window
    self.window=(win)
    self
  end
size()

[Source]

# File tk/lib/tk/variable.rb, line 424
  def size
    INTERP._invoke_without_enc('global', @id)
    TkComm.number(INTERP._invoke_without_enc('array', 'size', @id))
  end
string()

Alias for to_s

string=(val)

Alias for set_string

string_element(*idxs)

[Source]

# File tk/lib/tk/variable.rb, line 930
  def string_element(*idxs)
    _element_value(*idxs)
  end
string_type=(val)

Alias for set_string_type

symbol()

Alias for to_sym

symbol=(val)

Alias for set_symbol

symbol_element(*idxs)

Alias for element_to_sym

symbol_type=(val)

Alias for set_symbol_type

thread_tkwait()

[Source]

# File tk/lib/tk/variable.rb, line 377
  def thread_tkwait
    wait(true, true)
  end
thread_wait(check_root = false)

[Source]

# File tk/lib/tk/variable.rb, line 368
  def thread_wait(check_root = false)
    wait(true, check_root)
  end
tkwait(on_thread = true)

[Source]

# File tk/lib/tk/variable.rb, line 371
  def tkwait(on_thread = true)
    wait(on_thread, true)
  end
to_a()

Alias for list

to_eval()

[Source]

# File tk/lib/tk/variable.rb, line 1254
  def to_eval
    @id
  end
to_f()

[Source]

# File tk/lib/tk/variable.rb, line 915
  def to_f
    number(_value).to_f
  end
to_i()

[Source]

# File tk/lib/tk/variable.rb, line 908
  def to_i
    number(_value).to_i
  end
to_s()

[Source]

# File tk/lib/tk/variable.rb, line 922
  def to_s
    #string(value).to_s
    _value
  end
to_sym()

[Source]

# File tk/lib/tk/variable.rb, line 959
  def to_sym
    _value.intern
  end
trace(opts, cmd = Proc.new)

[Source]

# File tk/lib/tk/variable.rb, line 1269
  def trace(opts, cmd = Proc.new)
    @trace_var = [] if @trace_var == nil
    #opts = ['r','w','u'].find_all{|c| opts.index(c)}.join('')
    opts = opts.to_s
    opts = ['r','w','u'].find_all{|c| opts.index(c)}.join('')
    @trace_var.unshift([opts,cmd])
    if @trace_opts == nil
      TkVar_CB_TBL[@id] = self
      @trace_opts = opts.dup
      Tk.tk_call_without_enc('trace', 'variable', @id, @trace_opts,
                             'rb_var ' << @id)
??
    else
      newopts = @trace_opts.dup
      #opts.each_byte{|c| newopts += c.chr unless newopts.index(c)}
      opts.each_byte{|c| newopts.concat(c.chr) unless newopts.index(c)}
      if newopts != @trace_opts
        Tk.tk_call_without_enc('trace', 'vdelete', @id, @trace_opts,
                               'rb_var ' << @id)
        @trace_opts.replace(newopts)
        Tk.tk_call_without_enc('trace', 'variable', @id, @trace_opts,
                               'rb_var ' << @id)
??
      end
    end
    self
  end
trace_callback(elem, op)

[Source]

# File tk/lib/tk/variable.rb, line 1258
  def trace_callback(elem, op)
    if @trace_var.kind_of? Array
      @trace_var.each{|m,e| e.call(self,elem,op) if m.index(op)}
    end
    if elem.kind_of?(String) && elem != ''
      if @trace_elem.kind_of?(Hash) && @trace_elem[elem].kind_of?(Array)
        @trace_elem[elem].each{|m,e| e.call(self,elem,op) if m.index(op)}
      end
    end
  end
trace_element(elem, opts, cmd = Proc.new)

[Source]

# File tk/lib/tk/variable.rb, line 1322
  def trace_element(elem, opts, cmd = Proc.new)
    if @elem
      fail(RuntimeError,
           "invalid for a TkVariable which denotes an element of Tcl's array")
    end
    @trace_elem = {} if @trace_elem == nil
    @trace_elem[elem] = [] if @trace_elem[elem] == nil
    opts = opts.to_s
    opts = ['r','w','u'].find_all{|c| opts.index(c)}.join('')
    @trace_elem[elem].unshift([opts,cmd])
    if @trace_opts == nil
      TkVar_CB_TBL[@id] = self
      @trace_opts = opts.dup
      Tk.tk_call_without_enc('trace', 'variable', @id, @trace_opts,
                             'rb_var ' << @id)
??
    else
      newopts = @trace_opts.dup
      # opts.each_byte{|c| newopts += c.chr unless newopts.index(c)}
      opts.each_byte{|c| newopts.concat(c.chr) unless newopts.index(c)}
      if newopts != @trace_opts
        Tk.tk_call_without_enc('trace', 'vdelete', @id, @trace_opts,
                               'rb_var ' << @id)
        @trace_opts.replace(newopts)
        Tk.tk_call_without_enc('trace', 'variable', @id, @trace_opts,
                               'rb_var ' << @id)
??
      end
    end
    self
  end
trace_vdelete(opts,cmd)

[Source]

# File tk/lib/tk/variable.rb, line 1395
  def trace_vdelete(opts,cmd)
    return self unless @trace_var.kind_of? Array
    opts = opts.to_s
    opts = ['r','w','u'].find_all{|c| opts.index(c)}.join('')
    idx = -1
    newopts = ''
    @trace_var.each_with_index{|e,i|
      if idx < 0 && e[0] == opts && e[1] == cmd
        idx = i
        next
      end
      # e[0].each_byte{|c| newopts += c.chr unless newopts.index(c)}
      e[0].each_byte{|c| newopts.concat(c.chr) unless newopts.index(c)}
    }
    if idx >= 0
      @trace_var.delete_at(idx)
    else
      return self
    end

    @trace_elem.each{|elem|
      @trace_elem[elem].each{|e|
        # e[0].each_byte{|c| newopts += c.chr unless newopts.index(c)}
        e[0].each_byte{|c| newopts.concat(c.chr) unless newopts.index(c)}
      }
    }

    newopts = newopts.to_s
    newopts = ['r','w','u'].find_all{|c| newopts.index(c)}.join('')
    if newopts != @trace_opts
      Tk.tk_call_without_enc('trace', 'vdelete', @id, @trace_opts,
                             'rb_var ' << @id)
??
      @trace_opts.replace(newopts)
      if @trace_opts != ''
        Tk.tk_call_without_enc('trace', 'variable', @id, @trace_opts,
                               'rb_var ' << @id)
??
      end
    end

    self
  end
trace_vdelete_for_element(elem,opts,cmd)

[Source]

# File tk/lib/tk/variable.rb, line 1459
  def trace_vdelete_for_element(elem,opts,cmd)
    if @elem
      fail(RuntimeError,
           "invalid for a TkVariable which denotes an element of Tcl's array")
    end
    return self unless @trace_elem.kind_of? Hash
    return self unless @trace_elem[elem].kind_of? Array
    opts = opts.to_s
    opts = ['r','w','u'].find_all{|c| opts.index(c)}.join('')
    idx = -1
    @trace_elem[elem].each_with_index{|e,i|
      if idx < 0 && e[0] == opts && e[1] == cmd
        idx = i
        next
      end
    }
    if idx >= 0
      @trace_elem[elem].delete_at(idx)
    else
      return self
    end

    newopts = ''
    @trace_var.each{|e|
      # e[0].each_byte{|c| newopts += c.chr unless newopts.index(c)}
      e[0].each_byte{|c| newopts.concat(c.chr) unless newopts.index(c)}
    }
    @trace_elem.each{|elem|
      @trace_elem[elem].each{|e|
        # e[0].each_byte{|c| newopts += c.chr unless newopts.index(c)}
        e[0].each_byte{|c| newopts.concat(c.chr) unless newopts.index(c)}
      }
    }

    newopts = newopts.to_s
    newopts = ['r','w','u'].find_all{|c| newopts.index(c)}.join('')
    if newopts != @trace_opts
      Tk.tk_call_without_enc('trace', 'vdelete', @id, @trace_opts,
                             'rb_var ' << @id)
??
      @trace_opts.replace(newopts)
      if @trace_opts != ''
        Tk.tk_call_without_enc('trace', 'variable', @id, @trace_opts,
                               'rb_var ' << @id)
??
      end
    end

    self
  end
trace_vinfo()

[Source]

# File tk/lib/tk/variable.rb, line 1380
  def trace_vinfo
    return [] unless @trace_var
    @trace_var.dup
  end
undef_default()

[Source]

# File tk/lib/tk/variable.rb, line 125
  def undef_default
    @default_val = nil
    @def_default = false
    self
  end
unset(*elems)

[Source]

# File tk/lib/tk/variable.rb, line 648
  def unset(*elems)
    if elems.empty?
      INTERP._eval(Kernel.format('global %s; unset %s', @id, @id))
      #INTERP._eval(Kernel.format('unset %s', @id))
      #INTERP._eval('unset ' + @id)
    else
      index = elems.collect{|idx| _get_eval_string(idx, true)}.join(',')
      INTERP._eval(Kernel.format('global %s; unset %s(%s)', @id, @id, index))
      #INTERP._eval(Kernel.format('global %s; unset %s(%s)',
      #                           @id, @id, _get_eval_string(elem)))
      #INTERP._eval(Kernel.format('unset %s(%s)', @id, tk_tcl2ruby(elem)))
      #INTERP._eval('unset ' + @id + '(' + _get_eval_string(elem) + ')')
    end
  end
unset(*elems)

[Source]

# File tk/lib/tk/variable.rb, line 528
  def unset(*elems)
    if elems.empty?
      INTERP._unset_global_var(@id)
    else
      index = elems.collect{|idx| _get_eval_string(idx, true)}.join(',')
      INTERP._unset_global_var2(@id, index)
    end
  end
update(hash)

[Source]

# File tk/lib/tk/variable.rb, line 437
  def update(hash)
    if (is_scalar?)
      fail RuntimeError, 'cannot update a scalar variable'
    end
    hash.each{|k,v| self[k] = v}
    self
  end
value()

[Source]

# File tk/lib/tk/variable.rb, line 668
  def value
    _to_default_type(_value)
  end
value=(val)

[Source]

# File tk/lib/tk/variable.rb, line 561
  def value=(val)
    val = val._value if !@type && @type != :variable && val.kind_of?(TkVariable)
    begin
      #s = '"' + _get_eval_string(val).gsub(/[\[\]$"]/, '\\\\\&') + '"'
      s = '"' + _get_eval_string(val).gsub(/[\[\]$"\\]/, '\\\\\&') + '"'
      INTERP._eval(Kernel.format('global %s; set %s %s', @id, @id, s))
      #INTERP._eval(Kernel.format('set %s %s', @id, s))
      #_fromUTF8(INTERP._invoke_without_enc('set', @id, _toUTF8(s)))
    rescue
      if INTERP._eval(Kernel.format('global %s; array exists %s',
                            @id, @id)) != "1"
      #if INTERP._eval(Kernel.format('array exists %s', @id)) != "1"
      #if INTERP._invoke_without_enc('array', 'exists', @id) != "1"
        fail
      else
        if val == []
          INTERP._eval(Kernel.format('global %s; unset %s; set %s(0) 0; unset %s(0)', @id, @id, @id, @id))
          #INTERP._eval(Kernel.format('unset %s; set %s(0) 0; unset %s(0)',
          #                          @id, @id, @id))
          #INTERP._invoke_without_enc('unset', @id)
          #INTERP._invoke_without_enc('set', @id+'(0)', 0)
          #INTERP._invoke_without_enc('unset', @id+'(0)')
        elsif val.kind_of?(Array)
          a = []
          val.each_with_index{|e,i| a.push(i); a.push(array2tk_list(e, true))}
          #s = '"' + a.join(" ").gsub(/[\[\]$"]/, '\\\\\&') + '"'
          s = '"' + a.join(" ").gsub(/[\[\]$"\\]/, '\\\\\&') + '"'
          INTERP._eval(Kernel.format('global %s; unset %s; array set %s %s',
                                     @id, @id, @id, s))
          #INTERP._eval(Kernel.format('unset %s; array set %s %s',
          #                          @id, @id, s))
          #INTERP._invoke_without_enc('unset', @id)
          #_fromUTF8(INTERP._invoke_without_enc('array','set', @id, _toUTF8(s)))
        elsif  val.kind_of?(Hash)
          #s = '"' + val.to_a.collect{|e| array2tk_list(e)}.join(" ")           #                      .gsub(/[\[\]$"]/, '\\\\\&') + '"'
          s = '"' + val.to_a.collect{|e| array2tk_list(e, true)}.join(" ")\
                                .gsub(/[\[\]$\\"]/, '\\\\\&') + '"'
          INTERP._eval(Kernel.format('global %s; unset %s; array set %s %s',
                                     @id, @id, @id, s))
          #INTERP._eval(Kernel.format('unset %s; array set %s %s',
          #                          @id, @id, s))
          #INTERP._invoke_without_enc('unset', @id)
          #_fromUTF8(INTERP._invoke_without_enc('array','set', @id, _toUTF8(s)))
        else
          fail
        end
      end
    end
  end
value=(val)

[Source]

# File tk/lib/tk/variable.rb, line 466
  def value=(val)
    val = val._value if !@type && @type != :variable && val.kind_of?(TkVariable)
    if val.kind_of?(Hash)
      self.clear
      val.each{|k, v|
        #INTERP._set_global_var2(@id, _toUTF8(_get_eval_string(k)),
        #                       _toUTF8(_get_eval_string(v)))
        INTERP._set_global_var2(@id, _get_eval_string(k, true),
                                _get_eval_string(v, true))
      }
      self.value
#    elsif val.kind_of?(Array)
??
#      _fromUTF8(INTERP._set_global_var(@id, array2tk_list(val, true)))
    else
      #_fromUTF8(INTERP._set_global_var(@id, _toUTF8(_get_eval_string(val))))
      _fromUTF8(INTERP._set_global_var(@id, _get_eval_string(val, true)))
    end
  end
value_type=(val)

Alias for set_value_type

variable()

[Source]

# File tk/lib/tk/variable.rb, line 811
  def variable
    # keeps a Tcl's variable name
    TkVarAccess.new(self._value)
  end
variable=(var)

Alias for set_variable

variable_element(*idxs)

[Source]

# File tk/lib/tk/variable.rb, line 815
  def variable_element(*idxs)
    TkVarAccess.new(_element_value(*idxs))
  end
variable_type=(var)

Alias for set_variable_type

wait(on_thread = false, check_root = false)

[Source]

# File tk/lib/tk/variable.rb, line 346
  def wait(on_thread = false, check_root = false)
    if $SAFE >= 4
      fail SecurityError, "can't wait variable at $SAFE >= 4"
    end
    on_thread &= (Thread.list.size != 1)
    if on_thread
      if check_root
        INTERP._thread_tkwait('variable', @id)
      else
        INTERP._thread_vwait(@id)
      end
    else
      if check_root
        INTERP._invoke_without_enc('tkwait', 'variable', @id)
      else
        INTERP._invoke_without_enc('vwait', @id)
      end
    end
  end
window()

[Source]

# File tk/lib/tk/variable.rb, line 845
  def window
    TkComm.window(self._value)
  end
window=(win)

Alias for set_window

window_element(*idxs)

[Source]

# File tk/lib/tk/variable.rb, line 848
  def window_element(*idxs)
    TkComm.window(_element_value(*idxs))
  end
window_type=(win)

Alias for set_window_type

zero?()

[Source]

# File tk/lib/tk/variable.rb, line 1226
  def zero?
    numeric.zero?
  end
|(other)

[Source]

# File tk/lib/tk/variable.rb, line 1148
  def |(other)
    if other.kind_of?(Array)
      self.to_a | other.to_a
    else
      self.to_i | other.to_i
    end
  end


Class: TkVirtualEvent

Class | TkVirtualEvent
In: | tk/lib/tk/virtevent.rb
Parent: | TkObject

Methods

add delete getobj info info new

Classes and Modules

Class TkVirtualEvent::PreDefVirtEvent

Constants

TkCommandNames | = | ['event'.freeze].freeze
TkVirtualEventID | = | ["VirtEvent".freeze, "00000".taint].freeze
TkVirtualEventTBL | = | TkCore::INTERP.create_table

Public Class methods

getobj(event)

[Source]

# File tk/lib/tk/virtevent.rb, line 25
  def TkVirtualEvent.getobj(event)
    obj = TkVirtualEventTBL[event]
    if obj
      obj
    else
      if tk_call_without_enc('event', 'info').index("<#{event}>")
        PreDefVirtEvent.new(event)
      else
        fail ArgumentError, "undefined virtual event '<#{event}>'"
      end
    end
  end
info()

[Source]

# File tk/lib/tk/virtevent.rb, line 38
  def TkVirtualEvent.info
    tk_call_without_enc('event', 'info').split(/\s+/).collect!{|seq|
      TkVirtualEvent.getobj(seq[1..-2])
    }
  end
new(*sequences)

[Source]

# File tk/lib/tk/virtevent.rb, line 44
  def initialize(*sequences)
    # @path = @id = '<' + TkVirtualEventID.join('') + '>'
    @path = @id = '<' + TkVirtualEventID.join(TkCore::INTERP._ip_id_) + '>'
    TkVirtualEventID[1].succ!
    add(*sequences)
  end

Public Instance methods

add(*sequences)

[Source]

# File tk/lib/tk/virtevent.rb, line 51
  def add(*sequences)
    if sequences != []
      tk_call_without_enc('event', 'add', "<#{@id}>",
                          *(sequences.collect{|seq|
                              "<#{tk_event_sequence(seq)}>"
                            }) )
      TkVirtualEventTBL[@id] = self
    end
    self
  end
delete(*sequences)

[Source]

# File tk/lib/tk/virtevent.rb, line 62
  def delete(*sequences)
    if sequences == []
      tk_call_without_enc('event', 'delete', "<#{@id}>")
      TkVirtualEventTBL.delete(@id)
    else
      tk_call_without_enc('event', 'delete', "<#{@id}>",
                          *(sequences.collect{|seq|
                              "<#{tk_event_sequence(seq)}>"
                            }) )
      TkVirtualEventTBL.delete(@id) if info == []
    end
    self
  end
info()

[Source]

# File tk/lib/tk/virtevent.rb, line 76
  def info
    tk_call_without_enc('event','info',"<#{@id}>").split(/\s+/).collect!{|seq|
      l = seq.scan(/<*[^<>]+>*/).collect!{|subseq|
        case (subseq)
        when /^<<[^<>]+>>$/
          TkVirtualEvent.getobj(subseq[1..-2])
        when /^<[^<>]+>$/
          subseq[1..-2]
        else
          subseq.split('')
        end
      }.flatten
      (l.size == 1) ? l[0] : l
    }
  end


Class: TkVirtualEvent::PreDefVirtEvent

Class | TkVirtualEvent::PreDefVirtEvent
In: | tk/lib/tk/virtevent.rb
Parent: | self

Methods

new

Public Class methods

new(event, *sequences)

[Source]

# File tk/lib/tk/virtevent.rb, line 18
    def initialize(event, *sequences)
      @path = @id = event
      TkVirtualEvent::TkVirtualEventTBL[@id] = self
      add(*sequences)
    end


Class: TkWarning

Class | TkWarning
In: | tk/lib/tk/dialog.rb
Parent: | TkWarningObj

Methods

new show

Public Class methods

new(*args)

[Source]

# File tk/lib/tk/dialog.rb, line 322
  def initialize(*args)
    super(*args)
    show
  end
show(*args)

[Source]

# File tk/lib/tk/dialog.rb, line 319
  def self.show(*args)
    self.new(*args)
  end


Class: TkWarningObj

Class | TkWarningObj
In: | tk/lib/tk/dialog.rb
Parent: | TkDialogObj

dialog for warning

Methods

new show

Public Class methods

new(parent = nil, mes = nil)

[Source]

# File tk/lib/tk/dialog.rb, line 280
  def initialize(parent = nil, mes = nil)
    if !mes
      if parent.kind_of?(TkWindow)
        mes = ""
      else
        mes = parent.to_s
        parent = nil
      end
    end
    super(parent, :message=>mes)
  end

Public Instance methods

show(mes = nil)

[Source]

# File tk/lib/tk/dialog.rb, line 292
  def show(mes = nil)
    mes_bup = @message
    @message = mes if mes
    ret = super()
    @message = mes_bup
    ret
  end


Module: TkWinDDE

Module | TkWinDDE
In: | tk/lib/tk/winpkg.rb

Methods

async_eval async_execute binary_request eval execute package_name poke request servername services

Constants

TkCommandNames | = | ['dde'.freeze].freeze
PACKAGE_NAME | = | 'dde'.freeze

Public Class methods

package_name()

[Source]

# File tk/lib/tk/winpkg.rb, line 17
  def self.package_name
    PACKAGE_NAME
  end

Public Instance methods

async_eval(topic, cmd, *args)

[Source]

# File tk/lib/tk/winpkg.rb, line 80
  def async_eval(topic, cmd, *args)
    tk_call('dde', 'eval', -async, topic, cmd, *args)
  end
async_execute(service, topic, data)

[Source]

# File tk/lib/tk/winpkg.rb, line 56
  def async_execute(service, topic, data)
    tk_call('dde', '-async', 'execute', service, topic, data)
  end
binary_request(service, topic, item)

[Source]

# File tk/lib/tk/winpkg.rb, line 68
  def binary_request(service, topic, item)
    tk_call('dde', 'request', '-binary', service, topic, item)
  end
eval(topic, cmd, *args)

[Source]

# File tk/lib/tk/winpkg.rb, line 76
  def eval(topic, cmd, *args)
    tk_call('dde', 'eval', topic, cmd, *args)
  end
execute(service, topic, data)

[Source]

# File tk/lib/tk/winpkg.rb, line 52
  def execute(service, topic, data)
    tk_call('dde', 'execute', service, topic, data)
  end
poke(service, topic, item, data)

[Source]

# File tk/lib/tk/winpkg.rb, line 60
  def poke(service, topic, item, data)
    tk_call('dde', 'poke', service, topic, item, data)
  end
request(service, topic, item)

[Source]

# File tk/lib/tk/winpkg.rb, line 64
  def request(service, topic, item)
    tk_call('dde', 'request', service, topic, item)
  end
servername(*args)

def servername(topic=None)

  tk_call('dde', 'servername', topic)

end

[Source]

# File tk/lib/tk/winpkg.rb, line 30
  def servername(*args)
    if args.size == 0
      tk_call('dde', 'servername')
    else
      if args[-1].kind_of?(Hash)  # dde 1.2 +
        keys = _symbolkey2str(args.pop)
        force = (keys.delete('force'))? '-force': None
        exact = (keys.delete('exact'))? '-exact': None
        if keys.size == 0
          tk_call('dde', 'servername', force, exact)
        elsif args.size == 0
          tk_call('dde', 'servername', force, exact, *hash_kv(keys))
        else
          tk_call('dde', 'servername', force, exact,
                  *((hash_kv(keys) << '--') + args))
        end
      else
        tk_call('dde', 'servername', *args)
      end
    end
  end
services(service, topic)

[Source]

# File tk/lib/tk/winpkg.rb, line 72
  def services(service, topic)
    tk_call('dde', 'services', service, topic)
  end


Module: TkWinRegistry

Module | TkWinRegistry
In: | tk/lib/tk/winpkg.rb

Methods

broadcast delete get keys set type values

Constants

TkCommandNames = ['registry'.freeze].freeze

Public Instance methods

broadcast(keynam, timeout=nil)

[Source]

# File tk/lib/tk/winpkg.rb, line 100
  def broadcast(keynam, timeout=nil)
    if timeout
      tk_call('registry', 'broadcast', keynam, '-timeout', timeout)
    else
      tk_call('registry', 'broadcast', keynam)
    end
  end
delete(keynam, valnam=None)

[Source]

# File tk/lib/tk/winpkg.rb, line 108
  def delete(keynam, valnam=None)
    tk_call('registry', 'delete', keynam, valnam)
  end
get(keynam, valnam)

[Source]

# File tk/lib/tk/winpkg.rb, line 112
  def get(keynam, valnam)
    tk_call('registry', 'get', keynam, valnam)
  end
keys(keynam, pattern=nil)

[Source]

# File tk/lib/tk/winpkg.rb, line 116
  def keys(keynam, pattern=nil)
    lst = tk_split_simplelist(tk_call('registry', 'keys', keynam))
    if pattern
      lst.find_all{|key| key =~ pattern}
    else
      lst
    end
  end
set(keynam, valnam=None, data=None, dattype=None)

[Source]

# File tk/lib/tk/winpkg.rb, line 125
  def set(keynam, valnam=None, data=None, dattype=None)
    tk_call('registry', 'set', keynam, valnam, data, dattype)
  end
type(keynam, valnam)

[Source]

# File tk/lib/tk/winpkg.rb, line 129
  def type(keynam, valnam)
    tk_call('registry', 'type', keynam, valnam)
  end
values(keynam, pattern=nil)

[Source]

# File tk/lib/tk/winpkg.rb, line 133
  def values(keynam, pattern=nil)
    lst = tk_split_simplelist(tk_call('registry', 'values', keynam))
    if pattern
      lst.find_all{|val| val =~ pattern}
    else
      lst
    end
  end


Class: TkWindow

Class | TkWindow
In: | tk/lib/tkextlib/tktrans/tktrans.rb tk/lib/tkextlib/tkDND/tkdnd.rb tk/lib/tkextlib/tkDND/shape.rb tk/lib/tkextlib/tcllib/cursor.rb tk/lib/tk.rb
Parent: | Object

Methods

bind_class bindtags bindtags= bindtags_shift bindtags_unshift caret colormodel command current_grab cursor_propagate cursor_restore database_class database_class database_classname database_classname destroy eventloop_tkwait eventloop_tkwait_destroy eventloop_tkwait_visibility eventloop_tkwait_window eventloop_wait eventloop_wait_destroy eventloop_wait_visibility eventloop_wait_window exist? focus grab grab_current grab_release grab_set grab_set_global grab_status grid grid_bbox grid_columnconfig grid_columnconfiginfo grid_columnconfigure grid_config grid_configure grid_forget grid_in grid_info grid_location grid_propagate grid_remove grid_rowconfig grid_rowconfiginfo grid_rowconfigure grid_size grid_slaves lower lower_window new pack pack_config pack_configure pack_forget pack_in pack_info pack_propagate pack_slaves place place_config place_configinfo place_configure place_forget place_in place_info place_slaves raise raise_window release_grab set_focus set_global_grab set_grab thread_tkwait thread_tkwait_destroy thread_tkwait_visibility thread_tkwait_window thread_wait thread_wait_destroy thread_wait_visibility thread_wait_window tktrans_get_image tktrans_set_image tkwait tkwait_destroy tkwait_window to_eval ungrid unpack unplace wait wait_destroy wait_visibility wait_window

Included Modules

Tk::TkDND::DND Tk::TkDND::Shape TkWinfo

Constants

TkCommandNames = [].freeze
WidgetClassName = ''.freeze

> If TkCommandNames[0] is a string (not a null string),

    assume the string is a Tcl/Tk's create command of the widget class.

Public Class methods

database_class()

[Source]

# File tk/lib/tk.rb, line 3947
  def self.database_class
    WidgetClassNames[self::WidgetClassName]
  end
database_classname()

[Source]

# File tk/lib/tk.rb, line 3944
  def self.database_classname
    self::WidgetClassName
  end
new(parent=nil, keys=nil)

[Source]

# File tk/lib/tk.rb, line 3834
  def initialize(parent=nil, keys=nil)
    if parent.kind_of? Hash
      keys = _symbolkey2str(parent)
      parent = keys.delete('parent')
      widgetname = keys.delete('widgetname')
      install_win(if parent then parent.path end, widgetname)
      without_creating = keys.delete('without_creating')
      # if without_creating && !widgetname
      #   fail ArgumentError,
      #        "if set 'without_creating' to true, need to define 'widgetname'"
      # end
    elsif keys
      keys = _symbolkey2str(keys)
      widgetname = keys.delete('widgetname')
      install_win(if parent then parent.path end, widgetname)
      without_creating = keys.delete('without_creating')
      # if without_creating && !widgetname
      #   fail ArgumentError,
      #        "if set 'without_creating' to true, need to define 'widgetname'"
      # end
    else
      install_win(if parent then parent.path end)
    end
    if self.method(:create_self).arity == 0
      p 'create_self has no arg' if $DEBUG
      create_self unless without_creating
      if keys
        # tk_call @path, 'configure', *hash_kv(keys)
        configure(keys)
      end
    else
      p 'create_self has args' if $DEBUG
      fontkeys = {}
      methodkeys = {}
      if keys
        #['font', 'kanjifont', 'latinfont', 'asciifont'].each{|key|
        #  fontkeys[key] = keys.delete(key) if keys.key?(key)
        #}
        __font_optkeys.each{|key|
          fkey = key.to_s
          fontkeys[fkey] = keys.delete(fkey) if keys.key?(fkey)

          fkey = "kanji#{key}"
          fontkeys[fkey] = keys.delete(fkey) if keys.key?(fkey)

          fkey = "latin#{key}"
          fontkeys[fkey] = keys.delete(fkey) if keys.key?(fkey)

          fkey = "ascii#{key}"
          fontkeys[fkey] = keys.delete(fkey) if keys.key?(fkey)
        }

        __methodcall_optkeys.each{|key|
          key = key.to_s
          methodkeys[key] = keys.delete(key) if keys.key?(key)
        }

        __ruby2val_optkeys.each{|key, method|
          key = key.to_s
          keys[key] = method.call(keys[key]) if keys.has_key?(key)
        }
      end
      if without_creating && keys
        #configure(keys)
        configure(__conv_keyonly_opts(keys))
      else
        #create_self(keys)
        create_self(__conv_keyonly_opts(keys))
      end
      font_configure(fontkeys) unless fontkeys.empty?
      configure(methodkeys) unless methodkeys.empty?
    end
  end
to_eval()

WidgetClassNames[WidgetClassName] = self

 ==> If self is a widget class, entry to the WidgetClassNames table.

[Source]

# File tk/lib/tk.rb, line 3830
  def self.to_eval
    self::WidgetClassName
  end

Public Instance methods

bind_class()

[Source]

# File tk/lib/tk.rb, line 3929
  def bind_class
    @db_class || self.class()
  end
bindtags(taglist=nil)

[Source]

# File tk/lib/tk.rb, line 4396
  def bindtags(taglist=nil)
    if taglist
      fail ArgumentError, "taglist must be Array" unless taglist.kind_of? Array
      tk_call('bindtags', path, taglist)
      taglist
    else
      list(tk_call('bindtags', path)).collect{|tag|
        if tag.kind_of?(String)
          if cls = WidgetClassNames[tag]
            cls
          elsif btag = TkBindTag.id2obj(tag)
            btag
          else
            tag
          end
        else
          tag
        end
      }
    end
  end
bindtags=(taglist)

[Source]

# File tk/lib/tk.rb, line 4418
  def bindtags=(taglist)
    bindtags(taglist)
    taglist
  end
bindtags_shift()

[Source]

# File tk/lib/tk.rb, line 4423
  def bindtags_shift
    taglist = bindtags
    tag = taglist.shift
    bindtags(taglist)
    tag
  end
bindtags_unshift(tag)

[Source]

# File tk/lib/tk.rb, line 4430
  def bindtags_unshift(tag)
    bindtags(bindtags().unshift(tag))
  end
caret(keys=nil)

[Source]

# File tk/lib/tk.rb, line 4307
  def caret(keys=nil)
    TkXIM.caret(path, keys)
  end
colormodel(model=None)

[Source]

# File tk/lib/tk.rb, line 4302
  def colormodel(model=None)
    tk_call('tk', 'colormodel', path, model)
    self
  end
command(cmd=nil, &b)

[Source]

# File tk/lib/tk.rb, line 4292
  def command(cmd=nil, &b)
    if cmd
      configure_cmd('command', cmd)
    elsif b
      configure_cmd('command', Proc.new(&b))
    else
      cget('command')
    end
  end
current_grab()

Alias for grab_current

cursor_propagate(cursor)

[Source]

# File tk/lib/tkextlib/tcllib/cursor.rb, line 56
  def cursor_propagate(cursor)
    # Sets the cursor for self and all its descendants to cursor.
    #tk_call_without_enc('::cursor::propagate', @path, cursor)
    Tk::Tcllib::Cursor.cursor_propagate(self, cursor)
  end
cursor_restore(cursor = None)

[Source]

# File tk/lib/tkextlib/tcllib/cursor.rb, line 61
  def cursor_restore(cursor = None)
    # Restore the original or previously set cursor for self and all its
    # descendants. If cursor is specified, that will be used if on any
    # widget that did not have a preset cursor (set by a previous call
    # to TkWindow#cursor_propagate).
    #tk_call_without_enc('::cursor::restore', @path, cursor)
    Tk::Tcllib::Cursor.cursor_restore(self, cursor)
  end
database_class()

[Source]

# File tk/lib/tk.rb, line 3936
  def database_class
    name = database_classname()
    if WidgetClassNames[name]
      WidgetClassNames[name]
    else
      TkDatabaseClass.new(name)
    end
  end
database_classname()

[Source]

# File tk/lib/tk.rb, line 3933
  def database_classname
    TkWinfo.classname(self)
  end
destroy()

[Source]

# File tk/lib/tk.rb, line 4311
  def destroy
    super
    children = []
    rexp = /^#{self.path}\.[^.]+$/
    TkCore::INTERP.tk_windows.each{|path, obj|
      children << [path, obj] if path =~ rexp
    }
    if defined?(@cmdtbl)
      for id in @cmdtbl
        uninstall_cmd id
      end
    end

    children.each{|path, obj|
      if defined?(@cmdtbl)
        for id in @cmdtbl
          uninstall_cmd id
        end
      end
      TkCore::INTERP.tk_windows.delete(path)
    }

    begin
      tk_call_without_enc('destroy', epath)
    rescue
    end
    uninstall_win
  end
eventloop_tkwait()

Alias for eventloop_wait_visibility

eventloop_tkwait_destroy()

Alias for eventloop_wait_destroy

eventloop_tkwait_visibility()

Alias for eventloop_wait_visibility

eventloop_tkwait_window()

Alias for eventloop_wait_destroy

eventloop_wait()

Alias for eventloop_wait_visibility

eventloop_wait_destroy()

[Source]

# File tk/lib/tk.rb, line 4378
  def eventloop_wait_destroy
    wait_destroy(false)
  end
eventloop_wait_visibility()

[Source]

# File tk/lib/tk.rb, line 4351
  def eventloop_wait_visibility
    wait_visibility(false)
  end
eventloop_wait_window()

Alias for eventloop_wait_destroy

exist?()

[Source]

# File tk/lib/tk.rb, line 3925
  def exist?
    TkWinfo.exist?(self)
  end
focus(force=false)

Alias for set_focus

grab(opt = nil)

[Source]

# File tk/lib/tk.rb, line 4230
  def grab(opt = nil)
    unless opt
      tk_call_without_enc('grab', 'set', path)
      return self
    end

    case opt
    when 'set', :set
      tk_call_without_enc('grab', 'set', path)
      return self
    when 'global', :global
      #return(tk_call('grab', 'set', '-global', path))
      tk_call_without_enc('grab', 'set', '-global', path)
      return self
    when 'release', :release
      #return tk_call('grab', 'release', path)
      tk_call_without_enc('grab', 'release', path)
      return self
    when 'current', :current
      return window(tk_call_without_enc('grab', 'current', path))
    when 'status', :status
      return tk_call_without_enc('grab', 'status', path)
    else
      return tk_call_without_enc('grab', opt, path)
    end
  end
grab_current()

[Source]

# File tk/lib/tk.rb, line 4257
  def grab_current
    grab('current')
  end
grab_release()

[Source]

# File tk/lib/tk.rb, line 4261
  def grab_release
    grab('release')
  end
grab_set()

[Source]

# File tk/lib/tk.rb, line 4265
  def grab_set
    grab('set')
  end
grab_set_global()

[Source]

# File tk/lib/tk.rb, line 4269
  def grab_set_global
    grab('global')
  end
grab_status()

[Source]

# File tk/lib/tk.rb, line 4273
  def grab_status
    grab('status')
  end
grid(keys = nil)

[Source]

# File tk/lib/tk.rb, line 4024
  def grid(keys = nil)
    #tk_call 'grid', epath, *hash_kv(keys)
    if keys
      TkGrid.configure(self, keys)
    else
      TkGrid.configure(self)
    end
    self
  end
grid_bbox(*args)

[Source]

# File tk/lib/tk.rb, line 4053
  def grid_bbox(*args)
    #list(tk_call('grid', 'bbox', epath, *args))
    TkGrid.bbox(self, *args)
  end
grid_columnconfig(index, keys)

[Source]

# File tk/lib/tk.rb, line 4072
  def grid_columnconfig(index, keys)
    #tk_call('grid', 'columnconfigure', epath, index, *hash_kv(keys))
    TkGrid.columnconfigure(self, index, keys)
  end
grid_columnconfiginfo(index, slot=nil)

[Source]

# File tk/lib/tk.rb, line 4084
  def grid_columnconfiginfo(index, slot=nil)
    #if slot
    #  tk_call('grid', 'columnconfigure', epath, index, "-#{slot}").to_i
    #else
    #  ilist = list(tk_call('grid', 'columnconfigure', epath, index))
    #  info = {}
    #  while key = ilist.shift
    #   info[key[1..-1]] = ilist.shift
    #  end
    #  info
    #end
    TkGrid.columnconfiginfo(self, index, slot)
  end
grid_columnconfigure(index, keys)

Alias for grid_columnconfig

grid_config(slot, value=None)

[Source]

# File tk/lib/tk.rb, line 4058
  def grid_config(slot, value=None)
    #if slot.kind_of? Hash
    #  tk_call 'grid', 'configure', epath, *hash_kv(slot)
    #else
    #  tk_call 'grid', 'configure', epath, "-#{slot}", value
    #end
    if slot.kind_of? Hash
      TkGrid.configure(self, slot)
    else
      TkGrid.configure(self, slot=>value)
    end
  end
grid_configure(slot, value=None)

Alias for grid_config

grid_forget()

[Source]

# File tk/lib/tk.rb, line 4046
  def grid_forget
    #tk_call('grid', 'forget', epath)
    TkGrid.forget(self)
    self
  end
grid_in(target, keys = nil)

[Source]

# File tk/lib/tk.rb, line 4034
  def grid_in(target, keys = nil)
    if keys
      keys = keys.dup
      keys['in'] = target
    else
      keys = {'in'=>target}
    end
    #tk_call 'grid', epath, *hash_kv(keys)
    TkGrid.configure(self, keys)
    self
  end
grid_info()

[Source]

# File tk/lib/tk.rb, line 4112
  def grid_info()
    #list(tk_call('grid', 'info', epath))
    TkGrid.info(self)
  end
grid_location(x, y)

[Source]

# File tk/lib/tk.rb, line 4117
  def grid_location(x, y)
    #list(tk_call('grid', 'location', epath, x, y))
    TkGrid.location(self, x, y)
  end
grid_propagate(mode=None)

[Source]

# File tk/lib/tk.rb, line 4122
  def grid_propagate(mode=None)
    #if mode == None
    #  bool(tk_call('grid', 'propagate', epath))
    #else
    #  tk_call('grid', 'propagate', epath, mode)
    #  self
    #end
    if mode == None
      TkGrid.propagate(self)
    else
      TkGrid.propagate(self, mode)
      self
    end
  end
grid_remove()

[Source]

# File tk/lib/tk.rb, line 4137
  def grid_remove()
    #tk_call 'grid', 'remove', epath
    TkGrid.remove(self)
    self
  end
grid_rowconfig(index, keys)

[Source]

# File tk/lib/tk.rb, line 4078
  def grid_rowconfig(index, keys)
    #tk_call('grid', 'rowconfigure', epath, index, *hash_kv(keys))
    TkGrid.rowconfigure(self, index, keys)
  end
grid_rowconfiginfo(index, slot=nil)

[Source]

# File tk/lib/tk.rb, line 4098
  def grid_rowconfiginfo(index, slot=nil)
    #if slot
    #  tk_call('grid', 'rowconfigure', epath, index, "-#{slot}").to_i
    #else
    #  ilist = list(tk_call('grid', 'rowconfigure', epath, index))
    #  info = {}
    #  while key = ilist.shift
    #   info[key[1..-1]] = ilist.shift
    #  end
    #  info
    #end
    TkGrid.rowconfiginfo(self, index, slot)
  end
grid_rowconfigure(index, keys)

Alias for grid_rowconfig

grid_size()

[Source]

# File tk/lib/tk.rb, line 4143
  def grid_size()
    #list(tk_call('grid', 'size', epath))
    TkGrid.size(self)
  end
grid_slaves(args)

[Source]

# File tk/lib/tk.rb, line 4148
  def grid_slaves(args)
    #list(tk_call('grid', 'slaves', epath, *hash_kv(args)))
    TkGrid.slaves(self, args)
  end
lower(below=None)

[Source]

# File tk/lib/tk.rb, line 4277
  def lower(below=None)
    # below = below.epath if below.kind_of?(TkObject)
    below = _epath(below)
    tk_call 'lower', epath, below
    self
  end
lower_window(below=None)

Alias for lower

pack(keys = nil)

[Source]

# File tk/lib/tk.rb, line 3951
  def pack(keys = nil)
    #tk_call_without_enc('pack', epath, *hash_kv(keys, true))
    if keys
      TkPack.configure(self, keys)
    else
      TkPack.configure(self)
    end
    self
  end
pack_config(slot, value=None)

[Source]

# File tk/lib/tk.rb, line 3980
  def pack_config(slot, value=None)
    #if slot.kind_of? Hash
    #  tk_call 'pack', 'configure', epath, *hash_kv(slot)
    #else
    #  tk_call 'pack', 'configure', epath, "-#{slot}", value
    #end
    if slot.kind_of? Hash
      TkPack.configure(self, slot)
    else
      TkPack.configure(self, slot=>value)
    end
  end
pack_configure(slot, value=None)

Alias for pack_config

pack_forget()

[Source]

# File tk/lib/tk.rb, line 3973
  def pack_forget
    #tk_call_without_enc('pack', 'forget', epath)
    TkPack.forget(self)
    self
  end
pack_in(target, keys = nil)

[Source]

# File tk/lib/tk.rb, line 3961
  def pack_in(target, keys = nil)
    if keys
      keys = keys.dup
      keys['in'] = target
    else
      keys = {'in'=>target}
    end
    #tk_call 'pack', epath, *hash_kv(keys)
    TkPack.configure(self, keys)
    self
  end
pack_info()

[Source]

# File tk/lib/tk.rb, line 3994
  def pack_info()
    #ilist = list(tk_call('pack', 'info', epath))
    #info = {}
    #while key = ilist.shift
    #  info[key[1..-1]] = ilist.shift
    #end
    #return info
    TkPack.info(self)
  end
pack_propagate(mode=None)

[Source]

# File tk/lib/tk.rb, line 4004
  def pack_propagate(mode=None)
    #if mode == None
    #  bool(tk_call('pack', 'propagate', epath))
    #else
    #  tk_call('pack', 'propagate', epath, mode)
    #  self
    #end
    if mode == None
      TkPack.propagate(self)
    else
      TkPack.propagate(self, mode)
      self
    end
  end
pack_slaves()

[Source]

# File tk/lib/tk.rb, line 4019
  def pack_slaves()
    #list(tk_call('pack', 'slaves', epath))
    TkPack.slaves(self)
  end
place(keys)

[Source]

# File tk/lib/tk.rb, line 4153
  def place(keys)
    #tk_call 'place', epath, *hash_kv(keys)
    TkPlace.configure(self, keys)
    self
  end
place_config(slot, value=None)

[Source]

# File tk/lib/tk.rb, line 4178
  def place_config(slot, value=None)
    #if slot.kind_of? Hash
    #  tk_call 'place', 'configure', epath, *hash_kv(slot)
    #else
    #  tk_call 'place', 'configure', epath, "-#{slot}", value
    #end
    TkPlace.configure(self, slot, value)
  end
place_configinfo(slot = nil)

[Source]

# File tk/lib/tk.rb, line 4188
  def place_configinfo(slot = nil)
    # for >= Tk8.4a2 ?
    #if slot
    #  conf = tk_split_list(tk_call('place', 'configure', epath, "-#{slot}") )
    #  conf[0] = conf[0][1..-1]
    #  conf
    #else
    #  tk_split_simplelist(tk_call('place',
    #                             'configure', epath)).collect{|conflist|
    #   conf = tk_split_simplelist(conflist)
    #   conf[0] = conf[0][1..-1]
    #   conf
    #  }
    #end
    TkPlace.configinfo(self, slot)
  end
place_configure(slot, value=None)

Alias for place_config

place_forget()

[Source]

# File tk/lib/tk.rb, line 4171
  def  place_forget
    #tk_call 'place', 'forget', epath
    TkPlace.forget(self)
    self
  end
place_in(target, keys = nil)

[Source]

# File tk/lib/tk.rb, line 4159
  def place_in(target, keys = nil)
    if keys
      keys = keys.dup
      keys['in'] = target
    else
      keys = {'in'=>target}
    end
    #tk_call 'place', epath, *hash_kv(keys)
    TkPlace.configure(self, keys)
    self
  end
place_info()

[Source]

# File tk/lib/tk.rb, line 4205
  def place_info()
    #ilist = list(tk_call('place', 'info', epath))
    #info = {}
    #while key = ilist.shift
    #  info[key[1..-1]] = ilist.shift
    #end
    #return info
    TkPlace.info(self)
  end
place_slaves()

[Source]

# File tk/lib/tk.rb, line 4215
  def place_slaves()
    #list(tk_call('place', 'slaves', epath))
    TkPlace.slaves(self)
  end
raise(above=None)

[Source]

# File tk/lib/tk.rb, line 4284
  def raise(above=None)
    #above = above.epath if above.kind_of?(TkObject)
    above = _epath(above)
    tk_call 'raise', epath, above
    self
  end
raise_window(above=None)

Alias for raise

release_grab()

Alias for grab_release

set_focus(force=false)

[Source]

# File tk/lib/tk.rb, line 4220
  def set_focus(force=false)
    if force
      tk_call_without_enc('focus', '-force', path)
    else
      tk_call_without_enc('focus', path)
    end
    self
  end
set_global_grab()

Alias for grab_set_global

set_grab()

Alias for grab_set

thread_tkwait()

Alias for thread_wait_visibility

thread_tkwait_destroy()

Alias for thread_wait_destroy

thread_tkwait_visibility()

Alias for thread_wait_visibility

thread_tkwait_window()

Alias for thread_wait_destroy

thread_wait()

Alias for thread_wait_visibility

thread_wait_destroy()

[Source]

# File tk/lib/tk.rb, line 4382
  def thread_wait_destroy
    wait_destroy(true)
  end
thread_wait_visibility()

[Source]

# File tk/lib/tk.rb, line 4354
  def thread_wait_visibility
    wait_visibility(true)
  end
thread_wait_window()

Alias for thread_wait_destroy

tktrans_get_image()

[Source]

# File tk/lib/tkextlib/tktrans/tktrans.rb, line 37
  def tktrans_get_image()
    tk_send('tktrans::setwidget', @path)
  end
tktrans_set_image(img)

[Source]

# File tk/lib/tkextlib/tktrans/tktrans.rb, line 33
  def tktrans_set_image(img)
    tk_send('tktrans::setwidget', @path, img)
    self
  end
tkwait(on_thread = true)

Alias for wait_visibility

tkwait_destroy(on_thread = true)

Alias for wait_destroy

tkwait_window(on_thread = true)

Alias for wait_destroy

ungrid()

Alias for grid_forget

unpack()

Alias for pack_forget

unplace()

Alias for place_forget

wait(on_thread = true)

Alias for wait_visibility

wait_destroy(on_thread = true)

[Source]

# File tk/lib/tk.rb, line 4366
  def wait_destroy(on_thread = true)
    if $SAFE >= 4
      fail SecurityError, "can't wait destroy at $SAFE >= 4"
    end
    on_thread &= (Thread.list.size != 1)
    if on_thread
      INTERP._thread_tkwait('window', epath)
    else
      INTERP._invoke('tkwait', 'window', epath)
    end
  end
wait_visibility(on_thread = true)

[Source]

# File tk/lib/tk.rb, line 4340
  def wait_visibility(on_thread = true)
    if $SAFE >= 4
      fail SecurityError, "can't wait visibility at $SAFE >= 4"
    end
    on_thread &= (Thread.list.size != 1)
    if on_thread
      INTERP._thread_tkwait('visibility', path)
    else
      INTERP._invoke('tkwait', 'visibility', path)
    end
  end
wait_window(on_thread = true)

Alias for wait_destroy


Module: TkWinfo

Module | TkWinfo
In: | tk/lib/tk/winfo.rb

tk/winfo.rb : methods for winfo command

Methods

appname atom atomname cells children classname colormapfull containing depth exist? fpixels geometry height id interps manager mapped? parent pixels pointerx pointerxy pointery reqheight reqwidth rgb rootx rooty screen screencells screendepth screenheight screenmmheight screenmmwidth screenvisual screenwidth server toplevel viewable visual visualid visualsavailable vrootheight vrootwidth vrootx vrooty widget width winfo_appname winfo_atom winfo_atomname winfo_cells winfo_children winfo_class winfo_classname winfo_colormapfull winfo_containing winfo_depth winfo_exist? winfo_fpixels winfo_geometry winfo_height winfo_id winfo_interps winfo_manager winfo_mapped? winfo_parent winfo_pixels winfo_pointerx winfo_pointerxy winfo_pointery winfo_reqheight winfo_reqwidth winfo_rgb winfo_rootx winfo_rooty winfo_screen winfo_screencells winfo_screendepth winfo_screenheight winfo_screenmmheight winfo_screenmmwidth winfo_screenvisual winfo_screenwidth winfo_server winfo_toplevel winfo_viewable winfo_visual winfo_visualid winfo_visualsavailable winfo_vrootheight winfo_vrootwidth winfo_vrootx winfo_vrooty winfo_widget winfo_width winfo_x winfo_y x y

Included Modules

Tk

Constants

TkCommandNames = ['winfo'.freeze].freeze

Public Class methods

appname(win)

[Source]

# File tk/lib/tk/winfo.rb, line 153
  def TkWinfo.appname(win)
    tk_call('winfo', 'name', win)
  end
atom(name, win=nil)

[Source]

# File tk/lib/tk/winfo.rb, line 15
  def TkWinfo.atom(name, win=nil)
    if win
      number(tk_call_without_enc('winfo', 'atom', '-displayof', win,
                                 _get_eval_enc_str(name)))
    else
      number(tk_call_without_enc('winfo', 'atom', _get_eval_enc_str(name)))
    end
  end
atomname(id, win=nil)

[Source]

# File tk/lib/tk/winfo.rb, line 27
  def TkWinfo.atomname(id, win=nil)
    if win
      _fromUTF8(tk_call_without_enc('winfo', 'atomname',
                                    '-displayof', win, id))
    else
      _fromUTF8(tk_call_without_enc('winfo', 'atomname', id))
    end
  end
cells(win)

[Source]

# File tk/lib/tk/winfo.rb, line 39
  def TkWinfo.cells(win)
    number(tk_call_without_enc('winfo', 'cells', win))
  end
children(win)

[Source]

# File tk/lib/tk/winfo.rb, line 46
  def TkWinfo.children(win)
    list(tk_call_without_enc('winfo', 'children', win))
  end
classname(win)

[Source]

# File tk/lib/tk/winfo.rb, line 53
  def TkWinfo.classname(win)
    tk_call_without_enc('winfo', 'class', win)
  end
colormapfull(win)

[Source]

# File tk/lib/tk/winfo.rb, line 61
  def TkWinfo.colormapfull(win)
     bool(tk_call_without_enc('winfo', 'colormapfull', win))
  end
containing(rootX, rootY, win=nil)

[Source]

# File tk/lib/tk/winfo.rb, line 68
  def TkWinfo.containing(rootX, rootY, win=nil)
    if win
      window(tk_call_without_enc('winfo', 'containing',
                                 '-displayof', win, rootX, rootY))
    else
      window(tk_call_without_enc('winfo', 'containing', rootX, rootY))
    end
  end
depth(win)

[Source]

# File tk/lib/tk/winfo.rb, line 80
  def TkWinfo.depth(win)
    number(tk_call_without_enc('winfo', 'depth', win))
  end
exist?(win)

[Source]

# File tk/lib/tk/winfo.rb, line 87
  def TkWinfo.exist?(win)
    bool(tk_call_without_enc('winfo', 'exists', win))
  end
fpixels(win, dist)

[Source]

# File tk/lib/tk/winfo.rb, line 94
  def TkWinfo.fpixels(win, dist)
    number(tk_call_without_enc('winfo', 'fpixels', win, dist))
  end
geometry(win)

[Source]

# File tk/lib/tk/winfo.rb, line 101
  def TkWinfo.geometry(win)
    tk_call_without_enc('winfo', 'geometry', win)
  end
height(win)

[Source]

# File tk/lib/tk/winfo.rb, line 108
  def TkWinfo.height(win)
    number(tk_call_without_enc('winfo', 'height', win))
  end
id(win)

[Source]

# File tk/lib/tk/winfo.rb, line 115
  def TkWinfo.id(win)
    tk_call_without_enc('winfo', 'id', win)
  end
interps(win=nil)

[Source]

# File tk/lib/tk/winfo.rb, line 122
  def TkWinfo.interps(win=nil)
    if win
      #tk_split_simplelist(tk_call_without_enc('winfo', 'interps',
      #                                        '-displayof', win))
      tk_split_simplelist(tk_call_without_enc('winfo', 'interps',
                                              '-displayof', win),
                          false, true)
    else
      #tk_split_simplelist(tk_call_without_enc('winfo', 'interps'))
      tk_split_simplelist(tk_call_without_enc('winfo', 'interps'),
                          false, true)
    end
  end
manager(win)

[Source]

# File tk/lib/tk/winfo.rb, line 146
  def TkWinfo.manager(win)
    tk_call_without_enc('winfo', 'manager', win)
  end
mapped?(win)

[Source]

# File tk/lib/tk/winfo.rb, line 139
  def TkWinfo.mapped?(win)
    bool(tk_call_without_enc('winfo', 'ismapped', win))
  end
parent(win)

[Source]

# File tk/lib/tk/winfo.rb, line 160
  def TkWinfo.parent(win)
    window(tk_call_without_enc('winfo', 'parent', win))
  end
pixels(win, dist)

[Source]

# File tk/lib/tk/winfo.rb, line 178
  def TkWinfo.pixels(win, dist)
    number(tk_call_without_enc('winfo', 'pixels', win, dist))
  end
pointerx(win)

[Source]

# File tk/lib/tk/winfo.rb, line 372
  def TkWinfo.pointerx(win)
    number(tk_call_without_enc('winfo', 'pointerx', win))
  end
pointerxy(win)

[Source]

# File tk/lib/tk/winfo.rb, line 386
  def TkWinfo.pointerxy(win)
    list(tk_call_without_enc('winfo', 'pointerxy', win))
  end
pointery(win)

[Source]

# File tk/lib/tk/winfo.rb, line 379
  def TkWinfo.pointery(win)
    number(tk_call_without_enc('winfo', 'pointery', win))
  end
reqheight(win)

[Source]

# File tk/lib/tk/winfo.rb, line 185
  def TkWinfo.reqheight(win)
    number(tk_call_without_enc('winfo', 'reqheight', win))
  end
reqwidth(win)

[Source]

# File tk/lib/tk/winfo.rb, line 192
  def TkWinfo.reqwidth(win)
    number(tk_call_without_enc('winfo', 'reqwidth', win))
  end
rgb(win, color)

[Source]

# File tk/lib/tk/winfo.rb, line 199
  def TkWinfo.rgb(win, color)
    list(tk_call_without_enc('winfo', 'rgb', win, color))
  end
rootx(win)

[Source]

# File tk/lib/tk/winfo.rb, line 206
  def TkWinfo.rootx(win)
    number(tk_call_without_enc('winfo', 'rootx', win))
  end
rooty(win)

[Source]

# File tk/lib/tk/winfo.rb, line 213
  def TkWinfo.rooty(win)
    number(tk_call_without_enc('winfo', 'rooty', win))
  end
screen(win)

[Source]

# File tk/lib/tk/winfo.rb, line 220
  def TkWinfo.screen(win)
    tk_call('winfo', 'screen', win)
  end
screencells(win)

[Source]

# File tk/lib/tk/winfo.rb, line 227
  def TkWinfo.screencells(win)
    number(tk_call_without_enc('winfo', 'screencells', win))
  end
screendepth(win)

[Source]

# File tk/lib/tk/winfo.rb, line 234
  def TkWinfo.screendepth(win)
    number(tk_call_without_enc('winfo', 'screendepth', win))
  end
screenheight(win)

[Source]

# File tk/lib/tk/winfo.rb, line 241
  def TkWinfo.screenheight (win)
    number(tk_call_without_enc('winfo', 'screenheight', win))
  end
screenmmheight(win)

[Source]

# File tk/lib/tk/winfo.rb, line 248
  def TkWinfo.screenmmheight(win)
    number(tk_call_without_enc('winfo', 'screenmmheight', win))
  end
screenmmwidth(win)

[Source]

# File tk/lib/tk/winfo.rb, line 255
  def TkWinfo.screenmmwidth(win)
    number(tk_call_without_enc('winfo', 'screenmmwidth', win))
  end
screenvisual(win)

[Source]

# File tk/lib/tk/winfo.rb, line 262
  def TkWinfo.screenvisual(win)
    tk_call_without_enc('winfo', 'screenvisual', win)
  end
screenwidth(win)

[Source]

# File tk/lib/tk/winfo.rb, line 269
  def TkWinfo.screenwidth(win)
    number(tk_call_without_enc('winfo', 'screenwidth', win))
  end
server(win)

[Source]

# File tk/lib/tk/winfo.rb, line 276
  def TkWinfo.server(win)
    tk_call('winfo', 'server', win)
  end
toplevel(win)

[Source]

# File tk/lib/tk/winfo.rb, line 283
  def TkWinfo.toplevel(win)
    window(tk_call_without_enc('winfo', 'toplevel', win))
  end
viewable(win)

[Source]

# File tk/lib/tk/winfo.rb, line 365
  def TkWinfo.viewable(win)
    bool(tk_call_without_enc('winfo', 'viewable', win))
  end
visual(win)

[Source]

# File tk/lib/tk/winfo.rb, line 290
  def TkWinfo.visual(win)
    tk_call_without_enc('winfo', 'visual', win)
  end
visualid(win)

[Source]

# File tk/lib/tk/winfo.rb, line 297
  def TkWinfo.visualid(win)
    tk_call_without_enc('winfo', 'visualid', win)
  end
visualsavailable(win, includeids=false)

[Source]

# File tk/lib/tk/winfo.rb, line 304
  def TkWinfo.visualsavailable(win, includeids=false)
    if includeids
      list(tk_call_without_enc('winfo', 'visualsavailable',
                               win, "includeids"))
    else
      list(tk_call_without_enc('winfo', 'visualsavailable', win))
    end
  end
vrootheight(win)

[Source]

# File tk/lib/tk/winfo.rb, line 316
  def TkWinfo.vrootheight(win)
    number(tk_call_without_enc('winfo', 'vrootheight', win))
  end
vrootwidth(win)

[Source]

# File tk/lib/tk/winfo.rb, line 323
  def TkWinfo.vrootwidth(win)
    number(tk_call_without_enc('winfo', 'vrootwidth', win))
  end
vrootx(win)

[Source]

# File tk/lib/tk/winfo.rb, line 330
  def TkWinfo.vrootx(win)
    number(tk_call_without_enc('winfo', 'vrootx', win))
  end
vrooty(win)

[Source]

# File tk/lib/tk/winfo.rb, line 337
  def TkWinfo.vrooty(win)
    number(tk_call_without_enc('winfo', 'vrooty', win))
  end
widget(id, win=nil)

[Source]

# File tk/lib/tk/winfo.rb, line 167
  def TkWinfo.widget(id, win=nil)
    if win
      window(tk_call_without_enc('winfo', 'pathname', '-displayof', win, id))
    else
      window(tk_call_without_enc('winfo', 'pathname', id))
    end
  end
width(win)

[Source]

# File tk/lib/tk/winfo.rb, line 344
  def TkWinfo.width(win)
    number(tk_call_without_enc('winfo', 'width', win))
  end
x(win)

[Source]

# File tk/lib/tk/winfo.rb, line 351
  def TkWinfo.x(win)
    number(tk_call_without_enc('winfo', 'x', win))
  end
y(win)

[Source]

# File tk/lib/tk/winfo.rb, line 358
  def TkWinfo.y(win)
    number(tk_call_without_enc('winfo', 'y', win))
  end

Public Instance methods

winfo_appname()

[Source]

# File tk/lib/tk/winfo.rb, line 156
  def winfo_appname
    TkWinfo.appname self
  end
winfo_atom(name)

[Source]

# File tk/lib/tk/winfo.rb, line 23
  def winfo_atom(name)
    TkWinfo.atom(name, self)
  end
winfo_atomname(id)

[Source]

# File tk/lib/tk/winfo.rb, line 35
  def winfo_atomname(id)
    TkWinfo.atomname(id, self)
  end
winfo_cells()

[Source]

# File tk/lib/tk/winfo.rb, line 42
  def winfo_cells
    TkWinfo.cells self
  end
winfo_children()

[Source]

# File tk/lib/tk/winfo.rb, line 49
  def winfo_children
    TkWinfo.children self
  end
winfo_class()

Alias for winfo_classname

winfo_classname()

[Source]

# File tk/lib/tk/winfo.rb, line 56
  def winfo_classname
    TkWinfo.classname self
  end
winfo_colormapfull()

[Source]

# File tk/lib/tk/winfo.rb, line 64
  def winfo_colormapfull
    TkWinfo.colormapfull self
  end
winfo_containing(x, y)

[Source]

# File tk/lib/tk/winfo.rb, line 76
  def winfo_containing(x, y)
    TkWinfo.containing(x, y, self)
  end
winfo_depth()

[Source]

# File tk/lib/tk/winfo.rb, line 83
  def winfo_depth
    TkWinfo.depth self
  end
winfo_exist?()

[Source]

# File tk/lib/tk/winfo.rb, line 90
  def winfo_exist?
    TkWinfo.exist? self
  end
winfo_fpixels(dist)

[Source]

# File tk/lib/tk/winfo.rb, line 97
  def winfo_fpixels(dist)
    TkWinfo.fpixels self, dist
  end
winfo_geometry()

[Source]

# File tk/lib/tk/winfo.rb, line 104
  def winfo_geometry
    TkWinfo.geometry self
  end
winfo_height()

[Source]

# File tk/lib/tk/winfo.rb, line 111
  def winfo_height
    TkWinfo.height self
  end
winfo_id()

[Source]

# File tk/lib/tk/winfo.rb, line 118
  def winfo_id
    TkWinfo.id self
  end
winfo_interps()

[Source]

# File tk/lib/tk/winfo.rb, line 135
  def winfo_interps
    TkWinfo.interps self
  end
winfo_manager()

[Source]

# File tk/lib/tk/winfo.rb, line 149
  def winfo_manager
    TkWinfo.manager self
  end
winfo_mapped?()

[Source]

# File tk/lib/tk/winfo.rb, line 142
  def winfo_mapped?
    TkWinfo.mapped? self
  end
winfo_parent()

[Source]

# File tk/lib/tk/winfo.rb, line 163
  def winfo_parent
    TkWinfo.parent self
  end
winfo_pixels(dist)

[Source]

# File tk/lib/tk/winfo.rb, line 181
  def winfo_pixels(dist)
    TkWinfo.pixels self, dist
  end
winfo_pointerx()

[Source]

# File tk/lib/tk/winfo.rb, line 375
  def winfo_pointerx
    TkWinfo.pointerx self
  end
winfo_pointerxy()

[Source]

# File tk/lib/tk/winfo.rb, line 389
  def winfo_pointerxy
    TkWinfo.pointerxy self
  end
winfo_pointery()

[Source]

# File tk/lib/tk/winfo.rb, line 382
  def winfo_pointery
    TkWinfo.pointery self
  end
winfo_reqheight()

[Source]

# File tk/lib/tk/winfo.rb, line 188
  def winfo_reqheight
    TkWinfo.reqheight self
  end
winfo_reqwidth()

[Source]

# File tk/lib/tk/winfo.rb, line 195
  def winfo_reqwidth
    TkWinfo.reqwidth self
  end
winfo_rgb(color)

[Source]

# File tk/lib/tk/winfo.rb, line 202
  def winfo_rgb(color)
    TkWinfo.rgb self, color
  end
winfo_rootx()

[Source]

# File tk/lib/tk/winfo.rb, line 209
  def winfo_rootx
    TkWinfo.rootx self
  end
winfo_rooty()

[Source]

# File tk/lib/tk/winfo.rb, line 216
  def winfo_rooty
    TkWinfo.rooty self
  end
winfo_screen()

[Source]

# File tk/lib/tk/winfo.rb, line 223
  def winfo_screen
    TkWinfo.screen self
  end
winfo_screencells()

[Source]

# File tk/lib/tk/winfo.rb, line 230
  def winfo_screencells
    TkWinfo.screencells self
  end
winfo_screendepth()

[Source]

# File tk/lib/tk/winfo.rb, line 237
  def winfo_screendepth
    TkWinfo.screendepth self
  end
winfo_screenheight()

[Source]

# File tk/lib/tk/winfo.rb, line 244
  def winfo_screenheight
    TkWinfo.screenheight self
  end
winfo_screenmmheight()

[Source]

# File tk/lib/tk/winfo.rb, line 251
  def winfo_screenmmheight
    TkWinfo.screenmmheight self
  end
winfo_screenmmwidth()

[Source]

# File tk/lib/tk/winfo.rb, line 258
  def winfo_screenmmwidth
    TkWinfo.screenmmwidth self
  end
winfo_screenvisual()

[Source]

# File tk/lib/tk/winfo.rb, line 265
  def winfo_screenvisual
    TkWinfo.screenvisual self
  end
winfo_screenwidth()

[Source]

# File tk/lib/tk/winfo.rb, line 272
  def winfo_screenwidth
    TkWinfo.screenwidth self
  end
winfo_server()

[Source]

# File tk/lib/tk/winfo.rb, line 279
  def winfo_server
    TkWinfo.server self
  end
winfo_toplevel()

[Source]

# File tk/lib/tk/winfo.rb, line 286
  def winfo_toplevel
    TkWinfo.toplevel self
  end
winfo_viewable()

[Source]

# File tk/lib/tk/winfo.rb, line 368
  def winfo_viewable
    TkWinfo.viewable self
  end
winfo_visual()

[Source]

# File tk/lib/tk/winfo.rb, line 293
  def winfo_visual
    TkWinfo.visual self
  end
winfo_visualid()

[Source]

# File tk/lib/tk/winfo.rb, line 300
  def winfo_visualid
    TkWinfo.visualid self
  end
winfo_visualsavailable(includeids=false)

[Source]

# File tk/lib/tk/winfo.rb, line 312
  def winfo_visualsavailable(includeids=false)
    TkWinfo.visualsavailable self, includeids
  end
winfo_vrootheight()

[Source]

# File tk/lib/tk/winfo.rb, line 319
  def winfo_vrootheight
    TkWinfo.vrootheight self
  end
winfo_vrootwidth()

[Source]

# File tk/lib/tk/winfo.rb, line 326
  def winfo_vrootwidth
    TkWinfo.vrootwidth self
  end
winfo_vrootx()

[Source]

# File tk/lib/tk/winfo.rb, line 333
  def winfo_vrootx
    TkWinfo.vrootx self
  end
winfo_vrooty()

[Source]

# File tk/lib/tk/winfo.rb, line 340
  def winfo_vrooty
    TkWinfo.vrooty self
  end
winfo_widget(id)

[Source]

# File tk/lib/tk/winfo.rb, line 174
  def winfo_widget(id)
    TkWinfo.widget id, self
  end
winfo_width()

[Source]

# File tk/lib/tk/winfo.rb, line 347
  def winfo_width
    TkWinfo.width self
  end
winfo_x()

[Source]

# File tk/lib/tk/winfo.rb, line 354
  def winfo_x
    TkWinfo.x self
  end
winfo_y()

[Source]

# File tk/lib/tk/winfo.rb, line 361
  def winfo_y
    TkWinfo.y self
  end


Module: TkXIM

Module | TkXIM
In: | tk/lib/tk/xim.rb

Methods

caret caret configinfo configure current_configinfo imconfiginfo imconfigure useinputmethods useinputmethods useinputmethods_displayof

Included Modules

Tk

Constants

TkCommandNames = ['imconfigure'.freeze].freeze

Public Class methods

caret(win, keys=nil)

[Source]

# File tk/lib/tk/xim.rb, line 34
  def TkXIM.caret(win, keys=nil)
    if keys
      tk_call_without_enc('tk', 'caret', win, *hash_kv(keys))
      self
    else
      lst = tk_split_list(tk_call_without_enc('tk', 'caret', win))
      info = {}
      while key = lst.shift
        info[key[1..-1]] = lst.shift
      end
      info
    end
  end
configinfo(win, slot=nil)

[Source]

# File tk/lib/tk/xim.rb, line 61
  def TkXIM.configinfo(win, slot=nil)
    if TkComm::GET_CONFIGINFOwoRES_AS_ARRAY
      begin
        if /^8\.*/ === Tk::TK_VERSION  && JAPANIZED_TK
          if slot
            conf = tk_split_list(tk_call('imconfigure', win, "-#{slot}"))
            conf[0] = conf[0][1..-1]
            conf
          else
            tk_split_list(tk_call('imconfigure', win)).collect{|conf|
              conf[0] = conf[0][1..-1]
              conf
            }
          end
        else
          []
        end
      rescue
        []
      end
    else # ! TkComm::GET_CONFIGINFOwoRES_AS_ARRAY
      TkXIM.current_configinfo(win, slot)
    end
  end
configure(win, slot, value=None)

[Source]

# File tk/lib/tk/xim.rb, line 48
  def TkXIM.configure(win, slot, value=None)
    begin
      if /^8\.*/ === Tk::TK_VERSION  && JAPANIZED_TK
        if slot.kind_of? Hash
          tk_call('imconfigure', win, *hash_kv(slot))
        else
          tk_call('imconfigure', win, "-#{slot}", value)
        end
      end
    rescue
    end
  end
current_configinfo(win, slot=nil)

[Source]

# File tk/lib/tk/xim.rb, line 86
  def TkXIM.current_configinfo(win, slot=nil)
    begin
      if /^8\.*/ === Tk::TK_VERSION  && JAPANIZED_TK
        if slot
          conf = tk_split_list(tk_call('imconfigure', win, "-#{slot}"))
          { conf[0][1..-1] => conf[1] }
        else
          ret = {}
          tk_split_list(tk_call('imconfigure', win)).each{|conf|
            ret[conf[0][1..-1]] = conf[1]
          }
          ret
        end
      else
        {}
      end
    rescue
      {}
    end
  end
useinputmethods(value = None, win = nil)

[Source]

# File tk/lib/tk/xim.rb, line 12
  def TkXIM.useinputmethods(value = None, win = nil)
    if value == None
      if win
        bool(tk_call_without_enc('tk', 'useinputmethods',
                                 '-displayof', win))
      else
        bool(tk_call_without_enc('tk', 'useinputmethods'))
      end
    else
      if win
        bool(tk_call_without_enc('tk', 'useinputmethods',
                                 '-displayof', win, value))
      else
        bool(tk_call_without_enc('tk', 'useinputmethods', value))
      end
    end
  end
useinputmethods_displayof(win, value = None)

[Source]

# File tk/lib/tk/xim.rb, line 30
  def TkXIM.useinputmethods_displayof(win, value = None)
    TkXIM.useinputmethods(value, win)
  end

Public Instance methods

caret(keys=nil)

[Source]

# File tk/lib/tk/xim.rb, line 111
  def caret(keys=nil)
    TkXIM.caret(self, keys=nil)
  end
imconfiginfo(slot=nil)

[Source]

# File tk/lib/tk/xim.rb, line 119
  def imconfiginfo(slot=nil)
    TkXIM.configinfo(self, slot)
  end
imconfigure(slot, value=None)

[Source]

# File tk/lib/tk/xim.rb, line 115
  def imconfigure(slot, value=None)
    TkXIM.configure(self, slot, value)
  end
useinputmethods(value=None)

[Source]

# File tk/lib/tk/xim.rb, line 107
  def useinputmethods(value=None)
    TkXIM.useinputmethods(value, self)
  end


Class: TkXScrollbar

Class | TkXScrollbar
In: | tk/lib/tk/scrollbar.rb
Parent: | TkScrollbar


Class: TkYScrollbar

Class | TkYScrollbar
In: | tk/lib/tk/scrollbar.rb
Parent: | TkScrollbar


Class: TkcArc

Class | TkcArc
In: | tk/lib/tk/canvas.rb
Parent: | TkcItem

Constants

CItemTypeName = 'arc'.freeze


Class: TkcBitmap

Class | TkcBitmap
In: | tk/lib/tk/canvas.rb
Parent: | TkcItem

Constants

CItemTypeName = 'bitmap'.freeze


Class: TkcGroup

Class | TkcGroup
In: | tk/lib/tk/canvastag.rb
Parent: | TkcTag

Methods

add exclude include new

Constants

Tk_cGroup_ID = ['tkcg'.freeze, '00000'.taint].freeze

Public Class methods

new(parent, *args)

def create_self(parent, *args)

[Source]

# File tk/lib/tk/canvastag.rb, line 344
  def initialize(parent, *args)
    #unless parent.kind_of?(TkCanvas)
    #  fail ArgumentError, "expect TkCanvas for 1st argument"
    #end
    @c = parent
    @cpath = parent.path
    # @path = @id = Tk_cGroup_ID.join('')
    @path = @id = Tk_cGroup_ID.join(TkCore::INTERP._ip_id_)
    CTagID_TBL[@cpath] = {} unless CTagID_TBL[@cpath]
    CTagID_TBL[@cpath][@id] = self
    Tk_cGroup_ID[1].succ!
    include(*args) if args != []
  end

Public Instance methods

add(*tags)

Alias for include

exclude(*tags)

[Source]

# File tk/lib/tk/canvastag.rb, line 368
  def exclude(*tags)
    for i in tags
      #i.dtag(@id)
      @c.dtag(i, @id)
    end
    self
  end
include(*tags)

private :create_self

[Source]

# File tk/lib/tk/canvastag.rb, line 359
  def include(*tags)
    for i in tags
      #i.addtag(@id)
      @c.addtag_withtag(@id, i)
    end
    self
  end


Class: TkcImage

Class | TkcImage
In: | tk/lib/tk/canvas.rb
Parent: | TkcItem

Constants

CItemTypeName = 'image'.freeze


Class: TkcItem

Class | TkcItem
In: | tk/lib/tk/canvas.rb
Parent: | TkObject

Methods

create delete destroy exist? id id2obj new remove type2class

Included Modules

TkcTagAccess

Constants

CItemTypeName | = | nil
CItemTypeToClass | = | {}
CItemID_TBL | = | TkCore::INTERP.create_table

Public Class methods

create(canvas, *args)

[Source]

# File tk/lib/tk/canvas.rb, line 648
  def self.create(canvas, *args)
    unless self::CItemTypeName
      fail RuntimeError, "#{self} is an abstract class"
    end
    args, fontkeys = _parse_create_args(args)
    idnum = tk_call_without_enc(canvas.path, 'create',
                                self::CItemTypeName, *args)
    canvas.itemconfigure(idnum, fontkeys) unless fontkeys.empty?
    idnum.to_i  # 'canvas item id' is an integer number
  end
id2obj(canvas, id)

[Source]

# File tk/lib/tk/canvas.rb, line 592
  def TkcItem.id2obj(canvas, id)
    cpath = canvas.path
    return id unless CItemID_TBL[cpath]
    CItemID_TBL[cpath][id]? CItemID_TBL[cpath][id]: id
  end
new(parent, *args)

[Source]

# File tk/lib/tk/canvas.rb, line 660
  def initialize(parent, *args)
    #unless parent.kind_of?(TkCanvas)
    #  fail ArgumentError, "expect TkCanvas for 1st argument"
    #end
    @parent = @c = parent
    @path = parent.path

    @id = create_self(*args) # an integer number as 'canvas item id'
    CItemID_TBL[@path] = {} unless CItemID_TBL[@path]
    CItemID_TBL[@path][@id] = self
  end
type2class(type)

[Source]

# File tk/lib/tk/canvas.rb, line 588
  def TkcItem.type2class(type)
    CItemTypeToClass[type]
  end

Public Instance methods

delete()

[Source]

# File tk/lib/tk/canvas.rb, line 688
  def delete
    @c.delete @id
    CItemID_TBL[@path].delete(@id) if CItemID_TBL[@path]
    self
  end
destroy()

Alias for delete

exist?()

[Source]

# File tk/lib/tk/canvas.rb, line 680
  def exist?
    if @c.find_withtag(@id)
      true
    else
      false
    end
  end
id()

[Source]

# File tk/lib/tk/canvas.rb, line 676
  def id
    @id
  end
remove()

Alias for delete


Class: TkcLine

Class | TkcLine
In: | tk/lib/tk/canvas.rb
Parent: | TkcItem

Constants

CItemTypeName = 'line'.freeze


Class: TkcOval

Class | TkcOval
In: | tk/lib/tk/canvas.rb
Parent: | TkcItem

Constants

CItemTypeName = 'oval'.freeze


Class: TkcPolygon

Class | TkcPolygon
In: | tk/lib/tk/canvas.rb
Parent: | TkcItem

Constants

CItemTypeName = 'polygon'.freeze


Class: TkcRectangle

Class | TkcRectangle
In: | tk/lib/tk/canvas.rb
Parent: | TkcItem

Constants

CItemTypeName = 'rectangle'.freeze


Class: TkcTag

Class | TkcTag
In: | tk/lib/tk/canvastag.rb
Parent: | TkObject

Methods

above all below closest delete destroy enclosed exist? id id2obj new overlapping remove set_to_above set_to_all set_to_below set_to_closest set_to_enclosed set_to_overlapping set_to_withtag withtag

Included Modules

TkcTagAccess

Constants

CTagID_TBL | = | TkCore::INTERP.create_table
Tk_CanvasTag_ID | = | ['ctag'.freeze, '00000'.taint].freeze

Public Class methods

id2obj(canvas, id)

[Source]

# File tk/lib/tk/canvastag.rb, line 206
  def TkcTag.id2obj(canvas, id)
    cpath = canvas.path
    return id unless CTagID_TBL[cpath]
    CTagID_TBL[cpath][id]? CTagID_TBL[cpath][id]: id
  end
new(parent, mode=nil, *args)

[Source]

# File tk/lib/tk/canvastag.rb, line 212
  def initialize(parent, mode=nil, *args)
    #unless parent.kind_of?(TkCanvas)
    #  fail ArgumentError, "expect TkCanvas for 1st argument"
    #end
    @c = parent
    @cpath = parent.path
    # @path = @id = Tk_CanvasTag_ID.join('')
    @path = @id = Tk_CanvasTag_ID.join(TkCore::INTERP._ip_id_)
    CTagID_TBL[@cpath] = {} unless CTagID_TBL[@cpath]
    CTagID_TBL[@cpath][@id] = self
    Tk_CanvasTag_ID[1].succ!
    if mode
      tk_call_without_enc(@c.path, "addtag", @id, mode, *args)
    end
  end

Public Instance methods

above(target)

Alias for set_to_above

all()

Alias for set_to_all

below(target)

Alias for set_to_below

closest(x, y, halo=None, start=None)

Alias for set_to_closest

delete()

[Source]

# File tk/lib/tk/canvastag.rb, line 239
  def delete
    @c.delete @id
    CTagID_TBL[@cpath].delete(@id) if CTagID_TBL[@cpath]
    self
  end
destroy()

Alias for delete

enclosed(x1, y1, x2, y2)

Alias for set_to_enclosed

exist?()

[Source]

# File tk/lib/tk/canvastag.rb, line 231
  def exist?
    if @c.find_withtag(@id)
      true
    else
      false
    end
  end
id()

[Source]

# File tk/lib/tk/canvastag.rb, line 227
  def id
    @id
  end
overlapping(x1, y1, x2, y2)

Alias for set_to_overlapping

remove()

Alias for delete

set_to_above(target)

[Source]

# File tk/lib/tk/canvastag.rb, line 247
  def set_to_above(target)
    @c.addtag_above(@id, target)
    self
  end
set_to_all()

[Source]

# File tk/lib/tk/canvastag.rb, line 253
  def set_to_all
    @c.addtag_all(@id)
    self
  end
set_to_below(target)

[Source]

# File tk/lib/tk/canvastag.rb, line 259
  def set_to_below(target)
    @c.addtag_below(@id, target)
    self
  end
set_to_closest(x, y, halo=None, start=None)

[Source]

# File tk/lib/tk/canvastag.rb, line 265
  def set_to_closest(x, y, halo=None, start=None)
    @c.addtag_closest(@id, x, y, halo, start)
    self
  end
set_to_enclosed(x1, y1, x2, y2)

[Source]

# File tk/lib/tk/canvastag.rb, line 271
  def set_to_enclosed(x1, y1, x2, y2)
    @c.addtag_enclosed(@id, x1, y1, x2, y2)
    self
  end
set_to_overlapping(x1, y1, x2, y2)

[Source]

# File tk/lib/tk/canvastag.rb, line 277
  def set_to_overlapping(x1, y1, x2, y2)
    @c.addtag_overlapping(@id, x1, y1, x2, y2)
    self
  end
set_to_withtag(target)

[Source]

# File tk/lib/tk/canvastag.rb, line 283
  def set_to_withtag(target)
    @c.addtag_withtag(@id, target)
    self
  end
withtag(target)

Alias for set_to_withtag


Module: TkcTagAccess

Module | TkcTagAccess
In: | tk/lib/tk/canvastag.rb

Methods

& -@ ^ addtag bbox bind bind_append bind_remove bindinfo cget configinfo configure coords current_configinfo dchars deltag dtag find focus gettags icursor index insert itemtype list lower move raise scale select_adjust select_from select_to |

Included Modules

TkComm TkTreatTagFont

Public Instance methods

&(tag)

Following operators support logical expressions of canvas tags (for Tk8.3+). If tag1.path is ‘t1’ and tag2.path is ‘t2’, then

     ltag = tag1 & tag2; ltag.path => "(t1)&&(t2)"
     ltag = tag1 | tag2; ltag.path => "(t1)||(t2)"
     ltag = tag1 ^ tag2; ltag.path => "(t1)^(t2)"
     ltag = - tag1;      ltag.path => "!(t1)"

[Source]

# File tk/lib/tk/canvastag.rb, line 169
  def & (tag)
    if tag.kind_of? TkObject
      TkcTagString.new(@c, '(' + @id + ')&&(' + tag.path + ')')
    else
      TkcTagString.new(@c, '(' + @id + ')&&(' + tag.to_s + ')')
    end
  end
-@()

[Source]

# File tk/lib/tk/canvastag.rb, line 193
  def -@
    TkcTagString.new(@c, '!(' + @id + ')')
  end
^(tag)

[Source]

# File tk/lib/tk/canvastag.rb, line 185
  def ^ (tag)
    if tag.kind_of? TkObject
      TkcTagString.new(@c, '(' + @id + ')^(' + tag.path + ')')
    else
      TkcTagString.new(@c, '(' + @id + ')^(' + tag.to_s + ')')
    end
  end
addtag(tag)

[Source]

# File tk/lib/tk/canvastag.rb, line 15
  def addtag(tag)
    @c.addtag(tag, 'withtag', @id)
    self
  end
bbox()

[Source]

# File tk/lib/tk/canvastag.rb, line 20
  def bbox
    @c.bbox(@id)
  end
bind(seq, *args)

def bind(seq, cmd=Proc.new, *args)

  @c.itembind(@id, seq, cmd, *args)
  self

end

[Source]

# File tk/lib/tk/canvastag.rb, line 28
  def bind(seq, *args)
    # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    @c.itembind(@id, seq, cmd, *args)
    self
  end
bind_append(seq, *args)

def bind_append(seq, cmd=Proc.new, *args)

  @c.itembind_append(@id, seq, cmd, *args)
  self

end

[Source]

# File tk/lib/tk/canvastag.rb, line 43
  def bind_append(seq, *args)
    # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
    if TkComm._callback_entry?(args[0]) || !block_given?
      cmd = args.shift
    else
      cmd = Proc.new
    end
    @c.itembind_append(@id, seq, cmd, *args)
    self
  end
bind_remove(seq)

[Source]

# File tk/lib/tk/canvastag.rb, line 54
  def bind_remove(seq)
    @c.itembind_remove(@id, seq)
    self
  end
bindinfo(seq=nil)

[Source]

# File tk/lib/tk/canvastag.rb, line 59
  def bindinfo(seq=nil)
    @c.itembindinfo(@id, seq)
  end
cget(option)

[Source]

# File tk/lib/tk/canvastag.rb, line 63
  def cget(option)
    @c.itemcget(@id, option)
  end
configinfo(key=nil)

def configure(keys)

  @c.itemconfigure @id, keys

end

[Source]

# File tk/lib/tk/canvastag.rb, line 75
  def configinfo(key=nil)
    @c.itemconfiginfo(@id, key)
  end
configure(key, value=None)

[Source]

# File tk/lib/tk/canvastag.rb, line 67
  def configure(key, value=None)
    @c.itemconfigure(@id, key, value)
    self
  end
coords(*args)

[Source]

# File tk/lib/tk/canvastag.rb, line 83
  def coords(*args)
    @c.coords(@id, *args)
  end
current_configinfo(key=nil)

[Source]

# File tk/lib/tk/canvastag.rb, line 79
  def current_configinfo(key=nil)
    @c.current_itemconfiginfo(@id, key)
  end
dchars(first, last=None)

[Source]

# File tk/lib/tk/canvastag.rb, line 87
  def dchars(first, last=None)
    @c.dchars(@id, first, last)
    self
  end
deltag(tag_to_del=None)

Alias for dtag

dtag(tag_to_del=None)

[Source]

# File tk/lib/tk/canvastag.rb, line 92
  def dtag(tag_to_del=None)
    @c.dtag(@id, tag_to_del)
    self
  end
find()

[Source]

# File tk/lib/tk/canvastag.rb, line 98
  def find
    @c.find('withtag', @id)
  end
focus()

[Source]

# File tk/lib/tk/canvastag.rb, line 103
  def focus
    @c.itemfocus(@id)
  end
gettags()

[Source]

# File tk/lib/tk/canvastag.rb, line 107
  def gettags
    @c.gettags(@id)
  end
icursor(index)

[Source]

# File tk/lib/tk/canvastag.rb, line 111
  def icursor(index)
    @c.icursor(@id, index)
    self
  end
index(idx)

[Source]

# File tk/lib/tk/canvastag.rb, line 116
  def index(idx)
    @c.index(@id, idx)
  end
insert(beforethis, string)

[Source]

# File tk/lib/tk/canvastag.rb, line 120
  def insert(beforethis, string)
    @c.insert(@id, beforethis, string)
    self
  end
itemtype()

[Source]

# File tk/lib/tk/canvastag.rb, line 158
  def itemtype
    @c.itemtype(@id)
  end
list()

Alias for find

lower(belowthis=None)

[Source]

# File tk/lib/tk/canvastag.rb, line 125
  def lower(belowthis=None)
    @c.lower(@id, belowthis)
    self
  end
move(xamount, yamount)

[Source]

# File tk/lib/tk/canvastag.rb, line 130
  def move(xamount, yamount)
    @c.move(@id, xamount, yamount)
    self
  end
raise(abovethis=None)

[Source]

# File tk/lib/tk/canvastag.rb, line 135
  def raise(abovethis=None)
    @c.raise(@id, abovethis)
    self
  end
scale(xorigin, yorigin, xscale, yscale)

[Source]

# File tk/lib/tk/canvastag.rb, line 140
  def scale(xorigin, yorigin, xscale, yscale)
    @c.scale(@id, xorigin, yorigin, xscale, yscale)
    self
  end
select_adjust(index)

[Source]

# File tk/lib/tk/canvastag.rb, line 145
  def select_adjust(index)
    @c.select('adjust', @id, index)
    self
  end
select_from(index)

[Source]

# File tk/lib/tk/canvastag.rb, line 149
  def select_from(index)
    @c.select('from', @id, index)
    self
  end
select_to(index)

[Source]

# File tk/lib/tk/canvastag.rb, line 153
  def select_to(index)
    @c.select('to', @id, index)
    self
  end
|(tag)

[Source]

# File tk/lib/tk/canvastag.rb, line 177
  def | (tag)
    if tag.kind_of? TkObject
      TkcTagString.new(@c, '(' + @id + ')||(' + tag.path + ')')
    else
      TkcTagString.new(@c, '(' + @id + ')||(' + tag.to_s + ')')
    end
  end


Class: TkcTagAll

Class | TkcTagAll
In: | tk/lib/tk/canvastag.rb
Parent: | TkcTag

Methods

new

Public Class methods

new(parent)

[Source]

# File tk/lib/tk/canvastag.rb, line 316
  def initialize(parent)
    #unless parent.kind_of?(TkCanvas)
    #  fail ArgumentError, "expect TkCanvas for 1st argument"
    #end
    @c = parent
    @cpath = parent.path
    @path = @id = 'all'
    CTagID_TBL[@cpath] = {} unless CTagID_TBL[@cpath]
    CTagID_TBL[@cpath][@id] = self
  end


Class: TkcTagCurrent

Class | TkcTagCurrent
In: | tk/lib/tk/canvastag.rb
Parent: | TkcTag

Methods

new

Public Class methods

new(parent)

[Source]

# File tk/lib/tk/canvastag.rb, line 329
  def initialize(parent)
    #unless parent.kind_of?(TkCanvas)
    #  fail ArgumentError, "expect TkCanvas for 1st argument"
    #end
    @c = parent
    @cpath = parent.path
    @path = @id = 'current'
    CTagID_TBL[@cpath] = {} unless CTagID_TBL[@cpath]
    CTagID_TBL[@cpath][@id] = self
  end


Class: TkcTagString

Class | TkcTagString
In: | tk/lib/tk/canvastag.rb
Parent: | TkcTag

Methods

new new

Public Class methods

new(parent, name, *args)

[Source]

# File tk/lib/tk/canvastag.rb, line 291
  def self.new(parent, name, *args)
    if CTagID_TBL[parent.path] && CTagID_TBL[parent.path][name]
      return CTagID_TBL[parent.path][name]
    else
      super(parent, name, *args)
    end
  end
new(parent, name, mode=nil, *args)

[Source]

# File tk/lib/tk/canvastag.rb, line 299
  def initialize(parent, name, mode=nil, *args)
    #unless parent.kind_of?(TkCanvas)
    #  fail ArgumentError, "expect TkCanvas for 1st argument"
    #end
    @c = parent
    @cpath = parent.path
    @path = @id = name
    CTagID_TBL[@cpath] = {} unless CTagID_TBL[@cpath]
    CTagID_TBL[@cpath][@id] = self
    if mode
      tk_call_without_enc(@c.path, "addtag", @id, mode, *args)
    end
  end


Class: TkcText

Class | TkcText
In: | tk/lib/tk/canvas.rb
Parent: | TkcItem

Methods

create

Constants

CItemTypeName = 'text'.freeze

Public Class methods

create(canvas, *args)

[Source]

# File tk/lib/tk/canvas.rb, line 735
  def self.create(canvas, *args)
    if args[-1].kind_of?(Hash)
      keys = _symbolkey2str(args.pop)
      txt = keys['text']
      keys['text'] = _get_eval_enc_str(txt) if txt
      args.push(keys)
    end
    super(canvas, *args)
  end


Class: TkcWindow

Class | TkcWindow
In: | tk/lib/tk/canvas.rb
Parent: | TkcItem

Methods

create

Constants

CItemTypeName = 'window'.freeze

Public Class methods

create(canvas, *args)

[Source]

# File tk/lib/tk/canvas.rb, line 749
  def self.create(canvas, *args)
    if args[-1].kind_of?(Hash)
      keys = _symbolkey2str(args.pop)
      win = keys['window']
      # keys['window'] = win.epath if win.kind_of?(TkWindow)
      keys['window'] = _epath(win) if win
      args.push(keys)
    end
    super(canvas, *args)
  end


File: multi-tk.rb

multi-tk.rb

Path: | tk/lib/multi-tk.rb
Last Update: | Sat Oct 15 23:44:07 AUS Eastern Standard Time 2005

multi-tk.rb - supports multi Tk interpreters

        by Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>

Required files

tcltklib tkutil thread tk


File: remote-tk.rb

remote-tk.rb

Path: | tk/lib/remote-tk.rb
Last Update: | Sat Oct 15 23:44:07 AUS Eastern Standard Time 2005

remote-tk.rb - supports to control remote Tk interpreters

        by Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>

Required files

multi-tk


File: tk.rb

tk.rb

Path: | tk/lib/tk.rb
Last Update: | Mon Oct 24 20:15:34 AUS Eastern Standard Time 2005

tk.rb - Tk interface module using tcltklib

        $Date: 2005/10/24 02:07:04 $
        by Yukihiro Matsumoto <matz@netlab.jp>

Required files

tcltklib tkutil tk/autoload tkextlib/setup.rb


File: after.rb

after.rb

Path: | tk/lib/tk/after.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/after.rb : methods for Tcl/Tk after command

$Id: after.rb,v 1.1.2.1 2004/05/01 16:09:49 nagai Exp $

Required files

tk/timer


File: autoload.rb

autoload.rb

Path: | tk/lib/tk/autoload.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

autoload

Methods

TkGrid TkPack TkPlace

Public Instance methods

TkGrid(*args)

[Source]

# File tk/lib/tk/autoload.rb, line 8
def TkGrid(*args); TkGrid.configure(*args); end
TkPack(*args)

[Source]

# File tk/lib/tk/autoload.rb, line 11
def TkPack(*args); TkPack.configure(*args); end
TkPlace(*args)

[Source]

# File tk/lib/tk/autoload.rb, line 14
def TkPlace(*args); TkPlace.configure(*args); end


File: bgerror.rb

bgerror.rb

Path: | tk/lib/tk/bgerror.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tkbgerror — bgerror ( tkerror ) module

                   1998/07/16 by Hidetoshi Nagai <nagai@ai.kyutech.ac.jp>

Required files

tk


File: bindtag.rb

bindtag.rb

Path: | tk/lib/tk/bindtag.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/bind.rb : control event binding

Required files

tk


File: button.rb

button.rb

Path: | tk/lib/tk/button.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/button.rb : treat button widget

Required files

tk tk/label


File: canvas.rb

canvas.rb

Path: | tk/lib/tk/canvas.rb
Last Update: | Mon Oct 24 20:15:34 AUS Eastern Standard Time 2005

tk/canvas.rb - Tk canvas classes

        $Date: 2005/10/24 00:07:00 $
        by Yukihiro Matsumoto <matz@caelum.co.jp>

Required files

tk tk/canvastag tk/itemconfig tk/scrollable


File: canvastag.rb

canvastag.rb

Path: | tk/lib/tk/canvastag.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/canvastag.rb - methods for treating canvas tags

Required files

tk tk/tagfont tk/canvas

Constants

TkcNamedTag = TkcTagString


File: checkbutton.rb

checkbutton.rb

Path: | tk/lib/tk/checkbutton.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/checkbutton.rb : treat checkbutton widget

Required files

tk tk/radiobutton

Constants

TkCheckbutton = TkCheckButton


File: clipboard.rb

clipboard.rb

Path: | tk/lib/tk/clipboard.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/clipboard.rb : methods to treat clipboard

Required files

tk


File: clock.rb

clock.rb

Path: | tk/lib/tk/clock.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/clock.rb : methods for clock command

Required files

tk


File: composite.rb

composite.rb

Path: | tk/lib/tk/composite.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/composite.rb :

Required files

tk


File: console.rb

console.rb

Path: | tk/lib/tk/console.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/console.rb : control the console on system without a real console

Required files

tk


File: dialog.rb

dialog.rb

Path: | tk/lib/tk/dialog.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/dialog.rb : create dialog boxes

Required files

tk tk/variable.rb

Constants

TkDialog2 | = | TkDialogObj
TkWarning2 | = | TkWarningObj


File: encodedstr.rb

encodedstr.rb

Path: | tk/lib/tk/encodedstr.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/encodedstr.rb : Tk::EncodedString class

Required files

tk


File: entry.rb

entry.rb

Path: | tk/lib/tk/entry.rb
Last Update: | Mon Oct 24 20:15:34 AUS Eastern Standard Time 2005

tk/entry.rb - Tk entry classes

        $Date: 2005/10/22 22:16:24 $
        by Yukihiro Matsumoto <matz@caelum.co.jp>

Required files

tk tk/label tk/scrollable tk/validation


File: event.rb

event.rb

Path: | tk/lib/tk/event.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/event.rb - module for event

Required files

tkutil tk

Constants

ALIAS_TBL = { :button => :num, :delta => :wheel_delta, :root => :rootwin_id, :rootx => :x_root, :root_x => :x_root, :rooty => :y_root, :root_y => :y_root, :sendevent => :send_event, :window => :widget


File: font.rb

font.rb

Path: | tk/lib/tk/font.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/font.rb - the class to treat fonts on Ruby/Tk

                             by  Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk


File: frame.rb

frame.rb

Path: | tk/lib/tk/frame.rb
Last Update: | Mon Oct 24 20:15:34 AUS Eastern Standard Time 2005

tk/frame.rb : treat frame widget

Required files

tk


File: grid.rb

grid.rb

Path: | tk/lib/tk/grid.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/grid.rb : control grid geometry manager

Required files

tk


File: image.rb

image.rb

Path: | tk/lib/tk/image.rb
Last Update: | Mon Oct 24 20:15:34 AUS Eastern Standard Time 2005

tk/image.rb : treat Tk image objects

Required files

tk


File: itemconfig.rb

itemconfig.rb

Path: | tk/lib/tk/itemconfig.rb
Last Update: | Mon Oct 24 20:15:34 AUS Eastern Standard Time 2005

tk/itemconfig.rb : control item/tag configuration of widget

Required files

tk tkutil tk/itemfont.rb


File: itemfont.rb

itemfont.rb

Path: | tk/lib/tk/itemfont.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/itemfont.rb : control font of widget items

Required files

tk


File: kinput.rb

kinput.rb

Path: | tk/lib/tk/kinput.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/kinput.rb : control kinput

Required files

tk


File: label.rb

label.rb

Path: | tk/lib/tk/label.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/label.rb : treat label widget

Required files

tk


File: labelframe.rb

labelframe.rb

Path: | tk/lib/tk/labelframe.rb
Last Update: | Mon Oct 24 20:15:34 AUS Eastern Standard Time 2005

tk/labelframe.rb : treat labelframe widget

Required files

tk tk/frame

Constants

TkLabelframe = TkLabelFrame


File: listbox.rb

listbox.rb

Path: | tk/lib/tk/listbox.rb
Last Update: | Mon Oct 24 20:15:34 AUS Eastern Standard Time 2005

tk/listbox.rb : treat listbox widget

Required files

tk tk/itemconfig tk/scrollable tk/txtwin_abst


File: macpkg.rb

macpkg.rb

Path: | tk/lib/tk/macpkg.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/macpkg.rb : methods for Tcl/Tk packages for Macintosh

                  2000/11/22 by Hidetoshi Nagai <nagai@ai.kyutech.ac.jp>

  ATTENTION !!
      This is NOT TESTED. Because I have no test-environment.

Required files

tk


File: menu.rb

menu.rb

Path: | tk/lib/tk/menu.rb
Last Update: | Mon Oct 24 20:15:34 AUS Eastern Standard Time 2005

tk/menu.rb : treat menu and menubutton

Required files

tk tk/itemconfig tk/menuspec

Constants

TkMenuButton | = | TkMenubutton
TkOptionMenuButton | = | TkOptionMenubutton


File: menubar.rb

menubar.rb

Path: | tk/lib/tk/menubar.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/menubar.rb

Original version:

  Copyright (C) 1998 maeda shugo. All rights reserved.
  This file can be distributed under the terms of the Ruby.

Required files

tk tk/frame tk/composite tk/menuspec


File: menuspec.rb

menuspec.rb

Path: | tk/lib/tk/menuspec.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/menuspec.rb

                             Hidethoshi NAGAI (nagai@ai.kyutech.ac.jp)

based on tkmenubar.rb :

  Copyright (C) 1998 maeda shugo. All rights reserved.
  This file can be distributed under the terms of the Ruby.

The format of the menu_spec is:

  [ menu_info, menu_info, ... ]

And the format of the menu_info is:

  [
    [text, underline, configs], # menu button/entry (*1)
    [label, command, underline, accelerator, configs],   # command entry
    [label, TkVar_obj, underline, accelerator, configs], # checkbutton entry
    [label, [TkVar_obj, value],
                       underline, accelerator, configs], # radiobutton entry
    [label, [[...menu_info...], [...menu_info...], ...],
                       underline, accelerator, configs], # cascade entry (*2)
    '---', # separator
    ...
  ]

underline, accelerator, and configs are optional pearameters. Hashes are OK instead of Arrays. Then the entry type (‘command’, ‘checkbutton’, ‘radiobutton’ or ‘cascade’) is given by ‘type’ key (e.g. :type=>’cascade’). When type is ‘cascade’, an array of menu_info is acceptable for ‘menu’ key (then, create sub-menu).

NOTE: (*1)

  If you want to make special menus (*.help for UNIX, *.system for Win,
  and *.apple for Mac), append 'menu_name'=>name (name is 'help' for UNIX,
  'system' for Win, and 'apple' for Mac) option to the configs hash of
  menu button/entry information.

NOTE: (*2)

  If you want to configure a cascade menu, add :menu_config=>{...configs..}
  to the configs of the cascade entry.


File: message.rb

message.rb

Path: | tk/lib/tk/message.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/message.rb : treat message widget

Required files

tk tk/label


File: mngfocus.rb

mngfocus.rb

Path: | tk/lib/tk/mngfocus.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/mngfocus.rb : methods for Tcl/Tk standard library ‘focus.tcl‘

                        by Hidetoshi Nagai <nagai@ai.kyutech.ac.jp>

Required files

tk


File: msgcat.rb

msgcat.rb

Path: | tk/lib/tk/msgcat.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/msgcat.rb : methods for Tcl message catalog

                  by Hidetoshi Nagai <nagai@ai.kyutech.ac.jp>

Required files

tk

Constants

TkMsgCat = TkMsgCatalog


File: namespace.rb

namespace.rb

Path: | tk/lib/tk/namespace.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/namespace.rb : methods to manipulate Tcl/Tk namespace

                        by Hidetoshi Nagai <nagai@ai.kyutech.ac.jp>

Required files

tk


File: optiondb.rb

optiondb.rb

Path: | tk/lib/tk/optiondb.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/optiondb.rb : treat option database

Required files

tk

Constants

TkOption | = | TkOptionDB
TkResourceDB | = | TkOptionDB


File: optionobj.rb

optionobj.rb

Path: | tk/lib/tk/optionobj.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/optionobj.rb : control options for a group of widgets

 NOTE: If you want to use key-only option (no value),
       use Tk::None for the value of the key-only option.

       e.g. hash_kv({'aaa'=>1, 'bbb'=>Tk::None, 'ccc'=>3})
                => ["-aaa", 1, "-bbb", "-ccc", 3]

Required files

tk


File: pack.rb

pack.rb

Path: | tk/lib/tk/pack.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/pack.rb : control pack geometry manager

Required files

tk


File: package.rb

package.rb

Path: | tk/lib/tk/package.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/package.rb : package command

Required files

tk


File: palette.rb

palette.rb

Path: | tk/lib/tk/palette.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/palette.rb : methods for Tcl/Tk standard library ‘palette.tcl‘

                  1998/06/21 by Hidetoshi Nagai <nagai@ai.kyutech.ac.jp>

Required files

tk


File: panedwindow.rb

panedwindow.rb

Path: | tk/lib/tk/panedwindow.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/panedwindow.rb : treat panedwindow

Required files

tk

Constants

TkPanedwindow = TkPanedWindow


File: place.rb

place.rb

Path: | tk/lib/tk/place.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/place.rb : control place geometry manager

Required files

tk


File: radiobutton.rb

radiobutton.rb

Path: | tk/lib/tk/radiobutton.rb
Last Update: | Mon Oct 24 20:15:34 AUS Eastern Standard Time 2005

tk/radiobutton.rb : treat radiobutton widget

Required files

tk tk/button

Constants

TkRadiobutton = TkRadioButton


File: root.rb

root.rb

Path: | tk/lib/tk/root.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/root.rb : treat root widget

Required files

tk tk/wm tk/menuspec


File: scale.rb

scale.rb

Path: | tk/lib/tk/scale.rb
Last Update: | Mon Oct 24 20:15:34 AUS Eastern Standard Time 2005

tk/scale.rb : treat scale widget

Required files

tk


File: scrollable.rb

scrollable.rb

Path: | tk/lib/tk/scrollable.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/scrollable.rb : module for scrollable widget

Required files

tk


File: scrollbar.rb

scrollbar.rb

Path: | tk/lib/tk/scrollbar.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/scrollbar.rb : treat scrollbar widget

Required files

tk


File: scrollbox.rb

scrollbox.rb

Path: | tk/lib/tk/scrollbox.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/scrollbox.rb - Tk Listbox with Scrollbar

                  as an example of Composite Widget
        $Date: 2004/10/11 04:51:07 $
        by Yukihiro Matsumoto <matz@netlab.co.jp>

Required files

tk tk/listbox


File: selection.rb

selection.rb

Path: | tk/lib/tk/selection.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/selection.rb : control selection

Required files

tk


File: spinbox.rb

spinbox.rb

Path: | tk/lib/tk/spinbox.rb
Last Update: | Mon Oct 24 20:15:34 AUS Eastern Standard Time 2005

tk/spinbox.rb - Tk spinbox classes

        $Date: 2005/10/22 22:16:24 $
        by Yukihiro Matsumoto <matz@caelum.co.jp>

Required files

tk tk/entry


File: tagfont.rb

tagfont.rb

Path: | tk/lib/tk/tagfont.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/tagfont.rb : control font of tags

Required files

tk


File: text.rb

text.rb

Path: | tk/lib/tk/text.rb
Last Update: | Mon Oct 24 20:15:34 AUS Eastern Standard Time 2005

tk/text.rb - Tk text classes

        $Date: 2005/10/22 22:16:24 $
        by Yukihiro Matsumoto <matz@caelum.co.jp>

Required files

tk tk/itemfont tk/itemconfig tk/scrollable tk/txtwin_abst


File: textimage.rb

textimage.rb

Path: | tk/lib/tk/textimage.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/textimage.rb - treat Tk text image object

Required files

tk tk/text


File: textmark.rb

textmark.rb

Path: | tk/lib/tk/textmark.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/textmark.rb - methods for treating text marks

Required files

tk tk/text


File: texttag.rb

texttag.rb

Path: | tk/lib/tk/texttag.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/texttag.rb - methods for treating text tags

Required files

tk tk/text tk/tagfont


File: textwindow.rb

textwindow.rb

Path: | tk/lib/tk/textwindow.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/textwindow.rb - treat Tk text window object

Required files

tk tk/text


File: timer.rb

timer.rb

Path: | tk/lib/tk/timer.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/timer.rb : methods for Tcl/Tk after command

$Id: timer.rb,v 1.1.2.15 2005/05/08 14:20:53 nagai Exp $

Required files

tk

Constants

TkAfter = TkTimer


File: toplevel.rb

toplevel.rb

Path: | tk/lib/tk/toplevel.rb
Last Update: | Mon Oct 24 20:15:34 AUS Eastern Standard Time 2005

tk/toplevel.rb : treat toplevel widget

Required files

tk tk/wm tk/menuspec


File: txtwin_abst.rb

txtwin_abst.rb

Path: | tk/lib/tk/txtwin_abst.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/txtwin_abst.rb : TkTextWin abstruct class

Required files

tk


File: validation.rb

validation.rb

Path: | tk/lib/tk/validation.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/validation.rb - validation support module for entry, spinbox, and so on

Required files

tk


File: variable.rb

variable.rb

Path: | tk/lib/tk/variable.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/variable.rb : treat Tk variable object

Required files

tk


File: virtevent.rb

virtevent.rb

Path: | tk/lib/tk/virtevent.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/virtevent.rb : treats virtual events

                  1998/07/16 by Hidetoshi Nagai <nagai@ai.kyutech.ac.jp>

Required files

tk


File: winfo.rb

winfo.rb

Path: | tk/lib/tk/winfo.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/winfo.rb : methods for winfo command

Required files

tk


File: winpkg.rb

winpkg.rb

Path: | tk/lib/tk/winpkg.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/winpkg.rb : methods for Tcl/Tk packages for Microsoft Windows

                  2000/11/22 by Hidetoshi Nagai <nagai@ai.kyutech.ac.jp>

  ATTENTION !!
      This is NOT TESTED. Because I have no test-environment.

Required files

tk


File: wm.rb

wm.rb

Path: | tk/lib/tk/wm.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/wm.rb : methods for wm command

Required files

tk


File: xim.rb

xim.rb

Path: | tk/lib/tk/xim.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tk/xim.rb : control imput_method

Required files

tk


File: tkafter.rb

tkafter.rb

Path: | tk/lib/tkafter.rb
Last Update: | Sat Oct 15 23:44:07 AUS Eastern Standard Time 2005

tkafter.rb - load tk/after.rb

Required files

tk/timer


File: tkbgerror.rb

tkbgerror.rb

Path: | tk/lib/tkbgerror.rb
Last Update: | Sat Oct 15 23:44:07 AUS Eastern Standard Time 2005

tkbgerror.rb - load tk/bgerror.rb

Required files

tk/bgerror


File: tkcanvas.rb

tkcanvas.rb

Path: | tk/lib/tkcanvas.rb
Last Update: | Sat Oct 15 23:44:07 AUS Eastern Standard Time 2005

tkcanvas.rb - load tk/canvas.rb

Required files

tk/canvas


File: tkclass.rb

tkclass.rb

Path: | tk/lib/tkclass.rb
Last Update: | Sat Oct 15 23:44:07 AUS Eastern Standard Time 2005

tkclass.rb - Tk classes

        Date: 2000/11/27 09:23:36
        by Yukihiro Matsumoto <matz@caelum.co.jp>

        $Id: tkclass.rb,v 1.6.2.1 2004/10/11 04:51:06 nagai Exp $

Required files

tk

Methods

Mainloop

Constants

TopLevel | = | TkToplevel
Frame | = | TkFrame
Label | = | TkLabel
Button | = | TkButton
Radiobutton | = | TkRadioButton
Checkbutton | = | TkCheckButton
Message | = | TkMessage
Entry | = | TkEntry
Spinbox | = | TkSpinbox
Text | = | TkText
Scale | = | TkScale
Scrollbar | = | TkScrollbar
Listbox | = | TkListbox
Menu | = | TkMenu
Menubutton | = | TkMenubutton
Canvas | = | TkCanvas
Arc | = | TkcArc
Bitmap | = | TkcBitmap
Line | = | TkcLine
Oval | = | TkcOval
Polygon | = | TkcPolygon
Rectangle | = | TkcRectangle
TextItem | = | TkcText
WindowItem | = | TkcWindow
BitmapImage | = | TkBitmapImage
PhotoImage | = | TkPhotoImage
Selection | = | TkSelection
Winfo | = | TkWinfo
Pack | = | TkPack
Grid | = | TkGrid
Place | = | TkPlace
Variable | = | TkVariable
Font | = | TkFont
VirtualEvent | = | TkVirtualEvent

Public Instance methods

Mainloop()

[Source]

# File tk/lib/tkclass.rb, line 45
def Mainloop
  Tk.mainloop
end


File: tkconsole.rb

tkconsole.rb

Path: | tk/lib/tkconsole.rb
Last Update: | Sat Oct 15 23:44:07 AUS Eastern Standard Time 2005

tkconsole.rb - load tk/console.rb

Required files

tk/console


File: tkdialog.rb

tkdialog.rb

Path: | tk/lib/tkdialog.rb
Last Update: | Sat Oct 15 23:44:07 AUS Eastern Standard Time 2005

tkdialog.rb - load tk/dialog.rb

Required files

tk/dialog


File: tkentry.rb

tkentry.rb

Path: | tk/lib/tkentry.rb
Last Update: | Sat Oct 15 23:44:07 AUS Eastern Standard Time 2005

tkentry.rb - load tk/entry.rb

Required files

tk/entry


File: ICONS.rb

ICONS.rb

Path: | tk/lib/tkextlib/ICONS.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

ICONS support

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tkextlib/setup.rb tkextlib/ICONS/setup.rb tkextlib/ICONS/icons


File: icons.rb

icons.rb

Path: | tk/lib/tkextlib/ICONS/icons.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tkextlib/ICONS/icons.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/setup.rb tkextlib/ICONS/setup.rb icons icons


File: setup.rb

setup.rb

Path: | tk/lib/tkextlib/ICONS/setup.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

setup.rb — setup script before calling TkPackage.require()

  If you need some setup operations (for example, add a library path
  to the library search path) before using Tcl/Tk library packages
  wrapped by Ruby scripts in this directory, please write the setup
  operations in this file.


File: blt.rb

blt.rb

Path: | tk/lib/tkextlib/blt.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

BLT support

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/variable tkextlib/setup.rb tkextlib/blt/setup.rb BLT BLT


File: barchart.rb

barchart.rb

Path: | tk/lib/tkextlib/blt/barchart.rb
Last Update: | Mon Oct 24 20:15:34 AUS Eastern Standard Time 2005

tkextlib/blt/barchart.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/blt.rb tkextlib/blt/component.rb


File: bitmap.rb

bitmap.rb

Path: | tk/lib/tkextlib/blt/bitmap.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/blt/bitmap.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/blt.rb


File: busy.rb

busy.rb

Path: | tk/lib/tkextlib/blt/busy.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/blt/busy.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/itemconfig.rb tkextlib/blt.rb


File: component.rb

component.rb

Path: | tk/lib/tkextlib/blt/component.rb
Last Update: | Mon Oct 24 20:15:34 AUS Eastern Standard Time 2005

tkextlib/blt/component.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/blt.rb


File: container.rb

container.rb

Path: | tk/lib/tkextlib/blt/container.rb
Last Update: | Mon Oct 24 20:15:34 AUS Eastern Standard Time 2005

tkextlib/blt/container.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/blt.rb


File: cutbuffer.rb

cutbuffer.rb

Path: | tk/lib/tkextlib/blt/cutbuffer.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/blt/cutbuffer.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/blt.rb


File: dragdrop.rb

dragdrop.rb

Path: | tk/lib/tkextlib/blt/dragdrop.rb
Last Update: | Mon Oct 24 20:15:34 AUS Eastern Standard Time 2005

tkextlib/blt/dragdrop.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/itemconfig tkextlib/blt.rb


File: eps.rb

eps.rb

Path: | tk/lib/tkextlib/blt/eps.rb
Last Update: | Mon Oct 24 20:15:35 AUS Eastern Standard Time 2005

tkextlib/blt/eps.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/canvas tkextlib/blt.rb


File: graph.rb

graph.rb

Path: | tk/lib/tkextlib/blt/graph.rb
Last Update: | Mon Oct 24 20:15:35 AUS Eastern Standard Time 2005

tkextlib/blt/graph.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/blt.rb tkextlib/blt/component.rb


File: htext.rb

htext.rb

Path: | tk/lib/tkextlib/blt/htext.rb
Last Update: | Mon Oct 24 20:15:35 AUS Eastern Standard Time 2005

tkextlib/blt/htext.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/itemconfig.rb tkextlib/blt.rb


File: setup.rb

setup.rb

Path: | tk/lib/tkextlib/blt/setup.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

setup.rb — setup script before calling TkPackage.require()

  If you need some setup operations (for example, add a library path
  to the library search path) before using Tcl/Tk library packages
  wrapped by Ruby scripts in this directory, please write the setup
  operations in this file.


File: spline.rb

spline.rb

Path: | tk/lib/tkextlib/blt/spline.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/blt/spline.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/blt.rb


File: stripchart.rb

stripchart.rb

Path: | tk/lib/tkextlib/blt/stripchart.rb
Last Update: | Mon Oct 24 20:15:35 AUS Eastern Standard Time 2005

tkextlib/blt/stripchart.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/blt.rb tkextlib/blt/component.rb


File: table.rb

table.rb

Path: | tk/lib/tkextlib/blt/table.rb
Last Update: | Mon Oct 24 20:15:35 AUS Eastern Standard Time 2005

tkextlib/blt/table.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/itemconfig.rb tkextlib/blt.rb


File: tabnotebook.rb

tabnotebook.rb

Path: | tk/lib/tkextlib/blt/tabnotebook.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/blt/tabnotebook.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/blt.rb tkextlib/blt/tabset.rb


File: tabset.rb

tabset.rb

Path: | tk/lib/tkextlib/blt/tabset.rb
Last Update: | Mon Oct 24 20:15:35 AUS Eastern Standard Time 2005

tkextlib/blt/tabset.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/blt.rb


File: ted.rb

ted.rb

Path: | tk/lib/tkextlib/blt/ted.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/blt/ted.rb

  *** This is alpha version, because there is no document on BLT. ***

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/blt.rb


File: tile.rb

tile.rb

Path: | tk/lib/tkextlib/blt/tile.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/blt/tile.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/blt.rb


File: button.rb

button.rb

Path: | tk/lib/tkextlib/blt/tile/button.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/blt/tile/button.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/button tkextlib/blt/tile.rb


File: checkbutton.rb

checkbutton.rb

Path: | tk/lib/tkextlib/blt/tile/checkbutton.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/blt/tile/checkbutton.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/checkbutton tkextlib/blt/tile.rb


File: frame.rb

frame.rb

Path: | tk/lib/tkextlib/blt/tile/frame.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/blt/tile/frame.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/frame tkextlib/blt/tile.rb


File: label.rb

label.rb

Path: | tk/lib/tkextlib/blt/tile/label.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/blt/tile/label.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/label tkextlib/blt/tile.rb


File: radiobutton.rb

radiobutton.rb

Path: | tk/lib/tkextlib/blt/tile/radiobutton.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/blt/tile/radiobutton.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/radiobutton tkextlib/blt/tile.rb


File: scrollbar.rb

scrollbar.rb

Path: | tk/lib/tkextlib/blt/tile/scrollbar.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/blt/tile/scrollbar.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/scrollbar tkextlib/blt/tile.rb


File: toplevel.rb

toplevel.rb

Path: | tk/lib/tkextlib/blt/tile/toplevel.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/blt/tile/toplevel.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/toplevel tkextlib/blt/tile.rb


File: tree.rb

tree.rb

Path: | tk/lib/tkextlib/blt/tree.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/blt/tree.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/blt.rb


File: treeview.rb

treeview.rb

Path: | tk/lib/tkextlib/blt/treeview.rb
Last Update: | Mon Oct 24 20:15:35 AUS Eastern Standard Time 2005

tkextlib/blt/treeview.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/blt.rb tk/validation.rb


File: unix_dnd.rb

unix_dnd.rb

Path: | tk/lib/tkextlib/blt/unix_dnd.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/blt/unix_dnd.rb

  *** This is alpha version, because there is no document on BLT. ***

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/blt.rb


File: vector.rb

vector.rb

Path: | tk/lib/tkextlib/blt/vector.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/blt/vector.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/blt.rb


File: watch.rb

watch.rb

Path: | tk/lib/tkextlib/blt/watch.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/blt/watch.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/blt.rb


File: win_printer.rb

win_printer.rb

Path: | tk/lib/tkextlib/blt/win_printer.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/blt/win_printer.rb

    *** Windows only ***

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/blt.rb


File: winop.rb

winop.rb

Path: | tk/lib/tkextlib/blt/winop.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/blt/winop.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/blt.rb


File: bwidget.rb

bwidget.rb

Path: | tk/lib/tkextlib/bwidget.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

BWidget extension support

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/setup.rb tkextlib/bwidget/setup.rb BWidget BWidget


File: arrowbutton.rb

arrowbutton.rb

Path: | tk/lib/tkextlib/bwidget/arrowbutton.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/bwidget/arrowbutton.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/bwidget.rb tkextlib/bwidget/button


File: bitmap.rb

bitmap.rb

Path: | tk/lib/tkextlib/bwidget/bitmap.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/bwidget/bitmap.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/image tkextlib/bwidget.rb


File: button.rb

button.rb

Path: | tk/lib/tkextlib/bwidget/button.rb
Last Update: | Mon Oct 24 20:15:35 AUS Eastern Standard Time 2005

tkextlib/bwidget/button.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/button tkextlib/bwidget.rb


File: buttonbox.rb

buttonbox.rb

Path: | tk/lib/tkextlib/bwidget/buttonbox.rb
Last Update: | Mon Oct 24 20:15:35 AUS Eastern Standard Time 2005

tkextlib/bwidget/buttonbox.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/bwidget.rb tkextlib/bwidget/button


File: combobox.rb

combobox.rb

Path: | tk/lib/tkextlib/bwidget/combobox.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/bwidget/combobox.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/entry tkextlib/bwidget.rb tkextlib/bwidget/listbox tkextlib/bwidget/spinbox


File: dialog.rb

dialog.rb

Path: | tk/lib/tkextlib/bwidget/dialog.rb
Last Update: | Mon Oct 24 20:15:35 AUS Eastern Standard Time 2005

tkextlib/bwidget/dialog.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/frame tkextlib/bwidget.rb tkextlib/bwidget/buttonbox


File: dragsite.rb

dragsite.rb

Path: | tk/lib/tkextlib/bwidget/dragsite.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/bwidget/dragsite.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/bwidget.rb


File: dropsite.rb

dropsite.rb

Path: | tk/lib/tkextlib/bwidget/dropsite.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/bwidget/dropsite.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/bwidget.rb


File: dynamichelp.rb

dynamichelp.rb

Path: | tk/lib/tkextlib/bwidget/dynamichelp.rb
Last Update: | Mon Oct 24 20:15:35 AUS Eastern Standard Time 2005

tkextlib/bwidget/dynamichelp.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/bwidget.rb


File: entry.rb

entry.rb

Path: | tk/lib/tkextlib/bwidget/entry.rb
Last Update: | Mon Oct 24 20:15:35 AUS Eastern Standard Time 2005

tkextlib/bwidget/entry.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/entry tkextlib/bwidget.rb


File: label.rb

label.rb

Path: | tk/lib/tkextlib/bwidget/label.rb
Last Update: | Mon Oct 24 20:15:35 AUS Eastern Standard Time 2005

tkextlib/bwidget/label.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/label tkextlib/bwidget.rb


File: labelentry.rb

labelentry.rb

Path: | tk/lib/tkextlib/bwidget/labelentry.rb
Last Update: | Mon Oct 24 20:15:35 AUS Eastern Standard Time 2005

tkextlib/bwidget/labelentry.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/entry tkextlib/bwidget.rb tkextlib/bwidget/labelframe tkextlib/bwidget/entry


File: labelframe.rb

labelframe.rb

Path: | tk/lib/tkextlib/bwidget/labelframe.rb
Last Update: | Mon Oct 24 20:15:35 AUS Eastern Standard Time 2005

tkextlib/bwidget/labelframe.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/frame tkextlib/bwidget.rb tkextlib/bwidget/label


File: listbox.rb

listbox.rb

Path: | tk/lib/tkextlib/bwidget/listbox.rb
Last Update: | Mon Oct 24 20:15:35 AUS Eastern Standard Time 2005

tkextlib/bwidget/listbox.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/canvas tkextlib/bwidget.rb


File: mainframe.rb

mainframe.rb

Path: | tk/lib/tkextlib/bwidget/mainframe.rb
Last Update: | Mon Oct 24 20:15:35 AUS Eastern Standard Time 2005

tkextlib/bwidget/mainframe.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/frame tkextlib/bwidget.rb tkextlib/bwidget/progressbar


File: messagedlg.rb

messagedlg.rb

Path: | tk/lib/tkextlib/bwidget/messagedlg.rb
Last Update: | Mon Oct 24 20:15:35 AUS Eastern Standard Time 2005

tkextlib/bwidget/messagedlg.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/bwidget.rb tkextlib/bwidget/dialog.rb


File: notebook.rb

notebook.rb

Path: | tk/lib/tkextlib/bwidget/notebook.rb
Last Update: | Mon Oct 24 20:15:35 AUS Eastern Standard Time 2005

tkextlib/bwidget/notebook.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/frame tkextlib/bwidget.rb


File: pagesmanager.rb

pagesmanager.rb

Path: | tk/lib/tkextlib/bwidget/pagesmanager.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/bwidget/pagesmanager.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/frame tkextlib/bwidget.rb


File: panedwindow.rb

panedwindow.rb

Path: | tk/lib/tkextlib/bwidget/panedwindow.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/bwidget/panedwindow.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/frame tkextlib/bwidget.rb


File: panelframe.rb

panelframe.rb

Path: | tk/lib/tkextlib/bwidget/panelframe.rb
Last Update: | Sun Oct 23 08:16:27 AUS Eastern Standard Time 2005

tkextlib/bwidget/panelframe.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/frame tkextlib/bwidget.rb


File: passwddlg.rb

passwddlg.rb

Path: | tk/lib/tkextlib/bwidget/passwddlg.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/bwidget/passwddlg.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/bwidget.rb tkextlib/bwidget/messagedlg


File: progressbar.rb

progressbar.rb

Path: | tk/lib/tkextlib/bwidget/progressbar.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/bwidget/progressbar.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/bwidget.rb


File: progressdlg.rb

progressdlg.rb

Path: | tk/lib/tkextlib/bwidget/progressdlg.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/bwidget/progressdlg.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/variable tkextlib/bwidget.rb tkextlib/bwidget/progressbar tkextlib/bwidget/messagedlg


File: scrollableframe.rb

scrollableframe.rb

Path: | tk/lib/tkextlib/bwidget/scrollableframe.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/bwidget/scrollableframe.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/frame tkextlib/bwidget.rb


File: scrolledwindow.rb

scrolledwindow.rb

Path: | tk/lib/tkextlib/bwidget/scrolledwindow.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/bwidget/scrolledwindow.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/frame tkextlib/bwidget.rb


File: scrollview.rb

scrollview.rb

Path: | tk/lib/tkextlib/bwidget/scrollview.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/bwidget/scrollview.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/bwidget.rb


File: selectcolor.rb

selectcolor.rb

Path: | tk/lib/tkextlib/bwidget/selectcolor.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/bwidget/selectcolor.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/bwidget.rb tkextlib/bwidget/messagedlg


File: selectfont.rb

selectfont.rb

Path: | tk/lib/tkextlib/bwidget/selectfont.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/bwidget/selectfont.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/bwidget.rb tkextlib/bwidget/messagedlg


File: separator.rb

separator.rb

Path: | tk/lib/tkextlib/bwidget/separator.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/bwidget/separator.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/bwidget.rb


File: setup.rb

setup.rb

Path: | tk/lib/tkextlib/bwidget/setup.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

setup.rb — setup script before calling TkPackage.require()

  If you need some setup operations (for example, add a library path
  to the library search path) before using Tcl/Tk library packages
  wrapped by Ruby scripts in this directory, please write the setup
  operations in this file.


File: spinbox.rb

spinbox.rb

Path: | tk/lib/tkextlib/bwidget/spinbox.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/bwidget/entry.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/bwidget.rb tkextlib/bwidget/arrowbutton tkextlib/bwidget/entry


File: statusbar.rb

statusbar.rb

Path: | tk/lib/tkextlib/bwidget/statusbar.rb
Last Update: | Sun Oct 23 08:16:27 AUS Eastern Standard Time 2005

tkextlib/bwidget/statusbar.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/frame tkextlib/bwidget.rb


File: titleframe.rb

titleframe.rb

Path: | tk/lib/tkextlib/bwidget/titleframe.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/bwidget/titleframe.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/frame tkextlib/bwidget.rb


File: tree.rb

tree.rb

Path: | tk/lib/tkextlib/bwidget/tree.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/bwidget/tree.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/canvas tkextlib/bwidget.rb


File: widget.rb

widget.rb

Path: | tk/lib/tkextlib/bwidget/widget.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/bwidget/widget.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/bwidget.rb


File: itcl.rb

itcl.rb

Path: | tk/lib/tkextlib/itcl.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005
incr Tcl
support
                  by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tkextlib/setup.rb tkextlib/itcl/setup.rb tkextlib/itcl/incr_tcl.rb


File: incr_tcl.rb

incr_tcl.rb

Path: | tk/lib/tkextlib/itcl/incr_tcl.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/itk/incr_tcl.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/itcl.rb Itcl Itcl


File: setup.rb

setup.rb

Path: | tk/lib/tkextlib/itcl/setup.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

setup.rb — setup script before calling TkPackage.require()

  If you need some setup operations (for example, add a library path
  to the library search path) before using Tcl/Tk library packages
  wrapped by Ruby scripts in this directory, please write the setup
  operations in this file.


File: itk.rb

itk.rb

Path: | tk/lib/tkextlib/itk.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005
incr Tk
support
                   by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tkextlib/setup.rb tkextlib/itk/setup.rb tkextlib/itk/incr_tk.rb


File: incr_tk.rb

incr_tk.rb

Path: | tk/lib/tkextlib/itk/incr_tk.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/itk/incr_tk.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/menuspec tkextlib/itcl.rb tkextlib/itk.rb Itk Itk


File: setup.rb

setup.rb

Path: | tk/lib/tkextlib/itk/setup.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

setup.rb — setup script before calling TkPackage.require()

  If you need some setup operations (for example, add a library path
  to the library search path) before using Tcl/Tk library packages
  wrapped by Ruby scripts in this directory, please write the setup
  operations in this file.


File: iwidgets.rb

iwidgets.rb

Path: | tk/lib/tkextlib/iwidgets.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005
incr Widgets
support
              by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/itcl tkextlib/itk Iwidgets Iwidgets


File: buttonbox.rb

buttonbox.rb

Path: | tk/lib/tkextlib/iwidgets/buttonbox.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/buttonbox.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: calendar.rb

calendar.rb

Path: | tk/lib/tkextlib/iwidgets/calendar.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/calendar.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: canvasprintbox.rb

canvasprintbox.rb

Path: | tk/lib/tkextlib/iwidgets/canvasprintbox.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/canvasprintbox.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: canvasprintdialog.rb

canvasprintdialog.rb

Path: | tk/lib/tkextlib/iwidgets/canvasprintdialog.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/iwidgets/canvasprintdialog.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: checkbox.rb

checkbox.rb

Path: | tk/lib/tkextlib/iwidgets/checkbox.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/checkbox.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: combobox.rb

combobox.rb

Path: | tk/lib/tkextlib/iwidgets/combobox.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/combobox.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: dateentry.rb

dateentry.rb

Path: | tk/lib/tkextlib/iwidgets/dateentry.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/iwidgets/dateentry.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: datefield.rb

datefield.rb

Path: | tk/lib/tkextlib/iwidgets/datefield.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/datefield.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: dialog.rb

dialog.rb

Path: | tk/lib/tkextlib/iwidgets/dialog.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/iwidgets/dialog.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: dialogshell.rb

dialogshell.rb

Path: | tk/lib/tkextlib/iwidgets/dialogshell.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/dialogshell.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: disjointlistbox.rb

disjointlistbox.rb

Path: | tk/lib/tkextlib/iwidgets/disjointlistbox.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/disjointlistbox.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: entryfield.rb

entryfield.rb

Path: | tk/lib/tkextlib/iwidgets/entryfield.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/entryfield.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: extbutton.rb

extbutton.rb

Path: | tk/lib/tkextlib/iwidgets/extbutton.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/extbutton.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: extfileselectionbox.rb

extfileselectionbox.rb

Path: | tk/lib/tkextlib/iwidgets/extfileselectionbox.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/extfileselectionbox.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: extfileselectiondialog.rb

extfileselectiondialog.rb

Path: | tk/lib/tkextlib/iwidgets/extfileselectiondialog.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/iwidgets/extfileselectiondialog.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: feedback.rb

feedback.rb

Path: | tk/lib/tkextlib/iwidgets/feedback.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/feedback.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: fileselectionbox.rb

fileselectionbox.rb

Path: | tk/lib/tkextlib/iwidgets/fileselectionbox.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/fileselectionbox.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: fileselectiondialog.rb

fileselectiondialog.rb

Path: | tk/lib/tkextlib/iwidgets/fileselectiondialog.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/iwidgets/fileselectiondialog.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: finddialog.rb

finddialog.rb

Path: | tk/lib/tkextlib/iwidgets/finddialog.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/finddialog.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: hierarchy.rb

hierarchy.rb

Path: | tk/lib/tkextlib/iwidgets/hierarchy.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/hierarchy.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/text tkextlib/iwidgets.rb


File: hyperhelp.rb

hyperhelp.rb

Path: | tk/lib/tkextlib/iwidgets/hyperhelp.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/hyperhelp.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: labeledframe.rb

labeledframe.rb

Path: | tk/lib/tkextlib/iwidgets/labeledframe.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/labeledframe.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: labeledwidget.rb

labeledwidget.rb

Path: | tk/lib/tkextlib/iwidgets/labeledwidget.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/labeledwidget.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: mainwindow.rb

mainwindow.rb

Path: | tk/lib/tkextlib/iwidgets/mainwindow.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/mainwindow.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: menubar.rb

menubar.rb

Path: | tk/lib/tkextlib/iwidgets/menubar.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/menubar.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: messagebox.rb

messagebox.rb

Path: | tk/lib/tkextlib/iwidgets/messagebox.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/messagebox.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: messagedialog.rb

messagedialog.rb

Path: | tk/lib/tkextlib/iwidgets/messagedialog.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/iwidgets/messagedialog.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: notebook.rb

notebook.rb

Path: | tk/lib/tkextlib/iwidgets/notebook.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/notebook.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: optionmenu.rb

optionmenu.rb

Path: | tk/lib/tkextlib/iwidgets/optionmenu.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/optionmenu.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: panedwindow.rb

panedwindow.rb

Path: | tk/lib/tkextlib/iwidgets/panedwindow.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/panedwindow.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: promptdialog.rb

promptdialog.rb

Path: | tk/lib/tkextlib/iwidgets/promptdialog.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/iwidgets/promptdialog.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: pushbutton.rb

pushbutton.rb

Path: | tk/lib/tkextlib/iwidgets/pushbutton.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/pushbutton.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: radiobox.rb

radiobox.rb

Path: | tk/lib/tkextlib/iwidgets/radiobox.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/radiobox.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: scopedobject.rb

scopedobject.rb

Path: | tk/lib/tkextlib/iwidgets/scopedobject.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/iwidgets/buttonbox.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: scrolledcanvas.rb

scrolledcanvas.rb

Path: | tk/lib/tkextlib/iwidgets/scrolledcanvas.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/scrolledcanvas.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/canvas tkextlib/iwidgets.rb


File: scrolledframe.rb

scrolledframe.rb

Path: | tk/lib/tkextlib/iwidgets/scrolledframe.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/iwidgets/scrolledframe.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: scrolledhtml.rb

scrolledhtml.rb

Path: | tk/lib/tkextlib/iwidgets/scrolledhtml.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/scrolledhtml.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: scrolledlistbox.rb

scrolledlistbox.rb

Path: | tk/lib/tkextlib/iwidgets/scrolledlistbox.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/scrolledlistbox.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/listbox tkextlib/iwidgets.rb


File: scrolledtext.rb

scrolledtext.rb

Path: | tk/lib/tkextlib/iwidgets/scrolledtext.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/scrolledtext.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/text tkextlib/iwidgets.rb


File: scrolledwidget.rb

scrolledwidget.rb

Path: | tk/lib/tkextlib/iwidgets/scrolledwidget.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/iwidgets/scrolledwidget.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: selectionbox.rb

selectionbox.rb

Path: | tk/lib/tkextlib/iwidgets/selectionbox.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/selectionbox.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: selectiondialog.rb

selectiondialog.rb

Path: | tk/lib/tkextlib/iwidgets/selectiondialog.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/iwidgets/selectiondialog.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: setup.rb

setup.rb

Path: | tk/lib/tkextlib/iwidgets/setup.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

setup.rb — setup script before calling TkPackage.require()

  If you need some setup operations (for example, add a library path
  to the library search path) before using Tcl/Tk library packages
  wrapped by Ruby scripts in this directory, please write the setup
  operations in this file.


File: shell.rb

shell.rb

Path: | tk/lib/tkextlib/iwidgets/shell.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/iwidgets/shell.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: spindate.rb

spindate.rb

Path: | tk/lib/tkextlib/iwidgets/spindate.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/spindate.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: spinint.rb

spinint.rb

Path: | tk/lib/tkextlib/iwidgets/spinint.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/spinint.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: spinner.rb

spinner.rb

Path: | tk/lib/tkextlib/iwidgets/spinner.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/iwidgets/spinner.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: spintime.rb

spintime.rb

Path: | tk/lib/tkextlib/iwidgets/spintime.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/spintime.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: tabnotebook.rb

tabnotebook.rb

Path: | tk/lib/tkextlib/iwidgets/tabnotebook.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/tabnotebook.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: tabset.rb

tabset.rb

Path: | tk/lib/tkextlib/iwidgets/tabset.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/tabset.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: timeentry.rb

timeentry.rb

Path: | tk/lib/tkextlib/iwidgets/timeentry.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/timeentry.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: timefield.rb

timefield.rb

Path: | tk/lib/tkextlib/iwidgets/timefield.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/timefield.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: toolbar.rb

toolbar.rb

Path: | tk/lib/tkextlib/iwidgets/toolbar.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/toolbar.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: watch.rb

watch.rb

Path: | tk/lib/tkextlib/iwidgets/watch.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/iwidgets/watch.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/iwidgets.rb


File: pkg_checker.rb

pkg_checker.rb

Path: | tk/lib/tkextlib/pkg_checker.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

Ruby/Tk extension library checker

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk

Methods

check_pkg get_pkg_list help_msg subdir_check

Public Instance methods

check_pkg(file, verbose=false)

[Source]

# File tk/lib/tkextlib/pkg_checker.rb, line 91
def check_pkg(file, verbose=false)
  pkg_list = get_pkg_list(file)

  error_list = []
  success_list = {}

  pkg_list.each{|name, type|
    next if success_list[name]

    begin
      case type
      when :package
        ver = TkPackage.require(name)
        success_list[name] = ver
        error_list.delete_if{|n, t| n == name}

      when :library
        Tk.load_tcllibrary(name)
        success_list[name] = :library
        error_list.delete_if{|n, t| n == name}

      when :script
        Tk.load_tclscript(name)
        success_list[name] = :script
        error_list.delete_if{|n, t| n == name}

      when :require_ruby_lib
        require name

      end
    rescue => e
      if verbose
        error_list << [name, type, e.message]
      else
        error_list << [name, type]
      end
    end
  }

  success_list.dup.each{|name, ver|
    unless ver.kind_of?(String)
      begin
        ver = TkPackage.require(name)
        sccess_list[name] = ver
      rescue
      end
    end
  }

  [success_list, error_list]
end
get_pkg_list(file)

[Source]

# File tk/lib/tkextlib/pkg_checker.rb, line 66
def get_pkg_list(file)
  pkg_list = []

  File.foreach(file){|l|
    if l =~ /^(?:[^#]+\s|\s*)(?:|;\s*)TkPackage\s*\.\s*require\s*\(?\s*(["'])((\w|:)+)\1/
      pkg = [$2, :package]
      pkg_list << pkg unless pkg_list.member?(pkg)
    end
    if l =~ /^(?:[^#]+\s|\s*)(?:|;\s*)Tk\s*\.\s*load_tcllibrary\s*\(?\s*(["'])((\w|:)+)\1/
      pkg = [$2, :library]
      pkg_list << pkg unless pkg_list.member?(pkg)
    end
    if l =~ /^(?:[^#]+\s|\s*)(?:|;\s*)Tk\s*\.\s*load_tclscript\s*\(?\s*(["'])((\w|:)+)\1/
      pkg = [$2, :script]
      pkg_list << pkg unless pkg_list.member?(pkg)
    end
    if l =~ /^(?:[^#]+\s|\s*)(?:|;\s*)require\s*\(?\s*(["'])((\w|\/|:)+)\1/
      pkg = [$2, :require_ruby_lib]
      pkg_list << pkg unless pkg_list.member?(pkg)
    end
  }

  pkg_list
end
help_msg()

[Source]

# File tk/lib/tkextlib/pkg_checker.rb, line 16
def help_msg
  print "Usage: #{$0} [-l] [-v] [-h] [--] [dir]\n"
  print "\tIf dir is omitted, check the directry that this command exists.\n"
  print "\tAvailable options are \n"
  print "\t  -l : Add dir to $LOAD_PATH\n"
  print "\t       (If dir == '<parent>/tkextlib', add <parent> also.)\n"
  print "\t  -v : Verbose mode (show reason of fail)\n"
  print "\t  -h : Show this message\n"
  print "\t  -- : End of options\n"
end
subdir_check(dir, verbose=false)

[Source]

# File tk/lib/tkextlib/pkg_checker.rb, line 143
def subdir_check(dir, verbose=false)
  Dir.foreach(dir){|f|
    next if f == '.' || f == '..'
    if File.directory?(f)
      subdir_check(File.join(dir, f))
    elsif File.extname(f) == '.rb'
      path = File.join(dir, f)
      suc, err = check_pkg(path, verbose)
      if err.empty?
        print 'Ready : ', path, ' : require->', suc.inspect, "\n"
      else
        print '*LACK : ', path, ' : require->', suc.inspect,
          '  FAIL->', err.inspect, "\n"
      end
    end
  }
end


File: setup.rb

setup.rb

Path: | tk/lib/tkextlib/setup.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

setup.rb — setup script before using Tk extension libraries

  If you need some setup operations for Tk extensions (for example,
  modify the dynamic library path) required, please write the setup
  operations in this file. This file is required at the last of
  "require 'tk'".


File: tcllib.rb

tcllib.rb

Path: | tk/lib/tkextlib/tcllib.rb
Last Update: | Mon Oct 24 20:15:34 AUS Eastern Standard Time 2005

tcllib extension support

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/setup.rb tkextlib/tcllib/setup.rb widget tooltip


File: autoscroll.rb

autoscroll.rb

Path: | tk/lib/tkextlib/tcllib/autoscroll.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005
 tkextlib/tcllib/autoscroll.rb
                              by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

  * Part of tcllib extension
  * Provides for a scrollbar to automatically mapped and unmapped as needed

(The following is the original description of the library.)

This package allows scrollbars to be mapped and unmapped as needed depending on the size and content of the scrollbars scrolled widget. The scrollbar must be managed by either pack or grid, other geometry managers are not supported.

When managed by pack, any geometry changes made in the scrollbars parent between the time a scrollbar is unmapped, and when it is mapped will be lost. It is an error to destroy any of the scrollbars siblings while the scrollbar is unmapped. When managed by grid, if anything becomes gridded in the same row and column the scrollbar occupied it will be replaced by the scrollbar when remapped.

This package may be used on any scrollbar-like widget as long as it supports the set subcommand in the same style as scrollbar. If the set subcommand is not used then this package will have no effect.

Required files

tk tk/scrollbar tkextlib/tcllib.rb autoscroll autoscroll


File: ctext.rb

ctext.rb

Path: | tk/lib/tkextlib/tcllib/ctext.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/tcllib/ctext.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

 * Part of tcllib extension
 * Overloads the text widget and provides new commands

Required files

tk tk/text tkextlib/tcllib.rb ctext ctext


File: cursor.rb

cursor.rb

Path: | tk/lib/tkextlib/tcllib/cursor.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/tcllib/cursor.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

 * Part of tcllib extension
 * Procedures to handle CURSOR data

Required files

tk tkextlib/tcllib.rb cursor cursor


File: datefield.rb

datefield.rb

Path: | tk/lib/tkextlib/tcllib/datefield.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005
 tkextlib/tcllib/datefield.rb
                              by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

  * Part of tcllib extension
  * Tk datefield widget

(The following is the original description of the library.)

The datefield package provides the datefield widget which is an enhanced text entry widget for the purpose of date entry. Only valid dates of the form MM/DD/YYYY can be entered.

The datefield widget is, in fact, just an entry widget with specialized bindings. This means all the command and options for an entry widget apply equally here.

Required files

tk tk/entry tkextlib/tcllib.rb datefield datefield


File: dialog.rb

dialog.rb

Path: | tk/lib/tkextlib/tcllib/dialog.rb
Last Update: | Sun Oct 23 08:16:30 AUS Eastern Standard Time 2005

tkextlib/tcllib/dialog.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

 * Part of tcllib extension
 * Generic dialog widget (themed)

Required files

tk tkextlib/tcllib.rb widget::dialog


File: getstring.rb

getstring.rb

Path: | tk/lib/tkextlib/tcllib/getstring.rb
Last Update: | Sun Oct 23 08:16:30 AUS Eastern Standard Time 2005

tkextlib/tcllib/getstring.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

 * Part of tcllib extension
 * A dialog which consists of an Entry, OK, and Cancel buttons.

Required files

tk tk/entry tkextlib/tcllib.rb getstring


File: history.rb

history.rb

Path: | tk/lib/tkextlib/tcllib/history.rb
Last Update: | Sun Oct 23 08:16:30 AUS Eastern Standard Time 2005

tkextlib/tcllib/history.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

 * Part of tcllib extension
 * Provides a history for Entry widgets

Required files

tk tk/entry tkextlib/tcllib.rb history


File: ico.rb

ico.rb

Path: | tk/lib/tkextlib/tcllib/ico.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

tkextlib/tcllib/ico.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

 * Part of tcllib extension
 * Reading and writing windows icons

Required files

tk tk/image tkextlib/tcllib.rb ico ico history getstring widget::dialog


File: ip_entry.rb

ip_entry.rb

Path: | tk/lib/tkextlib/tcllib/ip_entry.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005
 tkextlib/tcllib/ip_entry.rb
                              by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

  * Part of tcllib extension
  * An IP address entry widget

(The following is the original description of the library.)

This package provides a widget for the entering of a IP address. It guarantees a valid address at all times.

Required files

tk tkextlib/tcllib.rb ipentry ipentry


File: panelframe.rb

panelframe.rb

Path: | tk/lib/tkextlib/tcllib/panelframe.rb
Last Update: | Sun Oct 23 08:16:30 AUS Eastern Standard Time 2005

tkextlib/tcllib/panelframe.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

 * Part of tcllib extension
 * Create PanelFrame widgets.

Required files

tk tkextlib/tcllib.rb widget::panelframe


File: plotchart.rb

plotchart.rb

Path: | tk/lib/tkextlib/tcllib/plotchart.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005
 tkextlib/tcllib/plotchart.rb
                              by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

  * Part of tcllib extension
  * Simple plotting and charting package

(The following is the original description of the library.)

Plotchart is a Tcl-only package that focuses on the easy creation of xy-plots, barcharts and other common types of graphical presentations. The emphasis is on ease of use, rather than flexibility. The procedures that create a plot use the entire canvas window, making the layout of the plot completely automatic.

This results in the creation of an xy-plot in, say, ten lines of code:

   package require Plotchart

   canvas .c -background white -width 400 -height 200
   pack   .c -fill both

   #
   # Create the plot with its x- and y-axes
   #
   set s [::Plotchart::createXYPlot .c {0.0 100.0 10.0} {0.0 100.0 20.0}]

   foreach {x y} {0.0 32.0 10.0 50.0 25.0 60.0 78.0 11.0 } {
       $s plot series1 $x $y
   }

   $s title "Data series"

A drawback of the package might be that it does not do any data management. So if the canvas that holds the plot is to be resized, the whole plot must be redrawn. The advantage, though, is that it offers a number of plot and chart types:

   * XY-plots like the one shown above with any number of data series.
   * Stripcharts, a kind of XY-plots where the horizontal axis is adjusted
     automatically. The result is a kind of sliding window on the data
     series.
   * Polar plots, where the coordinates are polar instead of cartesian.
   * Isometric plots, where the scale of the coordinates in the two
     directions is always the same, i.e. a circle in world coordinates
     appears as a circle on the screen.
     You can zoom in and out, as well as pan with these plots (Note: this
     works best if no axes are drawn, the zooming and panning routines do
     not distinguish the axes), using the mouse buttons with the control
     key and the arrow keys with the control key.
   * Piecharts, with automatic scaling to indicate the proportions.
   * Barcharts, with either vertical or horizontal bars, stacked bars or
     bars side by side.
   * Timecharts, where bars indicate a time period and milestones or other
     important moments in time are represented by triangles.
   * 3D plots (both for displaying surfaces and 3D bars)

Required files

tk tkextlib/tcllib.rb Plotchart Plotchart widget::panelframe


File: ruler.rb

ruler.rb

Path: | tk/lib/tkextlib/tcllib/ruler.rb
Last Update: | Sun Oct 23 08:16:30 AUS Eastern Standard Time 2005

tkextlib/tcllib/ruler.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

 * Part of tcllib extension
 * ruler widget

Required files

tk tkextlib/tcllib.rb widget::ruler


File: screenruler.rb

screenruler.rb

Path: | tk/lib/tkextlib/tcllib/screenruler.rb
Last Update: | Sun Oct 23 08:16:30 AUS Eastern Standard Time 2005

tkextlib/tcllib/screenruler.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

 * Part of tcllib extension
 * screenruler dialog

Required files

tk tkextlib/tcllib.rb widget::screenruler


File: scrollwin.rb

scrollwin.rb

Path: | tk/lib/tkextlib/tcllib/scrollwin.rb
Last Update: | Sun Oct 23 08:16:30 AUS Eastern Standard Time 2005

tkextlib/tcllib/scrollwin.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

 * Part of tcllib extension
 * Scrolled widget

Required files

tk tkextlib/tcllib.rb widget::scrolledwindow


File: setup.rb

setup.rb

Path: | tk/lib/tkextlib/tcllib/setup.rb
Last Update: | Sat Oct 15 23:44:09 AUS Eastern Standard Time 2005

setup.rb — setup script before calling TkPackage.require()

  If you need some setup operations (for example, add a library path
  to the library search path) before using Tcl/Tk library packages
  wrapped by Ruby scripts in this directory, please write the setup
  operations in this file.


File: style.rb

style.rb

Path: | tk/lib/tkextlib/tcllib/style.rb
Last Update: | Mon Oct 24 20:15:36 AUS Eastern Standard Time 2005

tkextlib/tcllib/style.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

 * Part of tcllib extension
 * select and use some 'style' of option (resource) DB

Required files

tk tkextlib/tcllib.rb style


File: superframe.rb

superframe.rb

Path: | tk/lib/tkextlib/tcllib/superframe.rb
Last Update: | Sun Oct 23 08:16:30 AUS Eastern Standard Time 2005

tkextlib/tcllib/superframe.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

 * Part of tcllib extension
 * Superframe widget - enhanced labelframe widget

Required files

tk tkextlib/tcllib.rb widget::superframe


File: swaplist.rb

swaplist.rb

Path: | tk/lib/tkextlib/tcllib/swaplist.rb
Last Update: | Sun Oct 23 08:16:30 AUS Eastern Standard Time 2005

tkextlib/tcllib/swaplist.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

 * Part of tcllib extension
 * A dialog which allows a user to move options between two lists

Required files

tk tkextlib/tcllib.rb swaplist


File: tablelist.rb

tablelist.rb

Path: | tk/lib/tkextlib/tcllib/tablelist.rb
Last Update: | Sun Oct 23 08:16:30 AUS Eastern Standard Time 2005

tkextlib/tcllib/tablelist.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

 * Part of tcllib extension
 * A multi-column listbox

Required files

tk tkextlib/tcllib.rb tkextlib/tcllib/tablelist_tile Tablelist

Constants

Tablelist_usingTile = TkPackage.provide('tile')


File: tablelist_core.rb

tablelist_core.rb

Path: | tk/lib/tkextlib/tcllib/tablelist_core.rb
Last Update: | Sun Oct 23 08:16:30 AUS Eastern Standard Time 2005

tkextlib/tcllib/tablelist_core.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

 * Part of tcllib extension
 * This file is required by 'tkextlib/tcllib/tablelist.rb' or
   'tkextlib/tcllib/tablelist_tile.rb'.

Required files

swaplist
widget::superframe
style
widget::scrolledwindow
widget::screenruler
widget::ruler


File: tablelist_tile.rb

tablelist_tile.rb

Path: | tk/lib/tkextlib/tcllib/tablelist_tile.rb
Last Update: | Sun Oct 23 08:16:30 AUS Eastern Standard Time 2005

tkextlib/tcllib/tablelist_tlie.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

 * Part of tcllib extension
 * A multi-column listbox

Required files

tk tkextlib/tcllib.rb Tablelist_tile

Constants

Tablelist_usingTile = true


File: tkpiechart.rb

tkpiechart.rb

Path: | tk/lib/tkextlib/tcllib/tkpiechart.rb
Last Update: | Mon Oct 24 20:15:37 AUS Eastern Standard Time 2005

tkextlib/tcllib/tkpiechart.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

 * Part of tcllib extension
 * Create 2D or 3D pies with labels in Tcl canvases

Required files

tk tk/canvas tkextlib/tcllib.rb tkpiechart tkpiechart


File: tooltip.rb

tooltip.rb

Path: | tk/lib/tkextlib/tcllib/tooltip.rb
Last Update: | Sun Oct 23 08:16:30 AUS Eastern Standard Time 2005

tkextlib/tcllib/tooltip.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

 * Part of tcllib extension
 * Provides tooltips, a small text message that is displayed when the
   mouse hovers over a widget.

Required files

tk tkextlib/tcllib.rb tooltip


File: widget.rb

widget.rb

Path: | tk/lib/tkextlib/tcllib/widget.rb
Last Update: | Sun Oct 23 08:16:30 AUS Eastern Standard Time 2005

tkextlib/tcllib/widget.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

 * Part of tcllib extension
 * megawidget package that uses snit as the object system (snidgets)

Required files

tk tkextlib/tcllib.rb widget


File: tclx.rb

tclx.rb

Path: | tk/lib/tkextlib/tclx.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

TclX support

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tkextlib/setup.rb tkextlib/tclx/setup.rb tkextlib/tclx/tclx


File: setup.rb

setup.rb

Path: | tk/lib/tkextlib/tclx/setup.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

setup.rb — setup script before calling TkPackage.require()

  If you need some setup operations (for example, add a library path
  to the library search path) before using Tcl/Tk library packages
  wrapped by Ruby scripts in this directory, please write the setup
  operations in this file.


File: tclx.rb

tclx.rb

Path: | tk/lib/tkextlib/tclx/tclx.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

tclx/tclx.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/setup.rb tkextlib/tclx/setup.rb Tclx Tclx


File: tile.rb

tile.rb

Path: | tk/lib/tkextlib/tile.rb
Last Update: | Mon Oct 24 20:15:34 AUS Eastern Standard Time 2005

Tile theme engin (tile widget set) support

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/setup.rb tkextlib/tile/setup.rb tile tile


File: dialog.rb

dialog.rb

Path: | tk/lib/tkextlib/tile/dialog.rb
Last Update: | Sun Oct 23 08:16:31 AUS Eastern Standard Time 2005

ttk::dialog (tile-0.7+)

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/tile.rb


File: setup.rb

setup.rb

Path: | tk/lib/tkextlib/tile/setup.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

setup.rb — setup script before calling TkPackage.require()

  If you need some setup operations (for example, add a library path
  to the library search path) before using Tcl/Tk library packages
  wrapped by Ruby scripts in this directory, please write the setup
  operations in this file.


File: style.rb

style.rb

Path: | tk/lib/tkextlib/tile/style.rb
Last Update: | Mon Oct 24 20:15:37 AUS Eastern Standard Time 2005

style commands

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/tile.rb


File: tbutton.rb

tbutton.rb

Path: | tk/lib/tkextlib/tile/tbutton.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

tbutton widget

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/tile.rb


File: tcheckbutton.rb

tcheckbutton.rb

Path: | tk/lib/tkextlib/tile/tcheckbutton.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

tcheckbutton widget

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/tile.rb


File: tcombobox.rb

tcombobox.rb

Path: | tk/lib/tkextlib/tile/tcombobox.rb
Last Update: | Mon Oct 24 20:15:37 AUS Eastern Standard Time 2005

tcombobox widget

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/tile.rb


File: tentry.rb

tentry.rb

Path: | tk/lib/tkextlib/tile/tentry.rb
Last Update: | Mon Oct 24 20:15:37 AUS Eastern Standard Time 2005

tentry widget

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/tile.rb


File: tframe.rb

tframe.rb

Path: | tk/lib/tkextlib/tile/tframe.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

tframe widget

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/tile.rb


File: tlabel.rb

tlabel.rb

Path: | tk/lib/tkextlib/tile/tlabel.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

tlabel widget

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/tile.rb


File: tlabelframe.rb

tlabelframe.rb

Path: | tk/lib/tkextlib/tile/tlabelframe.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

tlabelframe widget

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/tile.rb


File: tmenubutton.rb

tmenubutton.rb

Path: | tk/lib/tkextlib/tile/tmenubutton.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

tmenubutton widget

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/tile.rb


File: tnotebook.rb

tnotebook.rb

Path: | tk/lib/tkextlib/tile/tnotebook.rb
Last Update: | Mon Oct 24 20:15:37 AUS Eastern Standard Time 2005

tnotebook widget

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/tile.rb


File: tpaned.rb

tpaned.rb

Path: | tk/lib/tkextlib/tile/tpaned.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

tpaned widget

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/tile.rb


File: tprogressbar.rb

tprogressbar.rb

Path: | tk/lib/tkextlib/tile/tprogressbar.rb
Last Update: | Mon Oct 24 20:15:37 AUS Eastern Standard Time 2005

tprogressbar widget

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/tile.rb


File: tradiobutton.rb

tradiobutton.rb

Path: | tk/lib/tkextlib/tile/tradiobutton.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

tradiobutton widget

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/tile.rb


File: treeview.rb

treeview.rb

Path: | tk/lib/tkextlib/tile/treeview.rb
Last Update: | Mon Oct 24 20:15:37 AUS Eastern Standard Time 2005

treeview widget

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/tile.rb


File: tscale.rb

tscale.rb

Path: | tk/lib/tkextlib/tile/tscale.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

tscale & tprogress widget

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/tile.rb


File: tscrollbar.rb

tscrollbar.rb

Path: | tk/lib/tkextlib/tile/tscrollbar.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

tscrollbar widget

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/tile.rb


File: tseparator.rb

tseparator.rb

Path: | tk/lib/tkextlib/tile/tseparator.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

tseparator widget

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/tile.rb


File: tsquare.rb

tsquare.rb

Path: | tk/lib/tkextlib/tile/tsquare.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

tsquare widget

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/tile.rb


File: tkDND.rb

tkDND.rb

Path: | tk/lib/tkextlib/tkDND.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

TkDND (Tk Drag & Drop Extension) support

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/setup.rb tkextlib/tkDND/setup.rb


File: setup.rb

setup.rb

Path: | tk/lib/tkextlib/tkDND/setup.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

setup.rb — setup script before calling TkPackage.require()

  If you need some setup operations (for example, add a library path
  to the library search path) before using Tcl/Tk library packages
  wrapped by Ruby scripts in this directory, please write the setup
  operations in this file.


File: shape.rb

shape.rb

Path: | tk/lib/tkextlib/tkDND/shape.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

tkextlib/tkDND/shape.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/setup.rb tkextlib/tkDND/setup.rb shape


File: tkdnd.rb

tkdnd.rb

Path: | tk/lib/tkextlib/tkDND/tkdnd.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

tkextlib/tkDND/tkdnd.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/setup.rb tkextlib/tkDND/setup.rb tkdnd tkdnd tkdnd


File: tkHTML.rb

tkHTML.rb

Path: | tk/lib/tkextlib/tkHTML.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

TkHtml support

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tkextlib/setup.rb tkextlib/tkHTML/setup.rb tkextlib/tkHTML/htmlwidget


File: htmlwidget.rb

htmlwidget.rb

Path: | tk/lib/tkextlib/tkHTML/htmlwidget.rb
Last Update: | Mon Oct 24 20:15:37 AUS Eastern Standard Time 2005

tkextlib/tkHTML/htmlwidget.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/setup.rb tkextlib/tkHTML/setup.rb Tkhtml Tkhtml


File: setup.rb

setup.rb

Path: | tk/lib/tkextlib/tkHTML/setup.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

setup.rb — setup script before calling TkPackage.require()

  If you need some setup operations (for example, add a library path
  to the library search path) before using Tcl/Tk library packages
  wrapped by Ruby scripts in this directory, please write the setup
  operations in this file.


File: tkimg.rb

tkimg.rb

Path: | tk/lib/tkextlib/tkimg.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

TkImg extension support

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/setup.rb tkextlib/tkimg/setup.rb Img Img


File: bmp.rb

bmp.rb

Path: | tk/lib/tkextlib/tkimg/bmp.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

TkImg - format ‘bmp’

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/setup.rb tkextlib/tkimg/setup.rb img::bmp img::bmp


File: gif.rb

gif.rb

Path: | tk/lib/tkextlib/tkimg/gif.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

TkImg - format ‘gif’

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/setup.rb tkextlib/tkimg/setup.rb img::gif img::gif


File: ico.rb

ico.rb

Path: | tk/lib/tkextlib/tkimg/ico.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

TkImg - format ‘ico’

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/setup.rb tkextlib/tkimg/setup.rb img::ico img::ico


File: jpeg.rb

jpeg.rb

Path: | tk/lib/tkextlib/tkimg/jpeg.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

TkImg - format ‘jpeg’

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/setup.rb tkextlib/tkimg/setup.rb img::jpeg img::jpeg


File: pcx.rb

pcx.rb

Path: | tk/lib/tkextlib/tkimg/pcx.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

TkImg - format ‘pcx’

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)#

Required files

tk tkextlib/setup.rb tkextlib/tkimg/setup.rb img::pcx img::pcx


File: pixmap.rb

pixmap.rb

Path: | tk/lib/tkextlib/tkimg/pixmap.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

TkImg - format ‘pixmap’

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/setup.rb tkextlib/tkimg/setup.rb img::pixmap img::pixmap


File: png.rb

png.rb

Path: | tk/lib/tkextlib/tkimg/png.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

TkImg - format ‘png’

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/setup.rb tkextlib/tkimg/setup.rb img::png img::png


File: ppm.rb

ppm.rb

Path: | tk/lib/tkextlib/tkimg/ppm.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

TkImg - format ‘ppm’

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/setup.rb tkextlib/tkimg/setup.rb img::ppm img::ppm


File: ps.rb

ps.rb

Path: | tk/lib/tkextlib/tkimg/ps.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

TkImg - format ‘ps’

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/setup.rb tkextlib/tkimg/setup.rb img::ps img::ps


File: setup.rb

setup.rb

Path: | tk/lib/tkextlib/tkimg/setup.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

setup.rb — setup script before calling TkPackage.require()

  If you need some setup operations (for example, add a library path
  to the library search path) before using Tcl/Tk library packages
  wrapped by Ruby scripts in this directory, please write the setup
  operations in this file.


File: sgi.rb

sgi.rb

Path: | tk/lib/tkextlib/tkimg/sgi.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

TkImg - format ‘sgi’

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/setup.rb tkextlib/tkimg/setup.rb img::sgi img::sgi


File: sun.rb

sun.rb

Path: | tk/lib/tkextlib/tkimg/sun.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

TkImg - format ‘sun’

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/setup.rb tkextlib/tkimg/setup.rb img::sun img::sun


File: tga.rb

tga.rb

Path: | tk/lib/tkextlib/tkimg/tga.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

TkImg - format ‘tga’

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/setup.rb tkextlib/tkimg/setup.rb img::tga img::tga


File: tiff.rb

tiff.rb

Path: | tk/lib/tkextlib/tkimg/tiff.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

TkImg - format ‘tiff’

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/setup.rb tkextlib/tkimg/setup.rb img::tiff img::tiff


File: window.rb

window.rb

Path: | tk/lib/tkextlib/tkimg/window.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

TkImg - format ‘window’

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/setup.rb tkextlib/tkimg/setup.rb img::window img::window


File: xbm.rb

xbm.rb

Path: | tk/lib/tkextlib/tkimg/xbm.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

TkImg - format ‘xbm’

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/setup.rb tkextlib/tkimg/setup.rb img::xbm img::xbm


File: xpm.rb

xpm.rb

Path: | tk/lib/tkextlib/tkimg/xpm.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

TkImg - format ‘xpm’

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/setup.rb tkextlib/tkimg/setup.rb img::xpm img::xpm


File: tktable.rb

tktable.rb

Path: | tk/lib/tkextlib/tktable.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

TkTable support

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/setup.rb tkextlib/tktable/setup.rb tkextlib/tktable/tktable


File: setup.rb

setup.rb

Path: | tk/lib/tkextlib/tktable/setup.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

setup.rb — setup script before calling TkPackage.require()

  If you need some setup operations (for example, add a library path
  to the library search path) before using Tcl/Tk library packages
  wrapped by Ruby scripts in this directory, please write the setup
  operations in this file.


File: tktable.rb

tktable.rb

Path: | tk/lib/tkextlib/tktable/tktable.rb
Last Update: | Mon Oct 24 20:15:37 AUS Eastern Standard Time 2005

tkextlib/tktable/tktable.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/validation tkextlib/setup.rb tkextlib/tktable/setup.rb Tktable Tktable


File: tktrans.rb

tktrans.rb

Path: | tk/lib/tkextlib/tktrans.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

TkTrans support (win32 only)

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/setup.rb tkextlib/tktrans/setup.rb tkextlib/tktrans/tktrans


File: setup.rb

setup.rb

Path: | tk/lib/tkextlib/tktrans/setup.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

setup.rb — setup script before calling TkPackage.require()

  If you need some setup operations (for example, add a library path
  to the library search path) before using Tcl/Tk library packages
  wrapped by Ruby scripts in this directory, please write the setup
  operations in this file.


File: tktrans.rb

tktrans.rb

Path: | tk/lib/tkextlib/tktrans/tktrans.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

TkTrans support (win32 only)

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/setup.rb tkextlib/tktrans/setup.rb tktrans tktrans


File: treectrl.rb

treectrl.rb

Path: | tk/lib/tkextlib/treectrl.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

TkTreeCtrl support

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tkextlib/setup.rb tkextlib/treectrl/setup.rb tkextlib/treectrl/tktreectrl


File: setup.rb

setup.rb

Path: | tk/lib/tkextlib/treectrl/setup.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

setup.rb — setup script before calling TkPackage.require()

  If you need some setup operations (for example, add a library path
  to the library search path) before using Tcl/Tk library packages
  wrapped by Ruby scripts in this directory, please write the setup
  operations in this file.


File: tktreectrl.rb

tktreectrl.rb

Path: | tk/lib/tkextlib/treectrl/tktreectrl.rb
Last Update: | Mon Oct 24 20:15:37 AUS Eastern Standard Time 2005

tkextlib/treectrl/tktreectrl.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/setup.rb tkextlib/treectrl/setup.rb treectrl treectrl


File: trofs.rb

trofs.rb

Path: | tk/lib/tkextlib/trofs.rb
Last Update: | Sun Oct 23 08:16:25 AUS Eastern Standard Time 2005

trofs support

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tkextlib/setup.rb tkextlib/trofs/setup.rb tkextlib/trofs/trofs.rb


File: vu.rb

vu.rb

Path: | tk/lib/tkextlib/vu.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

The vu widget set support

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/setup.rb tkextlib/vu/setup.rb vu vu


File: bargraph.rb

bargraph.rb

Path: | tk/lib/tkextlib/vu/bargraph.rb
Last Update: | Mon Oct 24 20:15:37 AUS Eastern Standard Time 2005

::vu::bargraph widget

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/vu.rb


File: charts.rb

charts.rb

Path: | tk/lib/tkextlib/vu/charts.rb
Last Update: | Mon Oct 24 20:15:37 AUS Eastern Standard Time 2005

charts — Create and manipulate canvas Add-On Items

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tk/canvas tkextlib/vu.rb


File: dial.rb

dial.rb

Path: | tk/lib/tkextlib/vu/dial.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

::vu::dial widget

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/vu.rb


File: pie.rb

pie.rb

Path: | tk/lib/tkextlib/vu/pie.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

::vu::pie widget

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/vu.rb


File: setup.rb

setup.rb

Path: | tk/lib/tkextlib/vu/setup.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

setup.rb — setup script before calling TkPackage.require()

  If you need some setup operations (for example, add a library path
  to the library search path) before using Tcl/Tk library packages
  wrapped by Ruby scripts in this directory, please write the setup
  operations in this file.


File: spinbox.rb

spinbox.rb

Path: | tk/lib/tkextlib/vu/spinbox.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

::vu::spinbox widget

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

a standard spinbox (<= 8.3) This is the same as the 8.4 core spinbox widget.

Required files

tk tkextlib/vu.rb


File: winico.rb

winico.rb

Path: | tk/lib/tkextlib/winico.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

winico — Windows Icon extension support

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/setup.rb tkextlib/tktable/setup.rb tkextlib/winico/winico


File: setup.rb

setup.rb

Path: | tk/lib/tkextlib/winico/setup.rb
Last Update: | Sat Oct 15 23:44:10 AUS Eastern Standard Time 2005

setup.rb — setup script before calling TkPackage.require()

  If you need some setup operations (for example, add a library path
  to the library search path) before using Tcl/Tk library packages
  wrapped by Ruby scripts in this directory, please write the setup
  operations in this file.


File: winico.rb

winico.rb

Path: | tk/lib/tkextlib/winico/winico.rb
Last Update: | Mon Oct 24 20:15:37 AUS Eastern Standard Time 2005

tkextlib/winico/winico.rb

                             by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)

Required files

tk tkextlib/setup.rb tkextlib/winico/setup.rb winico winico

Methods

add_to_taskbar delete_from_taskbar modify_taskbar taskbar_add taskbar_delete taskbar_modify

Public Instance methods

add_to_taskbar(keys = {})

[Source]

# File tk/lib/tkextlib/winico/winico.rb, line 152
  def add_to_taskbar(keys = {})
    keys = _symbolkey2str(keys)
    Winico_callback._config_keys.each{|k|
      if keys[k].kind_of?(Array)
        cmd, *args = keys[k]
        keys[k] = Winico_callback.new(cmd, args.join(' '))
       # elsif keys[k].kind_of?(Proc)
      elsif TkComm._callback_entry?(keys[k])
        keys[k] = Winico_callback.new(keys[k])
      end
    }
    tk_call('winico', 'taskbar', 'add', @id, *(hash_kv(keys)))
    self
  end
delete_from_taskbar()

[Source]

# File tk/lib/tkextlib/winico/winico.rb, line 184
  def delete_from_taskbar
    tk_call('winico', 'taskbar', 'delete', @id)
    self
  end
modify_taskbar(keys = {})

[Source]

# File tk/lib/tkextlib/winico/winico.rb, line 168
  def modify_taskbar(keys = {})
    keys = _symbolkey2str(keys)
    Winico_callback._config_keys.each{|k|
      if keys[k].kind_of?(Array)
        cmd, *args = keys[k]
        keys[k] = Winico_callback.new(cmd, args.join(' '))
      # elsif keys[k].kind_of?(Proc)
      elsif TkComm._callback_entry?(keys[k])
        keys[k] = Winico_callback.new(keys[k])
      end
    }
    tk_call('winico', 'taskbar', 'modify', @id, *(hash_kv(keys)))
    self
  end
taskbar_add(keys = {})

Alias for add_to_taskbar

taskbar_delete()

Alias for delete_from_taskbar

taskbar_modify(keys = {})

Alias for modify_taskbar


File: tkfont.rb

tkfont.rb

Path: | tk/lib/tkfont.rb
Last Update: | Sat Oct 15 23:44:07 AUS Eastern Standard Time 2005

tkfont.rb - load tk/font.rb

Required files

tk/font


File: tkmacpkg.rb

tkmacpkg.rb

Path: | tk/lib/tkmacpkg.rb
Last Update: | Sat Oct 15 23:44:07 AUS Eastern Standard Time 2005

tkmacpkg.rb - load tk/macpkg.rb

Required files

tk/macpkg


File: tkmenubar.rb

tkmenubar.rb

Path: | tk/lib/tkmenubar.rb
Last Update: | Sat Oct 15 23:44:07 AUS Eastern Standard Time 2005

tkmenubar.rb - load tk/menubar.rb

Required files

tk/menubar


File: tkmngfocus.rb

tkmngfocus.rb

Path: | tk/lib/tkmngfocus.rb
Last Update: | Sat Oct 15 23:44:07 AUS Eastern Standard Time 2005

tkmngfocus.rb - load tk/mngfocus.rb

Required files

tk/mngfocus


File: tkpalette.rb

tkpalette.rb

Path: | tk/lib/tkpalette.rb
Last Update: | Sat Oct 15 23:44:07 AUS Eastern Standard Time 2005

tkpalette.rb - load tk/palette.rb

Required files

tk/palette


File: tkscrollbox.rb

tkscrollbox.rb

Path: | tk/lib/tkscrollbox.rb
Last Update: | Sat Oct 15 23:44:07 AUS Eastern Standard Time 2005

tkscrollbox.rb - load tk/scrollbox.rb

Required files

tk/scrollbox


File: tktext.rb

tktext.rb

Path: | tk/lib/tktext.rb
Last Update: | Sat Oct 15 23:44:07 AUS Eastern Standard Time 2005

tktext.rb - load tk/text.rb

Required files

tk/text


File: tkvirtevent.rb

tkvirtevent.rb

Path: | tk/lib/tkvirtevent.rb
Last Update: | Sat Oct 15 23:44:07 AUS Eastern Standard Time 2005

tkvirtevent.rb - load tk/virtevent.rb

Required files

tk/virtevent


File: tkwinpkg.rb

tkwinpkg.rb

Path: | tk/lib/tkwinpkg.rb
Last Update: | Sat Oct 15 23:44:08 AUS Eastern Standard Time 2005

tkwinpkg.rb - load tk/winpkg.rb

Required files

tk/winpkg


File: tkutil.c

tkutil.c

Path: | tk/tkutil.c
Last Update: | Thu Jul 28 19:15:33 AUS Eastern Standard Time 2005


Class: Dir

Class | Dir
In: | tmpdir.rb
Parent: | Object

tmpdir - retrieve temporary directory path

$Id: tmpdir.rb,v 1.5 2003/07/26 15:38:58 eban Exp $

Methods

tmpdir

Public Class methods

tmpdir()

[Source]

# File tmpdir.rb, line 27
  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


File: tmpdir.rb

tmpdir.rb

Path: | tmpdir.rb
Last Update: | Sun Jul 27 01:38:58 AUS Eastern Standard Time 2003

tmpdir - retrieve temporary directory path

$Id: tmpdir.rb,v 1.5 2003/07/26 15:38:58 eban Exp $

Required files

Win32API


Class: Tracer

Class | Tracer
In: | 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

Constants

MY_FILE_NAME | = | caller(0)[0].scan(/^(.*):[0-9]+$/)[0][0]
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)

[Source]

# File tracer.rb, line 151
  def Tracer.add_filter(p = proc)
    Single.add_filter(p)
  end
new()

[Source]

# File tracer.rb, line 39
  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
off()

[Source]

# File tracer.rb, line 143
  def Tracer.off
    Single.off
  end
on() {|| ...}

[Source]

# File tracer.rb, line 135
  def Tracer.on
    if block_given?
      Single.on{yield}
    else
      Single.on
    end
  end
set_get_line_procs(file_name, p = proc)

[Source]

# File tracer.rb, line 147
  def Tracer.set_get_line_procs(file_name, p = proc)
    Single.set_get_line_procs(file_name, p)
  end

Public Instance methods

add_filter(p = proc)

[Source]

# File tracer.rb, line 75
  def add_filter(p = proc)
    @filters.push p
  end
get_line(file, line)

[Source]

# File tracer.rb, line 83
  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()

[Source]

# File tracer.rb, line 107
  def get_thread_no
    if no = @threads[Thread.current.object_id]
      no
    else
      @threads[Thread.current.object_id] = @threads.size
    end
  end
off()

[Source]

# File tracer.rb, line 70
  def off
    set_trace_func nil
    stdout.print "Trace off\n" if Tracer.verbose?
  end
on() {|| ...}

[Source]

# File tracer.rb, line 56
  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
set_get_line_procs(file, p = proc)

[Source]

# File tracer.rb, line 79
  def set_get_line_procs(file, p = proc)
    @get_line_procs[file] = p
  end
stdout()

[Source]

# File tracer.rb, line 52
  def stdout
    Tracer.stdout
  end
trace_func(event, file, line, id, binding, klass, *)

[Source]

# File tracer.rb, line 115
  def trace_func(event, file, line, id, binding, klass, *)
    return if file == MY_FILE_NAME

    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


File: tracer.rb

tracer.rb

Path: | tracer.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005
  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__


Module: TSort

Module | TSort
In: | 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.

[Source]

# File tsort.rb, line 177
  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(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.

[Source]

# File tsort.rb, line 198
  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
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.

[Source]

# File tsort.rb, line 162
  def strongly_connected_components
    result = []
    each_strongly_connected_component {|component| result << component}
    result
  end
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.

[Source]

# File tsort.rb, line 133
  def tsort
    result = []
    tsort_each {|element| result << element}
    result
  end
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.

[Source]

# File tsort.rb, line 147
  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
tsort_each_child(node) {|child| ...}

Should be implemented by a extended class.

tsort_each_child is used to iterate for child nodes of node.

[Source]

# File tsort.rb, line 239
  def tsort_each_child(node) # :yields: child
    raise NotImplementedError.new
  end
tsort_each_node( {|node| ...}

Should be implemented by a extended class.

tsort_each_node is used to iterate for all nodes over a graph.

[Source]

# File tsort.rb, line 230
  def tsort_each_node # :yields: node
    raise NotImplementedError.new
  end


Class: TSort::Cyclic

Class | TSort::Cyclic
In: | tsort.rb
Parent: | StandardError


File: tsort.rb

tsort.rb

Path: | tsort.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

Required files

test/unit


File: un.rb

un.rb

Path: | un.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

un.rb

Copyright © 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

[Source]

# File un.rb, line 195
def chmod
  setup do |argv, options|
    mode = argv.shift.oct
    FileUtils.chmod mode, argv, options
  end
end
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

[Source]

# File 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
help()

Display help message.

  ruby -run -e help [COMMAND]

[Source]

# File 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
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

[Source]

# File 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
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

[Source]

# File 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
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

[Source]

# File 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
mv()

Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY.

  ruby -run -e mv -- [OPTION] SOURCE DEST

  -v          verbose

[Source]

# File 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()

Remove the FILE

  ruby -run -e rm -- [OPTION] FILE

  -f          ignore nonexistent files
  -r          remove the contents of directories recursively
  -v          verbose

[Source]

# File 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
rmdir()

Remove the DIR.

  ruby -run -e rmdir -- [OPTION] DIR

  -v          verbose

[Source]

# File un.rb, line 160
def rmdir
  setup do |argv, options|
    FileUtils.rmdir argv, options
  end
end
setup(options = "") {|ARGV, opt_hash| ...}

[Source]

# File 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
touch()

Update the access and modification times of each FILE to the current time.

  ruby -run -e touch -- [OPTION] FILE

  -v          verbose

[Source]

# File un.rb, line 210
def touch
  setup do |argv, options|
    FileUtils.touch argv, options
  end
end


Module: FileUtils

Module | FileUtils
In: | un.rb


Module: URI

Module | URI
In: | uri.rb uri/mailto.rb uri/ldap.rb uri/https.rb uri/http.rb uri/generic.rb uri/ftp.rb uri/common.rb

uri/common.rb

Author: | Akira Yamada <akira@ruby-lang.org>
Revision: | $Id: common.rb,v 1.11.2.7 2005/06/24 04:15:20 akira Exp $
License: | You can redistribute it and/or modify it under the same term as Ruby.

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.org/bla", "mailto:test@example.com"]

[Source]

# File uri/common.rb, line 547
  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
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>

[Source]

# File uri/common.rb, line 515
  def self.join(*str)
    u = self.parse(str[0])
    str[1 .. -1].each do |x|
      u = u.merge(x)
    end
    u
  end
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"

[Source]

# File uri/common.rb, line 479
  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
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

[Source]

# File uri/common.rb, line 589
  def self.regexp(schemes = nil)
    unless schemes
      ABS_URI_REF
    else
      /(?=#{Regexp.union(*schemes)}:)#{PATTERN::X_ABS_URI}/xn
    end
  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]

[Source]

# File uri/common.rb, line 376
  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


Module: Kernel

Module | Kernel
In: | uri/common.rb

Methods

URI

Public Instance methods

URI(uri_str)

alias for URI.parse.

This method is introduced at 1.8.2.

[Source]

# File uri/common.rb, line 603
  def URI(uri_str) # :doc:
    URI.parse(uri_str)
  end


Class: URI::BadURIError

Class | URI::BadURIError
In: | uri/common.rb
Parent: | Error

URI is valid, bad usage is not.


Class: URI::Error

Class | URI::Error
In: | uri/common.rb
Parent: | StandardError

Base class for all URI exceptions.


Module: URI::Escape

Module | URI::Escape
In: | 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.

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"

[Source]

# File uri/common.rb, line 280
    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(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"

[Source]

# File uri/common.rb, line 315
    def unescape(str)
      str.gsub(ESCAPED) do
        $&[1,2].hex.chr
      end
    end


Class: URI::FTP

Class | URI::FTP
In: | uri/ftp.rb
Parent: | Generic

RFC1738 section 3.2.

Methods

build new new2 to_s typecode=

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".

[Source]

# File 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(*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"

[Source]

# File 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
new2(user, password, host, port, path, typecode = nil, arg_check = true)

[Source]

# File 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

Public Instance methods

to_s()

[Source]

# File 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
typecode=(typecode)

[Source]

# File uri/ftp.rb, line 118
    def typecode=(typecode)
      check_typecode(typecode)
      set_typecode(typecode)
      typecode
    end


Class: URI::Generic

Class | URI::Generic
In: | uri/generic.rb
Parent: | Object

Base class for all URI classes.

Methods

+ - == absolute absolute? build build2 coerce component component default_port default_port eql? fragment= hash hierarchical? host= inspect merge merge! new normalize normalize! opaque= password password= path= port= query= registry= relative? route_from route_to scheme= select 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.

[Source]

# File uri/generic.rb, line 107
    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
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.

[Source]

# File uri/generic.rb, line 69
    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
component()

Components of the URI in the order.

[Source]

# File uri/generic.rb, line 44
    def self.component
      self::COMPONENT
    end
default_port()

Returns default port

[Source]

# File uri/generic.rb, line 25
    def self.default_port
      self::DEFAULT_PORT
    end
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.

[Source]

# File uri/generic.rb, line 155
    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
use_registry()

DOC: FIXME!

[Source]

# File uri/generic.rb, line 53
    def self.use_registry
      self::USE_REGISTRY
    end

Public Instance methods

+(oth)

Alias for merge

-(oth)

Alias for route_from

==(oth)

Compares to URI’s

[Source]

# File uri/generic.rb, line 1041
    def ==(oth)
      if self.class == oth.class
        self.normalize.component_ary == oth.normalize.component_ary
      else
        false
      end
    end
absolute()

Alias for absolute?

absolute?()

Checks if URI is an absolute one

[Source]

# File uri/generic.rb, line 594
    def absolute?
      if @scheme
        true
      else
        false
      end
    end
coerce(oth)

[Source]

# File uri/generic.rb, line 1107
    def coerce(oth)
      case oth
      when String
        oth = URI.parse(oth)
      else
        super
      end

      return oth, self
    end
component()

[Source]

# File uri/generic.rb, line 223
    def component
      self.class.component
    end
default_port()

[Source]

# File uri/generic.rb, line 29
    def default_port
      self.class.default_port
    end
eql?(oth)

[Source]

# File uri/generic.rb, line 1053
    def eql?(oth)
      self.component_ary.eql?(oth.component_ary)
    end
fragment=(v)

[Source]

# File uri/generic.rb, line 574
    def fragment=(v)
      check_fragment(v)
      set_fragment(v)
      v
    end
hash()

[Source]

# File uri/generic.rb, line 1049
    def hash
      self.component_ary.hash
    end
hierarchical?()

Checks if URI has a path

[Source]

# File uri/generic.rb, line 583
    def hierarchical?
      if @path
        true
      else
        false
      end
    end
host=(v)

[Source]

# File uri/generic.rb, line 393
    def host=(v)
      check_host(v)
      set_host(v)
      v
    end
inspect()

[Source]

# File uri/generic.rb, line 1103
    def inspect
      sprintf("#<%s:%#0x URL:%s>", self.class.to_s, self.object_id, self.to_s)
    end
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>

[Source]

# File uri/generic.rb, line 725
    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
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>

[Source]

# File uri/generic.rb, line 697
    def merge!(oth)
      t = merge(oth)
      if self == t
        nil
      else
        replace!(t)
        self
      end
    end
normalize()

Returns normalized URI

[Source]

# File uri/generic.rb, line 967
    def normalize
      uri = dup
      uri.normalize!
      uri
    end
normalize!()

Destructive version of normalize

[Source]

# File uri/generic.rb, line 976
    def normalize!
      if path && path == ''
        set_path('/')
      end
      if host && host != host.downcase
        set_host(self.host.downcase)
      end
    end
opaque=(v)

[Source]

# File uri/generic.rb, line 551
    def opaque=(v)
      check_opaque(v)
      set_opaque(v)
      v
    end
password()

[Source]

# File uri/generic.rb, line 369
    def password
      @password
    end
password=(password)

[Source]

# File uri/generic.rb, line 315
    def password=(password)
      check_password(password)
      set_password(password)
      password
    end
path=(v)

[Source]

# File uri/generic.rb, line 491
    def path=(v)
      check_path(v)
      set_path(v)
      v
    end
port=(v)

[Source]

# File uri/generic.rb, line 426
    def port=(v)
      check_port(v)
      set_port(v)
      port
    end
query=(v)

[Source]

# File uri/generic.rb, line 522
    def query=(v)
      check_query(v)
      set_query(v)
      v
    end
registry=(v)

[Source]

# File uri/generic.rb, line 455
    def registry=(v)
      check_registry(v)
      set_registry(v)
      v
    end
relative?()

Checks if URI is relative

[Source]

# File uri/generic.rb, line 606
    def relative?
      !absolute?
    end
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>

[Source]

# File uri/generic.rb, line 911
    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(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>

[Source]

# File uri/generic.rb, line 951
    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
scheme=(v)

[Source]

# File uri/generic.rb, line 242
    def scheme=(v)
      check_scheme(v)
      set_scheme(v)
      v
    end
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"]

[Source]

# File uri/generic.rb, line 1092
    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
to_s()

Constructs String from URI

[Source]

# File uri/generic.rb, line 997
    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
user()

[Source]

# File uri/generic.rb, line 365
    def user
      @user
    end
user=(user)

[Source]

# File uri/generic.rb, line 309
    def user=(user)
      check_user(user)
      set_user(user)
      user
    end
userinfo()

[Source]

# File uri/generic.rb, line 357
    def userinfo
      if !@password
        @user
      else
        @user + ':' + @password
      end
    end
userinfo=(userinfo)

Sets userinfo, argument is string like ‘name:pass’

[Source]

# File uri/generic.rb, line 300
    def userinfo=(userinfo)
      if userinfo.nil?
        return nil
      end
      check_userinfo(*userinfo)
      set_userinfo(*userinfo)
      userinfo
    end


Class: URI::HTTP

Class | URI::HTTP
In: | uri/http.rb
Parent: | Generic

RFC1738 section 3.3.

Methods

build new request_uri

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 of URI::HTTP with check. It is scheme, userinfo, host, port, path, query and fragment. It provided by an Array of a Hash.

[Source]

# File uri/http.rb, line 34
    def self.build(args)
      tmp = Util::make_components_hash(self, args)
      return super(tmp)
    end
new(*arg)

Description

Create a new URI::HTTP object from ``generic’’ components with no check.

[Source]

# File uri/http.rb, line 45
    def initialize(*arg)
      super(*arg)
    end

Public Instance methods

request_uri()

Description

Returns: path + ’?’ + query

[Source]

# File uri/http.rb, line 54
    def request_uri
      r = path_query
      if r[0] != ?/
        r = '/' + r
      end

      r
    end


Class: URI::HTTPS

Class | URI::HTTPS
In: | uri/https.rb
Parent: | HTTP

Constants

DEFAULT_PORT = 443


Class: URI::InvalidComponentError

Class | URI::InvalidComponentError
In: | uri/common.rb
Parent: | Error

Not a URI component.


Class: URI::InvalidURIError

Class | URI::InvalidURIError
In: | uri/common.rb
Parent: | Error

Not a URI.


Class: URI::LDAP

Class | URI::LDAP
In: | 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=

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)

[Source]

# File 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(*arg)

[Source]

# File uri/ldap.rb, line 59
    def initialize(*arg)
      super(*arg)

      if @fragment
        raise InvalidURIError, 'bad LDAP URL'
      end

      parse_dn
      parse_query
    end

Public Instance methods

attributes()

[Source]

# File uri/ldap.rb, line 120
    def attributes
      @attributes
    end
attributes=(val)

[Source]

# File uri/ldap.rb, line 131
    def attributes=(val)
      set_attributes(val)
      val
    end
dn()

[Source]

# File uri/ldap.rb, line 104
    def dn
      @dn
    end
dn=(val)

[Source]

# File uri/ldap.rb, line 115
    def dn=(val)
      set_dn(val)
      val
    end
extensions()

[Source]

# File uri/ldap.rb, line 168
    def extensions
      @extensions
    end
extensions=(val)

[Source]

# File uri/ldap.rb, line 179
    def extensions=(val)
      set_extensions(val)
      val
    end
filter()

[Source]

# File uri/ldap.rb, line 152
    def filter
      @filter
    end
filter=(val)

[Source]

# File uri/ldap.rb, line 163
    def filter=(val)
      set_filter(val)
      val
    end
hierarchical?()

[Source]

# File uri/ldap.rb, line 184
    def hierarchical?
      false
    end
scope()

[Source]

# File uri/ldap.rb, line 136
    def scope
      @scope
    end
scope=(val)

[Source]

# File uri/ldap.rb, line 147
    def scope=(val)
      set_scope(val)
      val
    end


Class: URI::MailTo

Class | URI::MailTo
In: | uri/mailto.rb
Parent: | Generic

RFC2368, The mailto URL scheme

Methods

build headers= new to= to_mailtext to_rfc822text to_s

Included Modules

REGEXP

Constants

DEFAULT_PORT | = | nil
COMPONENT | = | [ :scheme, :to, :headers ].freeze

Attributes

headers | [R]
to | [R]

Public Class methods

build(args)

Description

Creates a new URI::MailTo object from components of URI::MailTo with check. It is to and headers. It provided by an Array of a Hash. You can provide headers as String like "subject=subscribe&cc=addr" or Array like [["subject", "subscribe"], ["cc", "addr"]]

[Source]

# File uri/mailto.rb, line 70
    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(*arg)

Description

Creates a new URI::MailTo object from ``generic’’ components with no check. Because, this method is usually called from URI::parse and the method checks validity of each components.

[Source]

# File uri/mailto.rb, line 111
    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

Public Instance methods

headers=(v)

[Source]

# File uri/mailto.rb, line 182
    def headers=(v)
      check_headers(v)
      set_headers(v)
      v
    end
to=(v)

[Source]

# File uri/mailto.rb, line 152
    def to=(v)
      check_to(v)
      set_to(v)
      v
    end
to_mailtext()

Usage

  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"

[Source]

# File uri/mailto.rb, line 214
    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
to_rfc822text()

Alias for to_mailtext

to_s()

[Source]

# File uri/mailto.rb, line 188
    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


Module: URI::REGEXP

Module | URI::REGEXP
In: | uri/common.rb

Classes and Modules

Module URI::REGEXP::PATTERN


Module: URI::REGEXP::PATTERN

Module | URI::REGEXP::PATTERN
In: | uri/common.rb

Patterns used to parse URI’s


File: uri.rb

uri.rb

Path: | uri.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

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 © 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,v 1.8.2.2 2004/07/17 13:07:46 akira Exp $

See URI for documentation

Required files

uri/common uri/generic uri/ftp uri/http uri/https uri/ldap uri/mailto


File: common.rb

common.rb

Path: | uri/common.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

uri/common.rb

Author: | Akira Yamada <akira@ruby-lang.org>
Revision: | $Id: common.rb,v 1.11.2.7 2005/06/24 04:15:20 akira Exp $
License: | You can redistribute it and/or modify it under the same term as Ruby.


File: ftp.rb

ftp.rb

Path: | uri/ftp.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

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,v 1.3.2.1 2004/03/24 12:20:32 gsinclair Exp $

Required files

uri/generic


File: generic.rb

generic.rb

Path: | uri/generic.rb
Last Update: | Sat Oct 15 23:44:30 AUS Eastern Standard Time 2005

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,v 1.13.2.5 2005/06/24 04:15:20 akira Exp $

Required files

uri/common


File: http.rb

http.rb

Path: | uri/http.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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,v 1.2.2.1 2004/03/24 12:20:32 gsinclair Exp $

Required files

uri/generic


File: https.rb

https.rb

Path: | uri/https.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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,v 1.2.2.1 2004/03/24 12:20:32 gsinclair Exp $

Required files

uri/http


File: ldap.rb

ldap.rb

Path: | uri/ldap.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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,v 1.3.2.2 2004/07/17 13:07:46 akira Exp $

Required files

uri/generic


File: mailto.rb

mailto.rb

Path: | uri/mailto.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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,v 1.6.2.2 2004/05/13 04:03:33 akira Exp $

Required files

uri/generic


File: weakref.rb

weakref.rb

Path: | weakref.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

Weak Reference class that does not bother GCing.

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)

Required files

delegate thread


Class: WeakRef

Class | WeakRef
In: | weakref.rb
Parent: | Delegator

Methods

__getobj__ new weakref_alive?

Classes and Modules

Class WeakRef::RefError

Public Class methods

new(orig)

[Source]

# File weakref.rb, line 43
  def initialize(orig)
    super
    @__id = orig.__id__
    ObjectSpace.define_finalizer orig, @@final
    ObjectSpace.define_finalizer self, @@final
    __old_status = Thread.critical
    begin
      Thread.critical = true
      @@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

Public Instance methods

__getobj__()

[Source]

# File weakref.rb, line 59
  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
weakref_alive?()

[Source]

# File weakref.rb, line 70
  def weakref_alive?
    @@id_rev_map[self.__id__] == @__id
  end


Class: WeakRef::RefError

Class | WeakRef::RefError
In: | weakref.rb
Parent: | StandardError


File: webrick.rb

webrick.rb

Path: | webrick.rb
Last Update: | Thu Jul 24 02:51:36 AUS Eastern Standard Time 2003

WEBrick — WEB server toolkit.

Author: IPR — Internet Programming with Ruby — writers Copyright © 2000 TAKAHASHI Masayoshi, GOTOU YUUZOU Copyright © 2002 Internet Programming with Ruby writers. All rights reserved.

$IPR: webrick.rb,v 1.12 2002/10/01 17:16:31 gotoyuzo Exp $

Required files

webrick/compat.rb webrick/version.rb webrick/config.rb webrick/log.rb webrick/server.rb webrick/utils.rb webrick/accesslog webrick/htmlutils.rb webrick/httputils.rb webrick/cookie.rb webrick/httpversion.rb webrick/httpstatus.rb webrick/httprequest.rb webrick/httpresponse.rb webrick/httpserver.rb webrick/httpservlet.rb webrick/httpauth.rb


Module: Errno

Module | Errno
In: | webrick/compat.rb

compat.rb — cross platform compatibility

Author: IPR — Internet Programming with Ruby — writers Copyright © 2002 GOTOU Yuuzou Copyright © 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: | webrick/compat.rb
Parent: | SystemCallError


Class: Errno::ECONNRESET

Class | Errno::ECONNRESET
In: | webrick/compat.rb
Parent: | SystemCallError


Class: Errno::EPROTO

Class | Errno::EPROTO
In: | webrick/compat.rb
Parent: | SystemCallError


Module: WEBrick

Module | WEBrick
In: | webrick/version.rb webrick/utils.rb webrick/ssl.rb webrick/server.rb webrick/log.rb webrick/httpversion.rb webrick/httputils.rb webrick/httpstatus.rb webrick/httpservlet.rb webrick/httpservlet/prochandler.rb webrick/httpservlet/filehandler.rb webrick/httpservlet/erbhandler.rb webrick/httpservlet/cgihandler.rb webrick/httpservlet/abstract.rb webrick/httpserver.rb webrick/https.rb webrick/httpresponse.rb webrick/httprequest.rb webrick/httpproxy.rb webrick/httpauth.rb webrick/httpauth/userdb.rb webrick/httpauth/htpasswd.rb webrick/httpauth/htgroup.rb webrick/httpauth/htdigest.rb webrick/httpauth/digestauth.rb webrick/httpauth/basicauth.rb webrick/httpauth/authenticator.rb webrick/htmlutils.rb webrick/cookie.rb webrick/config.rb webrick/cgi.rb webrick/accesslog.rb

accesslog.rb — Access log handling utilities

Author: IPR — Internet Programming with Ruby — writers Copyright © 2002 keita yamaguchi Copyright © 2002 Internet Programming with Ruby writers

$IPR: accesslog.rb,v 1.1 2002/10/01 17:16:32 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

VERSION | = | "1.3.1"
CR | = | "\x0d"
LF | = | "\x0a"
CRLF | = | "\x0d\x0a"
NullReader | = | Object.new


Module: WEBrick::AccessLog

Module | WEBrick::AccessLog
In: | 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)

[Source]

# File 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
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

[Source]

# File 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


Class: WEBrick::AccessLog::AccessLogError

Class | WEBrick::AccessLog::AccessLogError
In: | webrick/accesslog.rb
Parent: | StandardError


Class: WEBrick::BasicLog

Class | WEBrick::BasicLog
In: | 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)

[Source]

# File 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

Public Instance methods

<<(obj)

[Source]

# File webrick/log.rb, line 44
    def <<(obj)
      log(INFO, obj.to_s)
    end
close()

[Source]

# File webrick/log.rb, line 32
    def close
      @log.close if @opened
      @log = nil
    end
debug(msg)

[Source]

# File webrick/log.rb, line 52
    def debug(msg) log(DEBUG, "DEBUG " << format(msg)); end
debug?()

[Source]

# File webrick/log.rb, line 58
    def debug?; @level >= DEBUG; end
error(msg)

[Source]

# File webrick/log.rb, line 49
    def error(msg) log(ERROR, "ERROR " << format(msg)); end
error?()

[Source]

# File webrick/log.rb, line 55
    def error?; @level >= ERROR; end
fatal(msg)

[Source]

# File webrick/log.rb, line 48
    def fatal(msg) log(FATAL, "FATAL " << format(msg)); end
fatal?()

[Source]

# File webrick/log.rb, line 54
    def fatal?; @level >= FATAL; end
info(msg)

[Source]

# File webrick/log.rb, line 51
    def info(msg)  log(INFO,  "INFO  " << format(msg)); end
info?()

[Source]

# File webrick/log.rb, line 57
    def info?;  @level >= INFO; end
log(level, data)

[Source]

# File webrick/log.rb, line 37
    def log(level, data)
      if @log && level <= @level
        data += "\n" if /\n\Z/ !~ data
        @log << data
      end
    end
warn(msg)

[Source]

# File webrick/log.rb, line 50
    def warn(msg)  log(WARN,  "WARN  " << format(msg)); end
warn?()

[Source]

# File webrick/log.rb, line 56
    def warn?;  @level >= WARN; end


Class: WEBrick::CGI

Class | WEBrick::CGI
In: | 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)

[Source]

# File 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

Public Instance methods

[](key)

[Source]

# File webrick/cgi.rb, line 44
    def [](key)
      @config[key]
    end
service(req, res)

[Source]

# File 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
start(env=ENV, stdin=$stdin, stdout=$stdout)

[Source]

# File 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


Class: WEBrick::CGI::Socket

Class | WEBrick::CGI::Socket
In: | 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)

[Source]

# File 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

Public Instance methods

<<(data)

[Source]

# File webrick/cgi.rb, line 212
      def <<(data)
        @out_port << data
      end
addr()

[Source]

# File webrick/cgi.rb, line 196
      def addr
        [nil, @server_port, @server_name, @server_addr]
      end
cert()

[Source]

# File 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
cipher()

[Source]

# File 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
each() {|line| ...}

[Source]

# File webrick/cgi.rb, line 208
      def each
        input.each{|line| yield(line) }
      end
gets(eol=LF)

[Source]

# File webrick/cgi.rb, line 200
      def gets(eol=LF)
        input.gets(eol)
      end
peer_cert()

[Source]

# File 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()

[Source]

# File 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
peeraddr()

[Source]

# File webrick/cgi.rb, line 192
      def peeraddr
        [nil, @remote_port, @remote_host, @remote_addr]
      end
read(size=nil)

[Source]

# File webrick/cgi.rb, line 204
      def read(size=nil)
        input.read(size)
      end


Module: WEBrick::Config

Module | WEBrick::Config
In: | webrick/ssl.rb webrick/https.rb webrick/config.rb

Constants

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"
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, }


Class: WEBrick::Cookie

Class | WEBrick::Cookie
In: | webrick/cookie.rb
Parent: | Object

Methods

expires expires= new parse 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

[Source]

# File 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
parse(str)

Cookie::parse()

  It parses Cookie field sent from the user agent.

[Source]

# File 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

Public Instance methods

expires()

[Source]

# File webrick/cookie.rb, line 36
    def expires
      @expires && Time.parse(@expires)
    end
expires=(t)

[Source]

# File webrick/cookie.rb, line 32
    def expires=(t)
      @expires = t && (t.is_a?(Time) ? t.httpdate : t.to_s)
    end
to_s()

[Source]

# File 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


Class: WEBrick::Daemon

Class | WEBrick::Daemon
In: | webrick/server.rb
Parent: | Object

Methods

start

Public Class methods

start() {|if block_given?| ...}

[Source]

# File 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


Class: WEBrick::GenericServer

Class | WEBrick::GenericServer
In: | webrick/ssl.rb webrick/server.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)

[Source]

# File 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

Public Instance methods

[](key)

[Source]

# File webrick/server.rb, line 70
    def [](key)
      @config[key]
    end
listen(address, port)

[Source]

# File webrick/server.rb, line 74
    def listen(address, port)
      @listeners += Utils::create_listeners(address, port, @logger)
    end
listen(address, port)

[Source]

# File 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
run(sock)

[Source]

# File webrick/server.rb, line 138
    def run(sock)
      @logger.fatal "run() must be provided by user."
    end
setup_ssl_context(config)

[Source]

# File 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
shutdown()

[Source]

# File 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
ssl_context()

[Source]

# File webrick/ssl.rb, line 82
    def ssl_context
      @ssl_context ||= nil
    end
start(&block)

[Source]

# File 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()

[Source]

# File webrick/server.rb, line 120
    def stop
      if @status == :Running
        @status = :Shutdown
      end
    end


Module: WEBrick::HTMLUtils

Module | WEBrick::HTMLUtils
In: | webrick/htmlutils.rb

Methods

escape

Public Instance methods

escape(string)

[Source]

# File 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


Module: WEBrick::HTTPAuth

Module | WEBrick::HTTPAuth
In: | webrick/httpauth.rb webrick/httpauth/userdb.rb webrick/httpauth/htpasswd.rb webrick/httpauth/htgroup.rb webrick/httpauth/htdigest.rb webrick/httpauth/digestauth.rb webrick/httpauth/basicauth.rb webrick/httpauth/authenticator.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)

[Source]

# File 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(req, res, realm, &block)

[Source]

# File 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(req, res, realm, &block)

[Source]

# File 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


Module: WEBrick::HTTPAuth::Authenticator

Module | WEBrick::HTTPAuth::Authenticator
In: | 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: | 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)

[Source]

# File webrick/httpauth/basicauth.rb, line 21
      def self.make_passwd(realm, user, pass)
        pass ||= ""
        pass.crypt(Utils::random_string(2))
      end
new(config, default=Config::BasicAuth)

[Source]

# File webrick/httpauth/basicauth.rb, line 28
      def initialize(config, default=Config::BasicAuth)
        check_init(config)
        @config = default.dup.update(config)
      end

Public Instance methods

authenticate(req, res)

[Source]

# File 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(req, res)

[Source]

# File webrick/httpauth/basicauth.rb, line 55
      def challenge(req, res)
        res[@response_field] = "#{@auth_scheme} realm=\"#{@realm}\""
        raise @auth_exception
      end


Class: WEBrick::HTTPAuth::DigestAuth

Class | WEBrick::HTTPAuth::DigestAuth
In: | 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)

[Source]

# File webrick/httpauth/digestauth.rb, line 29
      def self.make_passwd(realm, user, pass)
        pass ||= ""
        Digest::MD5::hexdigest([user, realm, pass].join(":"))
      end
new(config, default=Config::DigestAuth)

[Source]

# File 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

Public Instance methods

authenticate(req, res)

[Source]

# File 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(req, res, stale=false)

[Source]

# File 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


Class: WEBrick::HTTPAuth::Htdigest

Class | WEBrick::HTTPAuth::Htdigest
In: | 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)

[Source]

# File 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

Public Instance methods

delete_passwd(realm, user)

[Source]

# File webrick/httpauth/htdigest.rb, line 75
      def delete_passwd(realm, user)
        if hash = @digest[realm]
          hash.delete(user)
        end
      end
each() {|[user, realm, hash[user]]| ...}

[Source]

# File 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
flush(output=nil)

[Source]

# File 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(realm, user, reload_db)

[Source]

# File 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
reload()

[Source]

# File 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
set_passwd(realm, user, pass)

[Source]

# File 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


Class: WEBrick::HTTPAuth::Htgroup

Class | WEBrick::HTTPAuth::Htgroup
In: | webrick/httpauth/htgroup.rb
Parent: | Object

Methods

add flush members new reload

Public Class methods

new(path)

[Source]

# File 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

Public Instance methods

add(group, members)

[Source]

# File webrick/httpauth/htgroup.rb, line 56
      def add(group, members)
        @group[group] = members(group) | members
      end
flush(output=nil)

[Source]

# File 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(group)

[Source]

# File webrick/httpauth/htgroup.rb, line 51
      def members(group)
        reload
        @group[group] || []
      end
reload()

[Source]

# File 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


Class: WEBrick::HTTPAuth::Htpasswd

Class | WEBrick::HTTPAuth::Htpasswd
In: | 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)

[Source]

# File 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

Public Instance methods

delete_passwd(realm, user)

[Source]

# File webrick/httpauth/htpasswd.rb, line 72
      def delete_passwd(realm, user)
        @passwd.delete(user)
      end
each() {|[user, @passwd[user]]| ...}

[Source]

# File webrick/httpauth/htpasswd.rb, line 76
      def each
        @passwd.keys.sort.each{|user|
          yield([user, @passwd[user]])
        }
      end
flush(output=nil)

[Source]

# File 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(realm, user, reload_db)

[Source]

# File webrick/httpauth/htpasswd.rb, line 63
      def get_passwd(realm, user, reload_db)
        reload() if reload_db
        @passwd[user]
      end
reload()

[Source]

# File 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
set_passwd(realm, user, pass)

[Source]

# File webrick/httpauth/htpasswd.rb, line 68
      def set_passwd(realm, user, pass)
        @passwd[user] = make_passwd(realm, user, pass)
      end


Module: WEBrick::HTTPAuth::ProxyAuthenticator

Module | WEBrick::HTTPAuth::ProxyAuthenticator
In: | 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: | webrick/httpauth/basicauth.rb
Parent: | BasicAuth

Included Modules

ProxyAuthenticator


Class: WEBrick::HTTPAuth::ProxyDigestAuth

Class | WEBrick::HTTPAuth::ProxyDigestAuth
In: | webrick/httpauth/digestauth.rb
Parent: | DigestAuth

Methods

check_uri

Included Modules

ProxyAuthenticator

Public Instance methods

check_uri(req, auth_req)

[Source]

# File webrick/httpauth/digestauth.rb, line 338
      def check_uri(req, auth_req)
        return true
      end


Module: WEBrick::HTTPAuth::UserDB

Module | WEBrick::HTTPAuth::UserDB
In: | 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)

[Source]

# File 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
make_passwd(realm, user, pass)

[Source]

# File webrick/httpauth/userdb.rb, line 15
      def make_passwd(realm, user, pass)
        @auth_type::make_passwd(realm, user, pass)
      end
set_passwd(realm, user, pass)

[Source]

# File webrick/httpauth/userdb.rb, line 19
      def set_passwd(realm, user, pass)
        self[user] = pass
      end


Class: WEBrick::HTTPProxyServer

Class | WEBrick::HTTPProxyServer
In: | 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)

[Source]

# File webrick/httpproxy.rb, line 27
    def initialize(config)
      super
      c = @config
      @via = "#{c[:HTTPVersion]} #{c[:ServerName]}:#{c[:Port]}"
    end

Public Instance methods

choose_header(src, dst)

[Source]

# File 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
do_OPTIONS(req, res)

[Source]

# File webrick/httpproxy.rb, line 250
    def do_OPTIONS(req, res)
      res['allow'] = "GET,HEAD,POST,OPTIONS,CONNECT"
    end
proxy_auth(req, res)

[Source]

# File 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
proxy_connect(req, res)

[Source]

# File 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
proxy_service(req, res)

[Source]

# File 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_uri(req, res)

[Source]

# File webrick/httpproxy.rb, line 98
    def proxy_uri(req, res)
      @config[:ProxyURI]
    end
service(req, res)

[Source]

# File 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
set_cookie(src, dst)

Net::HTTP is stupid about the multiple header fields. Here is workaround:

[Source]

# File 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(h)

[Source]

# File 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
split_field(f)

[Source]

# File webrick/httpproxy.rb, line 54
    def split_field(f) f ? f.split(/,\s+/).collect{|i| i.downcase } : [] end


Class: WEBrick::HTTPRequest

Class | WEBrick::HTTPRequest
In: | webrick/https.rb webrick/httprequest.rb
Parent: | Object

Methods

[] body content_length content_type each fixup keep_alive? meta_vars meta_vars new parse parse parse_uri query to_s

Constants

BODY_CONTAINABLE_METHODS | = | [ "POST", "PUT" ]
BUFSIZE | = | 1024*4

External Aliases

parse | -> | orig_parse
parse_uri | -> | orig_parse_uri
meta_vars | -> | orig_meta_vars

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)

[Source]

# File 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

Public Instance methods

[](header_name)

[Source]

# File webrick/httprequest.rb, line 145
    def [](header_name)
      if @header
        value = @header[header_name.downcase]
        value.empty? ? nil : value.join(", ")
      end
    end
body(&block)

[Source]

# File webrick/httprequest.rb, line 124
    def body(&block)
      block ||= Proc.new{|chunk| @body << chunk }
      read_body(@socket, block)
      @body.empty? ? nil : @body
    end
content_length()

[Source]

# File webrick/httprequest.rb, line 137
    def content_length
      return Integer(self['content-length'])
    end
content_type()

[Source]

# File webrick/httprequest.rb, line 141
    def content_type
      return self['content-type']
    end
each() {|k, value.empty? ? nil : value.join(", ")| ...}

[Source]

# File webrick/httprequest.rb, line 152
    def each
      @header.each{|k, v|
        value = @header[k]
        yield(k, value.empty? ? nil : value.join(", "))
      }
    end
fixup()

[Source]

# File 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
keep_alive?()

[Source]

# File webrick/httprequest.rb, line 159
    def keep_alive?
      @keep_alive
    end
meta_vars()

[Source]

# File 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
meta_vars()

[Source]

# File 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(socket=nil)

[Source]

# File 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(socket=nil)

[Source]

# File 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
parse_uri(str, scheme="https")

[Source]

# File 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
query()

[Source]

# File webrick/httprequest.rb, line 130
    def query
      unless @query
        parse_query()
      end
      @query
    end
to_s()

[Source]

# File 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


Class: WEBrick::HTTPResponse

Class | WEBrick::HTTPResponse
In: | 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)

[Source]

# File 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

Public Instance methods

[](field)

[Source]

# File webrick/httpresponse.rb, line 58
    def [](field)
      @header[field.downcase]
    end
[]=(field, value)

[Source]

# File webrick/httpresponse.rb, line 62
    def []=(field, value)
      @header[field.downcase] = value.to_s
    end
chunked=(val)

[Source]

# File webrick/httpresponse.rb, line 92
    def chunked=(val)
      @chunked = val ? true : false
    end
chunked?()

[Source]

# File webrick/httpresponse.rb, line 88
    def chunked?
      @chunked
    end
content_length()

[Source]

# File webrick/httpresponse.rb, line 66
    def content_length
      if len = self['content-length']
        return Integer(len)
      end
    end
content_length=(len)

[Source]

# File webrick/httpresponse.rb, line 72
    def content_length=(len)
      self['content-length'] = len.to_s
    end
content_type()

[Source]

# File webrick/httpresponse.rb, line 76
    def content_type
      self['content-type']
    end
content_type=(type)

[Source]

# File webrick/httpresponse.rb, line 80
    def content_type=(type)
      self['content-type'] = type
    end
each() {|k, v| ...}

[Source]

# File webrick/httpresponse.rb, line 84
    def each
      @header.each{|k, v|  yield(k, v) }
    end
keep_alive?()

[Source]

# File webrick/httpresponse.rb, line 96
    def keep_alive?
      @keep_alive
    end
send_body(socket)

[Source]

# File 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
send_header(socket)

[Source]

# File 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_response(socket)

[Source]

# File 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
set_error(ex, backtrace=false)

[Source]

# File 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
set_redirect(status, url)

[Source]

# File 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
setup_header()

[Source]

# File 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
status=(status)

[Source]

# File webrick/httpresponse.rb, line 53
    def status=(status)
      @status = status
      @reason_phrase = HTTPStatus::reason_phrase(status)
    end
status_line()

[Source]

# File webrick/httpresponse.rb, line 49
    def status_line
      "HTTP/#@http_version #@status #@reason_phrase #{CRLF}"
    end
to_s()

[Source]

# File webrick/httpresponse.rb, line 191
    def to_s
      ret = ""
      send_response(ret)
      ret
    end


Class: WEBrick::HTTPServer

Class | WEBrick::HTTPServer
In: | 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)

[Source]

# File 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

Public Instance methods

access_log(config, req, res)

[Source]

# File 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
do_OPTIONS(req, res)

[Source]

# File webrick/httpserver.rb, line 107
    def do_OPTIONS(req, res)
      res["allow"] = "GET,HEAD,POST,OPTIONS"
    end
lookup_server(req)

[Source]

# File 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
mount(dir, servlet, *options)

[Source]

# File 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(dir, proc=nil, &block)

[Source]

# File 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
run(sock)

[Source]

# File 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
search_servlet(path)

[Source]

# File 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
service(req, res)

[Source]

# File 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
umount(dir)

Alias for unmount

unmount(dir)

[Source]

# File webrick/httpserver.rb, line 122
    def unmount(dir)
      @logger.debug(sprintf("unmount %s.", inspect, dir))
      @mount_tab.delete(dir)
    end
virtual_host(server)

[Source]

# File 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


Class: WEBrick::HTTPServer::MountTable

Class | WEBrick::HTTPServer::MountTable
In: | webrick/httpserver.rb
Parent: | Object

Methods

[] []= delete new scan

Public Class methods

new()

[Source]

# File webrick/httpserver.rb, line 164
      def initialize
        @tab = Hash.new
        compile
      end

Public Instance methods

[](dir)

[Source]

# File webrick/httpserver.rb, line 169
      def [](dir)
        dir = normalize(dir)
        @tab[dir]
      end
[]=(dir, val)

[Source]

# File webrick/httpserver.rb, line 174
      def []=(dir, val)
        dir = normalize(dir)
        @tab[dir] = val
        compile
        val
      end
delete(dir)

[Source]

# File webrick/httpserver.rb, line 181
      def delete(dir)
        dir = normalize(dir)
        res = @tab.delete(dir)
        compile
        res
      end
scan(path)

[Source]

# File webrick/httpserver.rb, line 188
      def scan(path)
        @scanner =~ path
        [ $&, $' ]
      end


Class: WEBrick::HTTPServerError

Class | WEBrick::HTTPServerError
In: | webrick/httpserver.rb
Parent: | ServerError


Module: WEBrick::HTTPServlet

Module | WEBrick::HTTPServlet
In: | webrick/httpservlet.rb webrick/httpservlet/prochandler.rb webrick/httpservlet/filehandler.rb webrick/httpservlet/erbhandler.rb webrick/httpservlet/cgihandler.rb webrick/httpservlet/abstract.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: | webrick/httpservlet/abstract.rb
Parent: | Object

Methods

do_GET do_HEAD do_OPTIONS get_instance new service

Public Class methods

get_instance(config, *options)

[Source]

# File webrick/httpservlet/abstract.rb, line 22
      def self.get_instance(config, *options)
        self.new(config, *options)
      end
new(server, *options)

[Source]

# File webrick/httpservlet/abstract.rb, line 26
      def initialize(server, *options)
        @server = @config = server
        @logger = @server[:Logger]
        @options = options
      end

Public Instance methods

do_GET(req, res)

[Source]

# File webrick/httpservlet/abstract.rb, line 42
      def do_GET(req, res)
        raise HTTPStatus::NotFound, "not found."
      end
do_HEAD(req, res)

[Source]

# File webrick/httpservlet/abstract.rb, line 46
      def do_HEAD(req, res)
        do_GET(req, res)
      end
do_OPTIONS(req, res)

[Source]

# File 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
service(req, res)

[Source]

# File 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


Class: WEBrick::HTTPServlet::CGIHandler

Class | WEBrick::HTTPServlet::CGIHandler
In: | 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)

[Source]

# File webrick/httpservlet/cgihandler.rb, line 25
      def initialize(server, name)
        super
        @script_filename = name
        @tempdir = server[:TempDir]
        @cgicmd = "#{CGIRunner} #{server[:CGIInterpreter]}"
      end

Public Instance methods

do_GET(req, res)

[Source]

# File 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
          header.each{|key, val| res[key] = val.join(", ") }
        rescue => ex
          raise HTTPStatus::InternalServerError, ex.message
        end
        res.body = body
      end
do_POST(req, res)

Alias for do_GET


Class: WEBrick::HTTPServlet::DefaultFileHandler

Class | WEBrick::HTTPServlet::DefaultFileHandler
In: | webrick/httpservlet/filehandler.rb
Parent: | AbstractServlet

Methods

do_GET make_partial_content new not_modified? prepare_range

Public Class methods

new(server, local_path)

[Source]

# File webrick/httpservlet/filehandler.rb, line 22
      def initialize(server, local_path)
        super
        @local_path = local_path
      end

Public Instance methods

do_GET(req, res)

[Source]

# File 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
make_partial_content(req, res, filename, filesize)

[Source]

# File 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
not_modified?(req, res, mtime, etag)

[Source]

# File 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_valie(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
prepare_range(range, filesize)

[Source]

# File 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


Class: WEBrick::HTTPServlet::ERBHandler

Class | WEBrick::HTTPServlet::ERBHandler
In: | webrick/httpservlet/erbhandler.rb
Parent: | AbstractServlet

Methods

do_GET do_POST new

Public Class methods

new(server, name)

[Source]

# File webrick/httpservlet/erbhandler.rb, line 19
      def initialize(server, name)
        super
        @script_filename = name
      end

Public Instance methods

do_GET(req, res)

[Source]

# File 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
do_POST(req, res)

Alias for do_GET


Class: WEBrick::HTTPServlet::FileHandler

Class | WEBrick::HTTPServlet::FileHandler
In: | 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)

[Source]

# File webrick/httpservlet/filehandler.rb, line 131
      def self.add_handler(suffix, handler)
        HandlerTable[suffix] = handler
      end
new(server, root, options={}, default=Config::FileHandler)

[Source]

# File 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
remove_handler(suffix)

[Source]

# File webrick/httpservlet/filehandler.rb, line 135
      def self.remove_handler(suffix)
        HandlerTable.delete(suffix)
      end

Public Instance methods

do_GET(req, res)

[Source]

# File webrick/httpservlet/filehandler.rb, line 169
      def do_GET(req, res)
        unless exec_handler(req, res)
          set_dir_list(req, res)
        end
      end
do_OPTIONS(req, res)

[Source]

# File webrick/httpservlet/filehandler.rb, line 181
      def do_OPTIONS(req, res)
        unless exec_handler(req, res)
          super(req, res)
        end
      end
do_POST(req, res)

[Source]

# File 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
service(req, res)

[Source]

# File 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


Class: WEBrick::HTTPServlet::HTTPServletError

Class | WEBrick::HTTPServlet::HTTPServletError
In: | webrick/httpservlet/abstract.rb
Parent: | StandardError


Class: WEBrick::HTTPServlet::ProcHandler

Class | WEBrick::HTTPServlet::ProcHandler
In: | webrick/httpservlet/prochandler.rb
Parent: | AbstractServlet

Methods

do_GET do_POST get_instance new

Public Class methods

new(proc)

[Source]

# File webrick/httpservlet/prochandler.rb, line 21
      def initialize(proc)
        @proc = proc
      end

Public Instance methods

do_GET(request, response)

[Source]

# File webrick/httpservlet/prochandler.rb, line 25
      def do_GET(request, response)
        @proc.call(request, response)
      end
do_POST(request, response)

Alias for do_GET

get_instance(server, *options)

[Source]

# File webrick/httpservlet/prochandler.rb, line 17
      def get_instance(server, *options)
        self
      end


Module: WEBrick::HTTPStatus

Module | WEBrick::HTTPStatus
In: | 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)

[Source]

# File webrick/httpstatus.rb, line 118
    def self.[](code)
      CodeToError[code]
    end

Public Instance methods

client_error?(code)

[Source]

# File webrick/httpstatus.rb, line 111
    def client_error?(code)
      code.to_i >= 400 and code.to_i < 500
    end
error?(code)

[Source]

# File webrick/httpstatus.rb, line 108
    def error?(code)
      code.to_i >= 400 and code.to_i < 600
    end
info?(code)

[Source]

# File webrick/httpstatus.rb, line 99
    def info?(code)
      code.to_i >= 100 and code.to_i < 200
    end
reason_phrase(code)

[Source]

# File webrick/httpstatus.rb, line 96
    def reason_phrase(code)
      StatusMessage[code.to_i]
    end
redirect?(code)

[Source]

# File webrick/httpstatus.rb, line 105
    def redirect?(code)
      code.to_i >= 300 and code.to_i < 400
    end
server_error?(code)

[Source]

# File webrick/httpstatus.rb, line 114
    def server_error?(code)
      code.to_i >= 500 and code.to_i < 600
    end
success?(code)

[Source]

# File webrick/httpstatus.rb, line 102
    def success?(code)
      code.to_i >= 200 and code.to_i < 300
    end


Class: WEBrick::HTTPStatus::ClientError

Class | WEBrick::HTTPStatus::ClientError
In: | webrick/httpstatus.rb
Parent: | Error


Class: WEBrick::HTTPStatus::EOFError

Class | WEBrick::HTTPStatus::EOFError
In: | webrick/httpstatus.rb
Parent: | StandardError


Class: WEBrick::HTTPStatus::Error

Class | WEBrick::HTTPStatus::Error
In: | webrick/httpstatus.rb
Parent: | Status


Class: WEBrick::HTTPStatus::Info

Class | WEBrick::HTTPStatus::Info
In: | webrick/httpstatus.rb
Parent: | Status


Class: WEBrick::HTTPStatus::Redirect

Class | WEBrick::HTTPStatus::Redirect
In: | webrick/httpstatus.rb
Parent: | Status


Class: WEBrick::HTTPStatus::ServerError

Class | WEBrick::HTTPStatus::ServerError
In: | webrick/httpstatus.rb
Parent: | Error


Class: WEBrick::HTTPStatus::Status

Class | WEBrick::HTTPStatus::Status
In: | webrick/httpstatus.rb
Parent: | StandardError


Class: WEBrick::HTTPStatus::Success

Class | WEBrick::HTTPStatus::Success
In: | webrick/httpstatus.rb
Parent: | Status


Module: WEBrick::HTTPUtils

Module | WEBrick::HTTPUtils
In: | 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)

[Source]

# File webrick/httputils.rb, line 360
    def _escape(str, regex) str.gsub(regex){ "%%%02X" % $1[0] } end
_make_regex(str)

[Source]

# File 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!(str)

[Source]

# File 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
_unescape(str, regex)

[Source]

# File webrick/httputils.rb, line 361
    def _unescape(str, regex) str.gsub(regex){ $1.hex.chr } end
dequote(str)

[Source]

# File webrick/httputils.rb, line 197
    def dequote(str)
      ret = (/\A"(.*)"\Z/ =~ str) ? $1 : str.dup
      ret.gsub!(/\\(.)/, "\\1")
      ret
    end
escape(str)

[Source]

# File webrick/httputils.rb, line 369
    def escape(str)
      _escape(str, UNESCAPED)
    end
escape8bit(str)

[Source]

# File webrick/httputils.rb, line 395
    def escape8bit(str)
      _escape(str, NONASCII)
    end
escape_form(str)

[Source]

# File webrick/httputils.rb, line 377
    def escape_form(str)
      ret = _escape(str, UNESCAPED_FORM)
      ret.gsub!(/ /, "+")
      ret
    end
escape_path(str)

[Source]

# File webrick/httputils.rb, line 387
    def escape_path(str)
      result = ""
      str.scan(%r{/([^/]*)}).each{|i|
        result << "/" << _escape(i[0], UNESCAPED_PCHAR)
      }
      return result
    end
load_mime_types(file)

Load Apache compatible mime.types file.

[Source]

# File 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(filename, mime_tab)

[Source]

# File 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
normalize_path(path)

[Source]

# File 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
parse_form_data(io, boundary)

[Source]

# File 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
parse_header(raw)

[Source]

# File 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
parse_query(str)

[Source]

# File 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_qvalues(value)

[Source]

# File 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
parse_range_header(ranges_specifier)

[Source]

# File 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
quote(str)

[Source]

# File webrick/httputils.rb, line 204
    def quote(str)
      '"' << str.gsub(/[\\\"]/o, "\\\1") << '"'
    end
split_header_value(str)

[Source]

# File webrick/httputils.rb, line 156
    def split_header_value(str)
      str.scan(/((?:"(?:\\.|[^"])+?"|[^",]+)+)
                (?:,\s*|\Z)/xn).collect{|v| v[0] }
    end
unescape(str)

[Source]

# File webrick/httputils.rb, line 373
    def unescape(str)
      _unescape(str, ESCAPED)
    end
unescape_form(str)

[Source]

# File webrick/httputils.rb, line 383
    def unescape_form(str)
      _unescape(str.gsub(/\+/, " "), ESCAPED)
    end


Class: WEBrick::HTTPUtils::FormData

Class | WEBrick::HTTPUtils::FormData
In: | 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]

Public Class methods

new(*args)

[Source]

# File 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

Public Instance methods

<<(str)

[Source]

# File 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
[](*key)

[Source]

# File webrick/httputils.rb, line 234
      def [](*key)
        begin
          @header[key[0].downcase].join(", ")
        rescue StandardError, NameError
          super
        end
      end
append_data(data)

[Source]

# File 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() {|tmp| ...}

[Source]

# File 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()

[Source]

# File webrick/httputils.rb, line 278
      def list
        ret = []
        each_data{|data|
          ret << data.to_s
        }
        ret
      end
to_ary()

Alias for list

to_s()

[Source]

# File webrick/httputils.rb, line 288
      def to_s
        String.new(self)
      end


Class: WEBrick::HTTPVersion

Class | WEBrick::HTTPVersion
In: | webrick/httpversion.rb
Parent: | Object

Methods

<=> convert new to_s

Included Modules

Comparable

Attributes

major | [RW]
minor | [RW]

Public Class methods

convert(version)

[Source]

# File webrick/httpversion.rb, line 16
    def self.convert(version)
      version.is_a?(self) ? version : new(version)
    end
new(version)

[Source]

# File 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

Public Instance methods

<=>(other)

[Source]

# File 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()

[Source]

# File webrick/httpversion.rb, line 45
    def to_s
      format("%d.%d", @major, @minor)
    end


Class: WEBrick::Log

Class | WEBrick::Log
In: | webrick/log.rb
Parent: | BasicLog

Methods

log new

Attributes

time_format [RW]

Public Class methods

new(log_file=nil, level=nil)

[Source]

# File 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

Public Instance methods

log(level, data)

[Source]

# File webrick/log.rb, line 82
    def log(level, data)
      tmp = Time.now.strftime(@time_format)
      tmp << " " << data
      super(level, tmp)
    end


Class: WEBrick::ServerError

Class | WEBrick::ServerError
In: | webrick/server.rb
Parent: | StandardError


Class: WEBrick::SimpleServer

Class | WEBrick::SimpleServer
In: | webrick/server.rb
Parent: | Object

Methods

start

Public Class methods

start() {|| ...}

[Source]

# File webrick/server.rb, line 22
    def SimpleServer.start
      yield
    end


Module: WEBrick::Utils

Module | WEBrick::Utils
In: | webrick/utils.rb 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)

[Source]

# File 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
create_self_signed_cert(bits, cn, comment)

[Source]

# File 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
getservername()

[Source]

# File webrick/utils.rb, line 49
    def getservername
      host = Socket::gethostname
      begin
        Socket::gethostbyname(host)[0]
      rescue
        host
      end
    end
random_string(len)

[Source]

# File 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
set_close_on_exec(io)

[Source]

# File webrick/utils.rb, line 30
    def set_close_on_exec(io)
      if defined?(Fcntl::FD_CLOEXEC)
        io.fcntl(Fcntl::FD_CLOEXEC, 1)
      end
    end
set_non_blocking(io)

[Source]

# File 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
su(user)

[Source]

# File 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


File: accesslog.rb

accesslog.rb

Path: | webrick/accesslog.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

accesslog.rb — Access log handling utilities

Author: IPR — Internet Programming with Ruby — writers Copyright © 2002 keita yamaguchi Copyright © 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: | webrick/cgi.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

cgi.rb — Yet another CGI library

Author: IPR — Internet Programming with Ruby — writers Copyright © 2003 Internet Programming with Ruby writers. All rights reserved.

$Id: cgi.rb,v 1.4.2.9 2005/09/28 06:16:59 gotoyuzo Exp $

Required files

webrick/httprequest webrick/httpresponse webrick/config stringio


File: compat.rb

compat.rb

Path: | webrick/compat.rb
Last Update: | Tue Aug 19 16:00:36 AUS Eastern Standard Time 2003

compat.rb — cross platform compatibility

Author: IPR — Internet Programming with Ruby — writers Copyright © 2002 GOTOU Yuuzou Copyright © 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: | webrick/config.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

config.rb — Default configurations.

Author: IPR — Internet Programming with Ruby — writers Copyright © 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright © 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: | webrick/cookie.rb
Last Update: | Thu Jul 24 02:51:36 AUS Eastern Standard Time 2003

cookie.rb — Cookie class

Author: IPR — Internet Programming with Ruby — writers Copyright © 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright © 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: | webrick/htmlutils.rb
Last Update: | Thu Jul 24 02:51:36 AUS Eastern Standard Time 2003

htmlutils.rb — HTMLUtils Module

Author: IPR — Internet Programming with Ruby — writers Copyright © 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright © 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: | webrick/httpauth.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

httpauth.rb — HTTP access authentication

Author: IPR — Internet Programming with Ruby — writers Copyright © 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright © 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: authenticator.rb

authenticator.rb

Path: | webrick/httpauth/authenticator.rb
Last Update: | Thu Jul 24 02:51:36 AUS Eastern Standard Time 2003

httpauth/authenticator.rb — Authenticator mix-in module.

Author: IPR — Internet Programming with Ruby — writers Copyright © 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: | webrick/httpauth/basicauth.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

httpauth/basicauth.rb — HTTP basic access authentication

Author: IPR — Internet Programming with Ruby — writers Copyright © 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: | webrick/httpauth/digestauth.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

httpauth/digestauth.rb — HTTP digest access authentication

Author: IPR — Internet Programming with Ruby — writers Copyright © 2003 Internet Programming with Ruby writers. Copyright © 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: | webrick/httpauth/htdigest.rb
Last Update: | Thu Jul 24 02:51:36 AUS Eastern Standard Time 2003

httpauth/htdigest.rb — Apache compatible htdigest file

Author: IPR — Internet Programming with Ruby — writers Copyright © 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: | webrick/httpauth/htgroup.rb
Last Update: | Thu Jul 24 02:51:36 AUS Eastern Standard Time 2003

httpauth/htgroup.rb — Apache compatible htgroup file

Author: IPR — Internet Programming with Ruby — writers Copyright © 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: | webrick/httpauth/htpasswd.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

httpauth/htpasswd — Apache compatible htpasswd file

Author: IPR — Internet Programming with Ruby — writers Copyright © 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: | webrick/httpauth/userdb.rb
Last Update: | Thu Jul 24 02:51:36 AUS Eastern Standard Time 2003

httpauth/userdb.rb — UserDB mix-in module.

Author: IPR — Internet Programming with Ruby — writers Copyright © 2003 Internet Programming with Ruby writers. All rights reserved.

$IPR: userdb.rb,v 1.2 2003/02/20 07:15:48 gotoyuzo Exp $


File: httpproxy.rb

httpproxy.rb

Path: | webrick/httpproxy.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

httpproxy.rb — HTTPProxy Class

Author: IPR — Internet Programming with Ruby — writers Copyright © 2002 GOTO Kentaro Copyright © 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: | webrick/httprequest.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

httprequest.rb — HTTPRequest Class

Author: IPR — Internet Programming with Ruby — writers Copyright © 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright © 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: | webrick/httpresponse.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

httpresponse.rb — HTTPResponse Class

Author: IPR — Internet Programming with Ruby — writers Copyright © 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright © 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: | webrick/https.rb
Last Update: | Tue Dec 23 07:13:06 AUS Eastern Daylight Time 2003

https.rb — SSL/TLS enhancement for HTTPServer

Author: IPR — Internet Programming with Ruby — writers Copyright © 2001 GOTOU Yuuzou Copyright © 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: | webrick/httpserver.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

httpserver.rb — HTTPServer Class

Author: IPR — Internet Programming with Ruby — writers Copyright © 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright © 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: | webrick/httpservlet.rb
Last Update: | Thu Jul 24 02:51:36 AUS Eastern Standard Time 2003

httpservlet.rb — HTTPServlet Utility File

Author: IPR — Internet Programming with Ruby — writers Copyright © 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright © 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: abstract.rb

abstract.rb

Path: | webrick/httpservlet/abstract.rb
Last Update: | Thu Jul 24 02:51:36 AUS Eastern Standard Time 2003

httpservlet.rb — HTTPServlet Module

Author: IPR — Internet Programming with Ruby — writers Copyright © 2000 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright © 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: | webrick/httpservlet/cgi_runner.rb
Last Update: | Thu Jul 24 02:51:36 AUS Eastern Standard Time 2003

cgi_runner.rb — CGI launcher.

Author: IPR — Internet Programming with Ruby — writers Copyright © 2000 TAKAHASHI Masayoshi, GOTOU YUUZOU Copyright © 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 © 2000 TAKAHASHI Masayoshi, GOTOU YUUZOU Copyright © 2002 Internet Programming with Ruby writers. All rights reserved.

$IPR: cgi_runner.rb,v 1.9 2002/09/25 11:33:15 gotoyuzo Exp $

[Source]

# File 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: cgihandler.rb

cgihandler.rb

Path: | webrick/httpservlet/cgihandler.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

cgihandler.rb — CGIHandler Class

Author: IPR — Internet Programming with Ruby — writers Copyright © 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright © 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: | webrick/httpservlet/erbhandler.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

erbhandler.rb — ERBHandler Class

Author: IPR — Internet Programming with Ruby — writers Copyright © 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright © 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: | webrick/httpservlet/filehandler.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

filehandler.rb — FileHandler Module

Author: IPR — Internet Programming with Ruby — writers Copyright © 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright © 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: | webrick/httpservlet/prochandler.rb
Last Update: | Thu Jul 24 02:51:36 AUS Eastern Standard Time 2003

prochandler.rb — ProcHandler Class

Author: IPR — Internet Programming with Ruby — writers Copyright © 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright © 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


File: httpstatus.rb

httpstatus.rb

Path: | webrick/httpstatus.rb
Last Update: | Thu Jul 24 02:51:36 AUS Eastern Standard Time 2003

httpstatus.rb — HTTPStatus Class

Author: IPR — Internet Programming with Ruby — writers Copyright © 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright © 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: | webrick/httputils.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

httputils.rb — HTTPUtils Module

Author: IPR — Internet Programming with Ruby — writers Copyright © 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright © 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: | webrick/httpversion.rb
Last Update: | Thu Jul 24 02:51:36 AUS Eastern Standard Time 2003

HTTPVersion.rb — presentation of HTTP version

Author: IPR — Internet Programming with Ruby — writers Copyright © 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: | webrick/log.rb
Last Update: | Fri Sep 19 02:09:02 AUS Eastern Standard Time 2003

log.rb — Log Class

Author: IPR — Internet Programming with Ruby — writers Copyright © 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright © 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: | webrick/server.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

server.rb — GenericServer Class

Author: IPR — Internet Programming with Ruby — writers Copyright © 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright © 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: | webrick/ssl.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

ssl.rb — SSL/TLS enhancement for GenericServer

Copyright © 2003 GOTOU Yuuzou All rights reserved.

$Id: ssl.rb,v 1.2.2.1 2005/01/18 06:03:43 gotoyuzo Exp $

Required files

webrick openssl


File: utils.rb

utils.rb

Path: | webrick/utils.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

utils.rb — Miscellaneous utilities

Author: IPR — Internet Programming with Ruby — writers Copyright © 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright © 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: | webrick/version.rb
Last Update: | Thu Jul 24 02:51:36 AUS Eastern Standard Time 2003

version.rb — version and release date

Author: IPR — Internet Programming with Ruby — writers Copyright © 2000 TAKAHASHI Masayoshi, GOTOU YUUZOU Copyright © 2003 Internet Programming with Ruby writers. All rights reserved.

$IPR: version.rb,v 1.74 2003/07/22 19:20:43 gotoyuzo Exp $


Class: Win32API

Class | Win32API
In: | Win32API/Win32API.c
Parent: | Object

Methods

Call call new

Public Class methods

new(p1, p2, p3, p4)

Public Instance methods

Call(...)

Alias for call

call(...)


Module: Win32

Module | Win32
In: | Win32API/lib/win32/resolv.rb Win32API/lib/win32/registry.rb

Classes and Modules

Module Win32::Resolv
Class Win32::Registry


Class: Win32::Registry

Class | Win32::Registry
In: | Win32API/lib/win32/registry.rb
Parent: | Object

Methods

[] []= _dump close create create created? delete delete_key delete_value each each_key each_value expand_environ flush info inspect keys name new open open open? read read_bin read_i read_s read_s_expand time2wtime type2name write write_bin write_i write_s wtime2time

Included Modules

Constants Enumerable

Classes and Modules

Module Win32::Registry::API
Module Win32::Registry::Constants
Class Win32::Registry::Error
Class Win32::Registry::PredefinedKey

Attributes

disposition | [R]
hkey | [R]
keyname | [R]
parent | [R]

Public Class methods

create(hkey, subkey, desired = KEY_ALL_ACCESS, opt = REG_OPTION_RESERVED) {|obj| ...}

[Source]

# File Win32API/lib/win32/registry.rb, line 541
    def self.create(hkey, subkey, desired = KEY_ALL_ACCESS, opt = REG_OPTION_RESERVED)
      newkey, disp = API.CreateKey(hkey.hkey, subkey, opt, desired)
      obj = new(newkey, hkey, subkey, disp)
      if block_given?
        begin
          yield obj
        ensure
          obj.close
        end
      else
        obj
      end
    end
expand_environ(str)

utility functions

[Source]

# File Win32API/lib/win32/registry.rb, line 495
    def self.expand_environ(str)
      str.gsub(/%([^%]+)%/) { ENV[$1] || $& }
    end
new(hkey, parent, keyname, disposition)

initialize

[Source]

# File Win32API/lib/win32/registry.rb, line 563
    def initialize(hkey, parent, keyname, disposition)
      @hkey = hkey
      @parent = parent
      @keyname = keyname
      @disposition = disposition
      @hkeyfinal = [ hkey ]
      ObjectSpace.define_finalizer self, @@final.call(@hkeyfinal)
    end
open(hkey, subkey, desired = KEY_READ, opt = REG_OPTION_RESERVED) {|obj| ...}

constructors

[Source]

# File Win32API/lib/win32/registry.rb, line 526
    def self.open(hkey, subkey, desired = KEY_READ, opt = REG_OPTION_RESERVED)
      subkey = subkey.chomp('\\')
      newkey = API.OpenKey(hkey.hkey, subkey, opt, desired)
      obj = new(newkey, hkey, subkey, REG_OPENED_EXISTING_KEY)
      if block_given?
        begin
          yield obj
        ensure
          obj.close
        end
      else
        obj
      end
    end
time2wtime(time)

[Source]

# File Win32API/lib/win32/registry.rb, line 517
    def self.time2wtime(time)
      time.to_i * 10000000 + 116444736000000000
    end
type2name(type)

[Source]

# File Win32API/lib/win32/registry.rb, line 509
    def self.type2name(type)
      @@type2name[type] || type.to_s
    end
wtime2time(wtime)

[Source]

# File Win32API/lib/win32/registry.rb, line 513
    def self.wtime2time(wtime)
      Time.at((wtime - 116444736000000000) / 10000000)
    end

Public Instance methods

[](name, *rtype)

[Source]

# File Win32API/lib/win32/registry.rb, line 690
    def [](name, *rtype)
      type, data = read(name, *rtype)
      case type
      when REG_SZ, REG_DWORD, REG_QWORD, REG_MULTI_SZ
        data
      when REG_EXPAND_SZ
        Registry.expand_environ(data)
      else
        raise TypeError, "Type #{type} is not supported."
      end
    end
[]=(name, rtype, value = nil)

[Source]

# File Win32API/lib/win32/registry.rb, line 746
    def []=(name, rtype, value = nil)
      if value
        write name, rtype, value
      else
        case value = rtype
        when Integer
          write name, REG_DWORD, value
        when String
          write name, REG_SZ, value
        when Array
          write name, REG_MULTI_SZ, value
        else
          raise TypeError, "Unexpected type #{value.class}"
        end
      end
      value
    end
_dump(depth)

marshalling

[Source]

# File Win32API/lib/win32/registry.rb, line 600
    def _dump(depth)
      raise TypeError, "can't dump Win32::Registry"
    end
close()

[Source]

# File Win32API/lib/win32/registry.rb, line 615
    def close
      API.CloseKey(@hkey)
      @hkey = @parent = @keyname = nil
      @hkeyfinal[0] = nil
    end
create(subkey, desired = KEY_ALL_ACCESS, opt = REG_OPTION_RESERVED, &blk)

[Source]

# File Win32API/lib/win32/registry.rb, line 611
    def create(subkey, desired = KEY_ALL_ACCESS, opt = REG_OPTION_RESERVED, &blk)
      self.class.create(self, subkey, desired, opt, &blk)
    end
created?()

attributes

[Source]

# File Win32API/lib/win32/registry.rb, line 576
    def created?
      @disposition == REG_CREATED_NEW_KEY
    end
delete(name)

Alias for delete_value

delete_key(name, recursive = false)

[Source]

# File Win32API/lib/win32/registry.rb, line 784
    def delete_key(name, recursive = false)
      if recursive
        open(name, KEY_ALL_ACCESS) do |reg|
          reg.keys.each do |key|
            begin
              reg.delete_key(key, true)
            rescue Error
              #
            end
          end
        end
        API.DeleteKey(@hkey, name)
      else
        begin
          API.EnumKey @hkey, 0
        rescue Error
          return API.DeleteKey(@hkey, name)
        end
        raise Error.new(5) ## ERROR_ACCESS_DENIED
      end
    end
delete_value(name)

delete

[Source]

# File Win32API/lib/win32/registry.rb, line 779
    def delete_value(name)
      API.DeleteValue(@hkey, name)
    end
each()

Alias for each_value

each_key() {|subkey, wtime| ...}

[Source]

# File Win32API/lib/win32/registry.rb, line 644
    def each_key
      index = 0
      while true
        begin
          subkey, wtime = API.EnumKey(@hkey, index)
        rescue Error
          break
        end
        yield subkey, wtime
        index += 1
      end
      index
    end
each_value() {|subkey, type, data| ...}

iterator

[Source]

# File Win32API/lib/win32/registry.rb, line 624
    def each_value
      index = 0
      while true
        begin
          subkey = API.EnumValue(@hkey, index)
        rescue Error
          break
        end
        begin
          type, data = read(subkey)
        rescue Error
          next
        end
        yield subkey, type, data
        index += 1
      end
      index
    end
flush()

flush

[Source]

# File Win32API/lib/win32/registry.rb, line 809
    def flush
      API.FlushKey @hkey
    end
info()

key information

[Source]

# File Win32API/lib/win32/registry.rb, line 816
    def info
      API.QueryInfoKey(@hkey)
    end
inspect()

[Source]

# File Win32API/lib/win32/registry.rb, line 593
    def inspect
      "\#<Win32::Registry key=#{name.inspect}>"
    end
keys()

[Source]

# File Win32API/lib/win32/registry.rb, line 658
    def keys
      keys_ary = []
      each_key { |key,| keys_ary << key }
      keys_ary
    end
name()

[Source]

# File Win32API/lib/win32/registry.rb, line 584
    def name
      parent = self
      name = @keyname
      while parent = parent.parent
        name = parent.keyname + '\\' + name
      end
      name
    end
open(subkey, desired = KEY_READ, opt = REG_OPTION_RESERVED, &blk)

open/close

[Source]

# File Win32API/lib/win32/registry.rb, line 607
    def open(subkey, desired = KEY_READ, opt = REG_OPTION_RESERVED, &blk)
      self.class.open(self, subkey, desired, opt, &blk)
    end
open?()

[Source]

# File Win32API/lib/win32/registry.rb, line 580
    def open?
      !@hkey.nil?
    end
read(name, *rtype)

reader

[Source]

# File Win32API/lib/win32/registry.rb, line 667
    def read(name, *rtype)
      type, data = API.QueryValue(@hkey, name)
      unless rtype.empty? or rtype.include?(type)
        raise TypeError, "Type mismatch (expect #{rtype.inspect} but #{type} present)"
      end
      case type
      when REG_SZ, REG_EXPAND_SZ
        [ type, data.chop ]
      when REG_MULTI_SZ
        [ type, data.split(/\0/) ]
      when REG_BINARY
        [ type, data ]
      when REG_DWORD
        [ type, API.unpackdw(data) ]
      when REG_DWORD_BIG_ENDIAN
        [ type, data.unpack('N')[0] ]
      when REG_QWORD
        [ type, API.unpackqw(data) ]
      else
        raise TypeError, "Type #{type} is not supported."
      end
    end
read_bin(name)

[Source]

# File Win32API/lib/win32/registry.rb, line 719
    def read_bin(name)
      read(name, REG_BINARY)[1]
    end
read_i(name)

[Source]

# File Win32API/lib/win32/registry.rb, line 715
    def read_i(name)
      read(name, REG_DWORD, REG_DWORD_BIG_ENDIAN, REG_QWORD)[1]
    end
read_s(name)

[Source]

# File Win32API/lib/win32/registry.rb, line 702
    def read_s(name)
      read(name, REG_SZ)[1]
    end
read_s_expand(name)

[Source]

# File Win32API/lib/win32/registry.rb, line 706
    def read_s_expand(name)
      type, data = read(name, REG_SZ, REG_EXPAND_SZ)
      if type == REG_EXPAND_SZ
        Registry.expand_environ(data)
      else
        data
      end
    end
write(name, type, data)

writer

[Source]

# File Win32API/lib/win32/registry.rb, line 726
    def write(name, type, data)
      case type
      when REG_SZ, REG_EXPAND_SZ
        data = data.to_s + "\0"
      when REG_MULTI_SZ
        data = data.to_a.join("\0") + "\0\0"
      when REG_BINARY
        data = data.to_s
      when REG_DWORD
        data = API.packdw(data.to_i)
      when REG_DWORD_BIG_ENDIAN
        data = [data.to_i].pack('N')
      when REG_QWORD
        data = API.packqw(data.to_i)
      else
        raise TypeError, "Unsupported type #{type}"
      end
      API.SetValue(@hkey, name, type, data, data.length)
    end
write_bin(name, value)

[Source]

# File Win32API/lib/win32/registry.rb, line 772
    def write_bin(name, value)
      write name, REG_BINARY, value.to_s
    end
write_i(name, value)

[Source]

# File Win32API/lib/win32/registry.rb, line 768
    def write_i(name, value)
      write name, REG_DWORD, value.to_i
    end
write_s(name, value)

[Source]

# File Win32API/lib/win32/registry.rb, line 764
    def write_s(name, value)
      write name, REG_SZ, value.to_s
    end


Module: Win32::Registry::API

Module | Win32::Registry::API
In: | Win32API/lib/win32/registry.rb

Win32 APIs

Methods

CloseKey CreateKey DeleteKey DeleteValue EnumKey EnumValue FlushKey OpenKey QueryInfoKey QueryValue SetValue check packdw packqw unpackdw unpackqw

Public Instance methods

CloseKey(hkey)

[Source]

# File Win32API/lib/win32/registry.rb, line 472
      def CloseKey(hkey)
        check RegCloseKey.call(hkey)
      end
CreateKey(hkey, name, opt, desired)

[Source]

# File Win32API/lib/win32/registry.rb, line 424
      def CreateKey(hkey, name, opt, desired)
        result = packdw(0)
        disp = packdw(0)
        check RegCreateKeyExA.call(hkey, name, 0, 0, opt, desired,
                                   0, result, disp)
        [ unpackdw(result), unpackdw(disp) ]
      end
DeleteKey(hkey, name)

[Source]

# File Win32API/lib/win32/registry.rb, line 464
      def DeleteKey(hkey, name)
        check RegDeleteKey.call(hkey, name)
      end
DeleteValue(hkey, name)

[Source]

# File Win32API/lib/win32/registry.rb, line 460
      def DeleteValue(hkey, name)
        check RegDeleteValue.call(hkey, name)
      end
EnumKey(hkey, index)

[Source]

# File Win32API/lib/win32/registry.rb, line 439
      def EnumKey(hkey, index)
        name = ' ' * Constants::MAX_KEY_LENGTH
        size = packdw(Constants::MAX_KEY_LENGTH)
        wtime = ' ' * 8
        check RegEnumKeyExA.call(hkey, index, name, size, 0, 0, 0, wtime)
        [ name[0, unpackdw(size)], unpackqw(wtime) ]
      end
EnumValue(hkey, index)

[Source]

# File Win32API/lib/win32/registry.rb, line 432
      def EnumValue(hkey, index)
        name = ' ' * Constants::MAX_KEY_LENGTH
        size = packdw(Constants::MAX_KEY_LENGTH)
        check RegEnumValueA.call(hkey, index, name, size, 0, 0, 0, 0)
        name[0, unpackdw(size)]
      end
FlushKey(hkey)

[Source]

# File Win32API/lib/win32/registry.rb, line 468
      def FlushKey(hkey)
        check RegFlushKey.call(hkey)
      end
OpenKey(hkey, name, opt, desired)

[Source]

# File Win32API/lib/win32/registry.rb, line 418
      def OpenKey(hkey, name, opt, desired)
        result = packdw(0)
        check RegOpenKeyExA.call(hkey, name, opt, desired, result)
        unpackdw(result)
      end
QueryInfoKey(hkey)

[Source]

# File Win32API/lib/win32/registry.rb, line 476
      def QueryInfoKey(hkey)
        subkeys = packdw(0)
        maxsubkeylen = packdw(0)
        values = packdw(0)
        maxvaluenamelen = packdw(0)
        maxvaluelen = packdw(0)
        secdescs = packdw(0)
        wtime = ' ' * 8
        check RegQueryInfoKey.call(hkey, 0, 0, 0, subkeys, maxsubkeylen, 0,
          values, maxvaluenamelen, maxvaluelen, secdescs, wtime)
        [ unpackdw(subkeys), unpackdw(maxsubkeylen), unpackdw(values),
          unpackdw(maxvaluenamelen), unpackdw(maxvaluelen),
          unpackdw(secdescs), unpackqw(wtime) ]
      end
QueryValue(hkey, name)

[Source]

# File Win32API/lib/win32/registry.rb, line 447
      def QueryValue(hkey, name)
        type = packdw(0)
        size = packdw(0)
        check RegQueryValueExA.call(hkey, name, 0, type, 0, size)
        data = ' ' * unpackdw(size)
        check RegQueryValueExA.call(hkey, name, 0, type, data, size)
        [ unpackdw(type), data[0, unpackdw(size)] ]
      end
SetValue(hkey, name, type, data, size)

[Source]

# File Win32API/lib/win32/registry.rb, line 456
      def SetValue(hkey, name, type, data, size)
        check RegSetValueExA.call(hkey, name, 0, type, data, size)
      end
check(result)

[Source]

# File Win32API/lib/win32/registry.rb, line 396
      def check(result)
        raise Error, result, caller(2) if result != 0
      end
packdw(dw)

[Source]

# File Win32API/lib/win32/registry.rb, line 400
      def packdw(dw)
        [dw].pack('V')
      end
packqw(qw)

[Source]

# File Win32API/lib/win32/registry.rb, line 409
      def packqw(qw)
        [ qw & 0xFFFFFFFF, qw >> 32 ].pack('VV')
      end
unpackdw(dw)

[Source]

# File Win32API/lib/win32/registry.rb, line 404
      def unpackdw(dw)
        dw += [0].pack('V')
        dw.unpack('V')[0]
      end
unpackqw(qw)

[Source]

# File Win32API/lib/win32/registry.rb, line 413
      def unpackqw(qw)
        qw = qw.unpack('VV')
        (qw[1] << 32) | qw[0]
      end


Module: Win32::Registry::Constants

Module | Win32::Registry::Constants
In: | Win32API/lib/win32/registry.rb

Constants

HKEY_CLASSES_ROOT | = | 0x80000000
HKEY_CURRENT_USER | = | 0x80000001
HKEY_LOCAL_MACHINE | = | 0x80000002
HKEY_USERS | = | 0x80000003
HKEY_PERFORMANCE_DATA | = | 0x80000004
HKEY_PERFORMANCE_TEXT | = | 0x80000050
HKEY_PERFORMANCE_NLSTEXT | = | 0x80000060
HKEY_CURRENT_CONFIG | = | 0x80000005
HKEY_DYN_DATA | = | 0x80000006
REG_NONE | = | 0
REG_SZ | = | 1
REG_EXPAND_SZ | = | 2
REG_BINARY | = | 3
REG_DWORD | = | 4
REG_DWORD_LITTLE_ENDIAN | = | 4
REG_DWORD_BIG_ENDIAN | = | 5
REG_LINK | = | 6
REG_MULTI_SZ | = | 7
REG_RESOURCE_LIST | = | 8
REG_FULL_RESOURCE_DESCRIPTOR | = | 9
REG_RESOURCE_REQUIREMENTS_LIST | = | 10
REG_QWORD | = | 11
REG_QWORD_LITTLE_ENDIAN | = | 11
STANDARD_RIGHTS_READ | = | 0x00020000
STANDARD_RIGHTS_WRITE | = | 0x00020000
KEY_QUERY_VALUE | = | 0x0001
KEY_SET_VALUE | = | 0x0002
KEY_CREATE_SUB_KEY | = | 0x0004
KEY_ENUMERATE_SUB_KEYS | = | 0x0008
KEY_NOTIFY | = | 0x0010
KEY_CREATE_LINK | = | 0x0020
KEY_READ | = | STANDARD_RIGHTS_READ | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS | KEY_NOTIFY
KEY_WRITE | = | STANDARD_RIGHTS_WRITE | KEY_SET_VALUE | KEY_CREATE_SUB_KEY
KEY_EXECUTE | = | KEY_READ
KEY_ALL_ACCESS | = | KEY_READ | KEY_WRITE | KEY_CREATE_LINK
REG_OPTION_RESERVED | = | 0x0000
REG_OPTION_NON_VOLATILE | = | 0x0000
REG_OPTION_VOLATILE | = | 0x0001
REG_OPTION_CREATE_LINK | = | 0x0002
REG_OPTION_BACKUP_RESTORE | = | 0x0004
REG_OPTION_OPEN_LINK | = | 0x0008
REG_LEGAL_OPTION | = | REG_OPTION_RESERVED | REG_OPTION_NON_VOLATILE | REG_OPTION_CREATE_LINK | REG_OPTION_BACKUP_RESTORE | REG_OPTION_OPEN_LINK
REG_CREATED_NEW_KEY | = | 1
REG_OPENED_EXISTING_KEY | = | 2
REG_WHOLE_HIVE_VOLATILE | = | 0x0001
REG_REFRESH_HIVE | = | 0x0002
REG_NO_LAZY_FLUSH | = | 0x0004
REG_FORCE_RESTORE | = | 0x0008
MAX_KEY_LENGTH | = | 514
MAX_VALUE_LENGTH | = | 32768


Class: Win32::Registry::Error

Class | Win32::Registry::Error
In: | Win32API/lib/win32/registry.rb
Parent: | ::StandardError

Error

Methods

new

Constants

FormatMessageA = Win32API.new('kernel32.dll', 'FormatMessageA', 'LPLLPLP', 'L')

Attributes

code [R]

Public Class methods

new(code)

[Source]

# File Win32API/lib/win32/registry.rb, line 338
      def initialize(code)
        @code = code
        msg = "\0" * 1024
        len = FormatMessageA.call(0x1200, 0, code, 0, msg, 1024, 0)
        super msg[0, len].tr("\r", '').chomp
      end


Class: Win32::Registry::PredefinedKey

Class | Win32::Registry::PredefinedKey
In: | Win32API/lib/win32/registry.rb
Parent: | Registry

Predefined Keys

Methods

class close new

Public Class methods

new(hkey, keyname)

[Source]

# File Win32API/lib/win32/registry.rb, line 351
      def initialize(hkey, keyname)
        @hkey = hkey
        @parent = nil
        @keyname = keyname
        @disposition = REG_OPENED_EXISTING_KEY
      end

Public Instance methods

class()

Fake class for Registry#open, Registry#create

[Source]

# File Win32API/lib/win32/registry.rb, line 364
      def class
        Registry
      end
close()

Predefined keys cannot be closed

[Source]

# File Win32API/lib/win32/registry.rb, line 359
      def close
        raise Error.new(5) ## ERROR_ACCESS_DENIED
      end


Module: Win32::Resolv

Module | Win32::Resolv
In: | Win32API/lib/win32/resolv.rb

Methods

get_hosts_path get_resolv_info

Constants

API = Registry::API

Public Class methods

get_hosts_path()

[Source]

# File Win32API/lib/win32/resolv.rb, line 12
    def self.get_hosts_path
      path = get_hosts_dir
      path = File.join(path.gsub(/\\/, File::SEPARATOR), 'hosts')
      File.exist?(path) ? path : nil
    end
get_resolv_info()

[Source]

# File Win32API/lib/win32/resolv.rb, line 18
    def self.get_resolv_info
      search, nameserver = get_info
      if search.empty?
        search = nil
      else
        search.delete("")
        search.uniq!
      end
      if nameserver.empty?
        nameserver = nil
      else
        nameserver.delete("")
        nameserver.delete("0.0.0.0")
        nameserver.uniq!
      end
      [ search, nameserver ]
    end


File: Win32API.c

Win32API.c

Path: | Win32API/Win32API.c
Last Update: | Sat Oct 15 23:43:50 AUS Eastern Standard Time 2005


File: getch.rb

getch.rb

Path: | Win32API/getch.rb
Last Update: | Fri Aug 13 15:37:46 AUS Eastern Standard Time 1999

Required files

Win32API


File: registry.rb

registry.rb

Path: | Win32API/lib/win32/registry.rb
Last Update: | Sat Jul 19 04:11:45 AUS Eastern Standard Time 2003

Required files

Win32API


File: resolv.rb

resolv.rb

Path: | Win32API/lib/win32/resolv.rb
Last Update: | Tue Oct 25 16:35:28 AUS Eastern Standard Time 2005

Required files

win32/registry


File: point.rb

point.rb

Path: | Win32API/point.rb
Last Update: | Fri Aug 13 15:37:47 AUS Eastern Standard Time 1999

Required files

Win32API

Constants

GetDesktopWindow | = | Win32API.new("user32", "GetDesktopWindow", [], 'L')
GetActiveWindow | = | Win32API.new("user32", "GetActiveWindow", [], 'L')
SendMessage | = | Win32API.new("user32", "SendMessage", ['L'] * 4, 'L')


Class: WIN32OLE

Class | WIN32OLE
In: | 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

Public Class methods

WIN32OLE.codepage

Returns current codepage.

   WIN32OLE.codepage # => WIN32OLE::CP_ACP

[Source]

/*
 *  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);
}
WIN32OLE.codepage = CP

Sets current codepage.

   WIN32OLE.codepage = WIN32OLE::CP_UTF8

[Source]

/*
 *  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;
}
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.

[Source]

/*
 *  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);
}
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

[Source]

/*
 *  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;
}
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.

[Source]

/*
 *  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;
}
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.

[Source]

/*
 *  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);
}
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.

[Source]

/*
 *  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));
}
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)

[Source]

/*
 *  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;
}

Public Instance methods

WIN32OLE['property']

Returns property of OLE object.

   excel = WIN32OLE.new('Excel.Application')
   puts excel['Visible'] # => false

[Source]

/*
 *  call-seq:
 *     WIN32OLE['property']
 *
 *  Returns property of OLE object.
 *
 *     excel = WIN32OLE.new('Excel.Application')
 *     puts excel['Visible'] # => false
 */
static VALUE
fole_getproperty(self, property)
    VALUE self, property;
{
    return ole_invoke(1, &property, self, DISPATCH_PROPERTYGET);
}
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.

[Source]

/*
 *  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);
}
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

[Source]

/*
 *  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);
}
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

[Source]

/*
 *   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);
}
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

[Source]

/*
 *   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#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

[Source]

/*
 *  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;
}
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

[Source]

/*
 *  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#method_missing(id [,arg1, arg2, ...])

Calls WIN32OLE#invoke method.

[Source]

/*
 *  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);
    }
}
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.

[Source]

/*
 *  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;
}
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

[Source]

/*
 *  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);
}
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

[Source]

/*
 *  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);
}
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')

[Source]

/*
 *   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_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

[Source]

/*
 *  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);
}
WIN32OLE#ole_obj_help

Returns WIN32OLE_TYPE object.

   excel = WIN32OLE.new('Excel.Application')
   tobj = excel.ole_obj_help

[Source]

/*
 *   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;
}
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

[Source]

/*
 *  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);
}
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.

[Source]

/*
 *  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);
}


Class: OLEProperty

Class | OLEProperty
In: | win32ole/lib/win32ole/property.rb
Parent: | Object

OLEProperty helper class of Property with arguments.

Methods

[] []= new

Public Class methods

new(obj, dispid, gettypes, settypes)

[Source]

# File win32ole/lib/win32ole/property.rb, line 4
  def initialize(obj, dispid, gettypes, settypes)
    @obj = obj
    @dispid = dispid
    @gettypes = gettypes
    @settypes = settypes
  end

Public Instance methods

[](*args)

[Source]

# File win32ole/lib/win32ole/property.rb, line 10
  def [](*args)
    @obj._getproperty(@dispid, args, @gettypes)
  end
[]=(*args)

[Source]

# File win32ole/lib/win32ole/property.rb, line 13
  def []=(*args)
    @obj._setproperty(@dispid, args, @settypes)
  end


Module: WIN32OLE::VARIANT

Module | WIN32OLE::VARIANT
In: | win32ole/win32ole.c


Class: WIN32OLERuntimeError

Class | WIN32OLERuntimeError
In: | win32ole/win32ole.c
Parent: | RuntimeError


Class: WIN32OLE_EVENT

Class | WIN32OLE_EVENT
In: | 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.

[Source]

/*
 *  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;
}
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')

[Source]

/*
 *  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;
}

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}

[Source]

/*
 *  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);
}
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.

[Source]

/*
 *  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);
}


Class: WIN32OLE_METHOD

Class | WIN32OLE_METHOD
In: | 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')

[Source]

/*
 *  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;
}

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

[Source]

/*
 *  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);
}
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

[Source]

/*
 *  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")));
}
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

[Source]

/*
 *  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;
}
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

[Source]

/*
 *  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);
}
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

[Source]

/*
 *  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);
}
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.

[Source]

/*
 *  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);
}
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

[Source]

/*
 *   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);
}
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"

[Source]

/*
 *  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);
}
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

[Source]

/*
 *  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"));
}
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

[Source]

/*
 *  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);
}
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]

[Source]

/*
 *  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);
}
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

[Source]

/*
 *  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);
}
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"]

[Source]

/*
 *  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);
}
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

[Source]

/*
 *  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);
}
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

[Source]

/*
 *  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);
}
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

[Source]

/*
 *  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);
}
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

[Source]

/*
 *  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);
}


Class: WIN32OLE_PARAM

Class | WIN32OLE_PARAM
In: | 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

[Source]

/*
 *  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);
}
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

[Source]

/*
 *  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);
}
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

[Source]

/*
 *  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"));
}
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

[Source]

/*
 *  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);
}
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"]

[Source]

/*
 *  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);
}
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

[Source]

/*
 *  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);
}
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

[Source]

/*
 *  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);
}
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

[Source]

/*
 *  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);
}
to_s()

Alias for name


Class: WIN32OLE_TYPE

Class | WIN32OLE_TYPE
In: | 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.

[Source]

/*
 *  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;
}
WIN32OLE_TYPE.ole_classes(typelib)

Returns array of WIN32OLE_TYPE objects defined by the typelib type library.

[Source]

/*
 *   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;
}
WIN32OLE_TYPE.progids

Returns array of ProgID.

[Source]

/*
 *  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;
}
WIN32OLE_TYPE.typelibs

Returns array of type libraries.

[Source]

/*
 *  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;
}

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}

[Source]

/*
 *  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);
}
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

[Source]

/*
 *  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);
}
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

[Source]

/*
 *  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);
}
WIN32OLE_TYPE#helpstring #=> help string.

Returns help string.

  tobj = WIN32OLE_TYPE.new('Microsoft Internet Controls', 'IWebBrowser')
  puts tobj.helpstring # => Web Browser interface

[Source]

/*
 *  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);
}
WIN32OLE_TYPE#major_version

Returns major version.

   tobj = WIN32OLE_TYPE.new('Microsoft Word 10.0 Object Library', 'Documents')
   puts tobj.major_version # => 8

[Source]

/*
 *  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);
}
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

[Source]

/*
 *  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);
}
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

[Source]

/*
 * 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"));
}
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',....]

[Source]

/*
 *  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);
}
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

[Source]

/*
 *  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);
}
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

[Source]

/*
 * 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);
}
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

[Source]

/*
 *  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);
}
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

[Source]

/*
 *  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);
}
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

[Source]

/*
 *  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);
}
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

[Source]

/*
 *  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);
}


Class: WIN32OLE_VARIABLE

Class | WIN32OLE_VARIABLE
In: | 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

[Source]

/*
 *  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"));
}
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

[Source]

/*
 *   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);
}
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"]

[Source]

/*
 *  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);
}
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

[Source]

/*
 *  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);
}
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

[Source]

/*
 * 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);
}
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

[Source]

/*
 *  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);
}
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

[Source]

/*
 *  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);
}


File: property.rb

property.rb

Path: | win32ole/lib/win32ole/property.rb
Last Update: | Sat Jun 01 22:34:29 AUS Eastern Standard Time 2002

OLEProperty helper class of Property with arguments.


File: win32ole.c

win32ole.c

Path: | win32ole/win32ole.c
Last Update: | Sat Oct 15 23:44:27 AUS Eastern Standard Time 2005


Module: WSDL
In: wsdl/xmlSchema/xsd2ruby.rb
wsdl/xmlSchema/unique.rb
wsdl/xmlSchema/simpleType.rb
wsdl/xmlSchema/simpleRestriction.rb
wsdl/xmlSchema/simpleExtension.rb
wsdl/xmlSchema/simpleContent.rb
wsdl/xmlSchema/sequence.rb
wsdl/xmlSchema/schema.rb
wsdl/xmlSchema/pattern.rb
wsdl/xmlSchema/parser.rb
wsdl/xmlSchema/length.rb
wsdl/xmlSchema/include.rb
wsdl/xmlSchema/importer.rb
wsdl/xmlSchema/import.rb
wsdl/xmlSchema/enumeration.rb
wsdl/xmlSchema/element.rb
wsdl/xmlSchema/data.rb
wsdl/xmlSchema/content.rb
wsdl/xmlSchema/complexType.rb
wsdl/xmlSchema/complexContent.rb
wsdl/xmlSchema/choice.rb
wsdl/xmlSchema/attribute.rb
wsdl/xmlSchema/any.rb
wsdl/xmlSchema/annotation.rb
wsdl/xmlSchema/all.rb
wsdl/wsdl.rb
wsdl/types.rb
wsdl/soap/wsdl2ruby.rb
wsdl/soap/standaloneServerStubCreator.rb
wsdl/soap/servantSkeltonCreator.rb
wsdl/soap/operation.rb
wsdl/soap/methodDefCreator.rb
wsdl/soap/mappingRegistryCreator.rb
wsdl/soap/headerfault.rb
wsdl/soap/header.rb
wsdl/soap/fault.rb
wsdl/soap/element.rb
wsdl/soap/driverCreator.rb
wsdl/soap/definitions.rb
wsdl/soap/data.rb
wsdl/soap/complexType.rb
wsdl/soap/clientSkeltonCreator.rb
wsdl/soap/classDefCreatorSupport.rb
wsdl/soap/classDefCreator.rb
wsdl/soap/cgiStubCreator.rb
wsdl/soap/body.rb
wsdl/soap/binding.rb
wsdl/soap/address.rb
wsdl/service.rb
wsdl/portType.rb
wsdl/port.rb
wsdl/part.rb
wsdl/parser.rb
wsdl/param.rb
wsdl/operationBinding.rb
wsdl/operation.rb
wsdl/message.rb
wsdl/info.rb
wsdl/importer.rb
wsdl/import.rb
wsdl/documentation.rb
wsdl/definitions.rb
wsdl/data.rb
wsdl/binding.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: | 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()

[Source]

# File wsdl/binding.rb, line 22
  def initialize
    super
    @name = nil
    @type = nil
    @operations = XSD::NamedElements.new
    @soapbinding = nil
  end

Public Instance methods

parse_attr(attr, value)

[Source]

# File 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
parse_element(element)

[Source]

# File 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
targetnamespace()

[Source]

# File wsdl/binding.rb, line 30
  def targetnamespace
    parent.targetnamespace
  end


Class: WSDL::Definitions

Class | WSDL::Definitions
In: | wsdl/soap/definitions.rb wsdl/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()

[Source]

# File 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
exception_complextype()

[Source]

# File 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
fault_complextype()

[Source]

# File 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
new()

[Source]

# File 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
parse_element(element)

[Source]

# File wsdl/definitions.rb, line 237
  def self.parse_element(element)
    if element == DefinitionsName
      Definitions.new
    else
      nil
    end
  end
soap_rpc_complextypes()

[Source]

# File 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

Public Instance methods

add_type(complextype)

ToDo: simpletype must be accepted…

[Source]

# File wsdl/definitions.rb, line 106
  def add_type(complextype)
    @anontypes << complextype
  end
binding(name)

[Source]

# File 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
bindings()

[Source]

# File 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
collect_attributes()

[Source]

# File 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_complextypes()

[Source]

# File 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_elements()

[Source]

# File 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_faulttypes()

[Source]

# File 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
collect_simpletypes()

[Source]

# File 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
inspect()

[Source]

# File wsdl/definitions.rb, line 42
  def inspect
    sprintf("#<%s:0x%x %s>", self.class.name, __id__, @name || '(unnamed)')
  end
message(name)

[Source]

# File 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
messages()

[Source]

# File 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
parse_attr(attr, value)

[Source]

# File 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(element)

[Source]

# File 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
porttype(name)

[Source]

# File 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
porttype_binding(name)

[Source]

# File 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
porttypes()

[Source]

# File 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
service(name)

[Source]

# File 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
services()

[Source]

# File 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
soap_rpc_complextypes(binding)

[Source]

# File wsdl/soap/definitions.rb, line 73
  def soap_rpc_complextypes(binding)
    types = rpc_operation_complextypes(binding)
    types + self.class.soap_rpc_complextypes
  end
targetnamespace=(targetnamespace)

[Source]

# File wsdl/definitions.rb, line 46
  def targetnamespace=(targetnamespace)
    @targetnamespace = targetnamespace
    if @name
      @name = XSD::QName.new(@targetnamespace, @name.name)
    end
  end


Class: WSDL::Documentation

Class | WSDL::Documentation
In: | wsdl/documentation.rb
Parent: | Info

Methods

new parse_attr parse_element

Public Class methods

new()

[Source]

# File wsdl/documentation.rb, line 16
  def initialize
    super
  end

Public Instance methods

parse_attr(attr, value)

[Source]

# File wsdl/documentation.rb, line 25
  def parse_attr(attr, value)
    # Accepts any attribute.
    true
  end
parse_element(element)

[Source]

# File wsdl/documentation.rb, line 20
  def parse_element(element)
    # Accepts any element.
    self
  end


Class: WSDL::Error

Class | WSDL::Error
In: | wsdl/wsdl.rb
Parent: | StandardError


Class: WSDL::Import

Class | WSDL::Import
In: | wsdl/import.rb
Parent: | Info

Methods

new parse_attr parse_element

Attributes

content | [R]
location | [R]
namespace | [R]

Public Class methods

new()

[Source]

# File wsdl/import.rb, line 21
  def initialize
    super
    @namespace = nil
    @location = nil
    @content = nil
    @web_client = nil
  end

Public Instance methods

parse_attr(attr, value)

[Source]

# File 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
parse_element(element)

[Source]

# File wsdl/import.rb, line 29
  def parse_element(element)
    case element
    when DocumentationName
      o = Documentation.new
      o
    else
      nil
    end
  end


Class: WSDL::Importer

Class | WSDL::Importer
In: | wsdl/importer.rb
Parent: | WSDL::XMLSchema::Importer

Methods

import

Public Class methods

import(location, originalroot = nil)

[Source]

# File wsdl/importer.rb, line 17
  def self.import(location, originalroot = nil)
    new.import(location, originalroot)
  end


Class: WSDL::Info

Class | WSDL::Info
In: | 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()

[Source]

# File wsdl/info.rb, line 17
  def initialize
    @root = nil
    @parent = nil
    @id = nil
  end

Public Instance methods

inspect()

[Source]

# File 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_attr(attr, value)

[Source]

# File wsdl/info.rb, line 33
  def parse_attr(attr, value); end
parse_element(element)

[Source]

# File wsdl/info.rb, line 31
  def parse_element(element); end
parse_epilogue()

[Source]

# File wsdl/info.rb, line 35
  def parse_epilogue; end


Class: WSDL::Message

Class | WSDL::Message
In: | wsdl/message.rb
Parent: | Info

Methods

new parse_attr parse_element targetnamespace

Attributes

name | [R]
parts | [R]

Public Class methods

new()

[Source]

# File wsdl/message.rb, line 19
  def initialize
    super
    @name = nil
    @parts = []
  end

Public Instance methods

parse_attr(attr, value)

[Source]

# File 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
parse_element(element)

[Source]

# File 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
targetnamespace()

[Source]

# File wsdl/message.rb, line 25
  def targetnamespace
    parent.targetnamespace
  end


Class: WSDL::Operation

Class | WSDL::Operation
In: | 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()

[Source]

# File wsdl/operation.rb, line 34
  def initialize
    super
    @name = nil
    @type = nil
    @parameter_order = nil
    @input = nil
    @output = nil
    @fault = []
  end

Public Instance methods

input_info()

[Source]

# File wsdl/operation.rb, line 48
  def input_info
    typename = input.find_message.name
    NameInfo.new(@name, typename, inputparts)
  end
inputname()

[Source]

# File wsdl/operation.rb, line 62
  def inputname
    XSD::QName.new(targetnamespace, input.name ? input.name.name : @name.name)
  end
inputparts()

[Source]

# File wsdl/operation.rb, line 58
  def inputparts
    sort_parts(input.find_message.parts)
  end
output_info()

[Source]

# File wsdl/operation.rb, line 53
  def output_info
    typename = output.find_message.name
    NameInfo.new(@name, typename, outputparts)
  end
outputname()

[Source]

# File wsdl/operation.rb, line 70
  def outputname
    XSD::QName.new(targetnamespace,
      output.name ? output.name.name : @name.name + 'Response')
  end
outputparts()

[Source]

# File wsdl/operation.rb, line 66
  def outputparts
    sort_parts(output.find_message.parts)
  end
parse_attr(attr, value)

[Source]

# File 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
parse_element(element)

[Source]

# File 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
targetnamespace()

[Source]

# File wsdl/operation.rb, line 44
  def targetnamespace
    parent.targetnamespace
  end


Class: WSDL::Operation::NameInfo

Class | WSDL::Operation::NameInfo
In: | 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)

[Source]

# File wsdl/operation.rb, line 20
    def initialize(op_name, optype_name, parts)
      @op_name = op_name
      @optype_name = optype_name
      @parts = parts
    end


Class: WSDL::OperationBinding

Class | WSDL::OperationBinding
In: | 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()

[Source]

# File wsdl/operationBinding.rb, line 22
  def initialize
    super
    @name = nil
    @input = nil
    @output = nil
    @fault = []
    @soapoperation = nil
  end

Public Instance methods

find_operation()

[Source]

# File wsdl/operationBinding.rb, line 39
  def find_operation
    porttype.operations[@name] or raise RuntimeError.new("#{@name} not found")
  end
parse_attr(attr, value)

[Source]

# File 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
parse_element(element)

[Source]

# File 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
porttype()

[Source]

# File wsdl/operationBinding.rb, line 35
  def porttype
    root.porttype(parent.type)
  end
soapaction()

[Source]

# File wsdl/operationBinding.rb, line 63
  def soapaction
    if @soapoperation
      @soapoperation.soapaction
    else
      nil
    end
  end
soapoperation_name()

[Source]

# File wsdl/operationBinding.rb, line 43
  def soapoperation_name
    if @soapoperation
      @soapoperation.input_info.op_name
    else
      find_operation.name
    end
  end
soapoperation_style()

[Source]

# File 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
targetnamespace()

[Source]

# File wsdl/operationBinding.rb, line 31
  def targetnamespace
    parent.targetnamespace
  end


Class: WSDL::Param

Class | WSDL::Param
In: | 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()

[Source]

# File wsdl/param.rb, line 22
  def initialize
    super
    @message = nil
    @name = nil
    @soapbody = nil
    @soapheader = []
    @soapfault = nil
  end

Public Instance methods

find_message()

[Source]

# File wsdl/param.rb, line 35
  def find_message
    root.message(@message) or raise RuntimeError.new("#{@message} not found")
  end
parse_attr(attr, value)

[Source]

# File 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
parse_element(element)

[Source]

# File 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
soapbody_use()

[Source]

# File wsdl/param.rb, line 39
  def soapbody_use
    if @soapbody
      @soapbody.use || :literal
    else
      raise RuntimeError.new("soap:body not found")
    end
  end
targetnamespace()

[Source]

# File wsdl/param.rb, line 31
  def targetnamespace
    parent.targetnamespace
  end


Class: WSDL::Parser

Class | WSDL::Parser
In: | 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 = {})

[Source]

# File 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

Public Instance methods

characters(text)

[Source]

# File 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
charset()

[Source]

# File wsdl/parser.rb, line 69
  def charset
    @parser.charset
  end
end_element(name)

[Source]

# File 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
parse(string_or_readable)

[Source]

# File wsdl/parser.rb, line 61
  def parse(string_or_readable)
    @parsestack = []
    @lastnode = nil
    @textbuf = ''
    @parser.do_parse(string_or_readable)
    @lastnode
  end
start_element(name, attrs)

[Source]

# File 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


Class: WSDL::Parser::AttributeConstraintError

Class | WSDL::Parser::AttributeConstraintError
In: | wsdl/parser.rb
Parent: | FormatDecodeError


Class: WSDL::Parser::ElementConstraintError

Class | WSDL::Parser::ElementConstraintError
In: | wsdl/parser.rb
Parent: | FormatDecodeError


Class: WSDL::Parser::FormatDecodeError

Class | WSDL::Parser::FormatDecodeError
In: | wsdl/parser.rb
Parent: | ParseError


Class: WSDL::Parser::ParseError

Class | WSDL::Parser::ParseError
In: | wsdl/parser.rb
Parent: | Error


Class: WSDL::Parser::ParseFrame

Class | WSDL::Parser::ParseFrame
In: | wsdl/parser.rb
Parent: | Object

Methods

new

Attributes

name | [R]
node | [RW]
ns | [R]

Public Class methods

new(ns, name, node)

[Source]

# File wsdl/parser.rb, line 43
    def initialize(ns, name, node)
      @ns = ns
      @name = name
      @node = node
    end


Class: WSDL::Parser::UnexpectedElementError

Class | WSDL::Parser::UnexpectedElementError
In: | wsdl/parser.rb
Parent: | FormatDecodeError


Class: WSDL::Parser::UnknownAttributeError

Class | WSDL::Parser::UnknownAttributeError
In: | wsdl/parser.rb
Parent: | FormatDecodeError


Class: WSDL::Parser::UnknownElementError

Class | WSDL::Parser::UnknownElementError
In: | wsdl/parser.rb
Parent: | FormatDecodeError


Class: WSDL::Part

Class | WSDL::Part
In: | wsdl/part.rb
Parent: | Info

Methods

new parse_attr parse_element

Attributes

element | [R]
name | [R]
type | [R]

Public Class methods

new()

[Source]

# File wsdl/part.rb, line 20
  def initialize
    super
    @name = nil
    @element = nil
    @type = nil
  end

Public Instance methods

parse_attr(attr, value)

[Source]

# File 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
parse_element(element)

[Source]

# File wsdl/part.rb, line 27
  def parse_element(element)
    case element
    when DocumentationName
      o = Documentation.new
      o
    else
      nil
    end
  end


Class: WSDL::Port

Class | WSDL::Port
In: | 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()

[Source]

# File wsdl/port.rb, line 20
  def initialize
    super
    @name = nil
    @binding = nil
    @soap_address = nil
  end

Public Instance methods

find_binding()

[Source]

# File wsdl/port.rb, line 35
  def find_binding
    root.binding(@binding) or raise RuntimeError.new("#{@binding} not found")
  end
inputoperation_map()

[Source]

# File 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()

[Source]

# File 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_attr(attr, value)

[Source]

# File 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
parse_element(element)

[Source]

# File 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
porttype()

[Source]

# File wsdl/port.rb, line 31
  def porttype
    root.porttype(find_binding.type)
  end
targetnamespace()

[Source]

# File wsdl/port.rb, line 27
  def targetnamespace
    parent.targetnamespace
  end


Class: WSDL::PortType

Class | WSDL::PortType
In: | wsdl/portType.rb
Parent: | Info

Methods

find_binding locations new parse_attr parse_element targetnamespace

Attributes

name | [R]
operations | [R]

Public Class methods

new()

[Source]

# File wsdl/portType.rb, line 24
  def initialize
    super
    @name = nil
    @operations = XSD::NamedElements.new
  end

Public Instance methods

find_binding()

[Source]

# File wsdl/portType.rb, line 30
  def find_binding
    root.bindings.find { |item| item.type == @name } or
      raise RuntimeError.new("#{@name} not found")
  end
locations()

[Source]

# File 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_attr(attr, value)

[Source]

# File 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
parse_element(element)

[Source]

# File 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
targetnamespace()

[Source]

# File wsdl/portType.rb, line 20
  def targetnamespace
    parent.targetnamespace
  end


Module: WSDL::SOAP

Module | WSDL::SOAP
In: | wsdl/soap/wsdl2ruby.rb wsdl/soap/standaloneServerStubCreator.rb wsdl/soap/servantSkeltonCreator.rb wsdl/soap/operation.rb wsdl/soap/methodDefCreator.rb wsdl/soap/mappingRegistryCreator.rb wsdl/soap/headerfault.rb wsdl/soap/header.rb wsdl/soap/fault.rb wsdl/soap/driverCreator.rb wsdl/soap/data.rb wsdl/soap/clientSkeltonCreator.rb wsdl/soap/classDefCreatorSupport.rb wsdl/soap/classDefCreator.rb wsdl/soap/cgiStubCreator.rb wsdl/soap/body.rb wsdl/soap/binding.rb wsdl/soap/address.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: | wsdl/soap/address.rb
Parent: | Info

Methods

new parse_attr parse_element

Attributes

location [R]

Public Class methods

new()

[Source]

# File wsdl/soap/address.rb, line 19
  def initialize
    super
    @location = nil
  end

Public Instance methods

parse_attr(attr, value)

[Source]

# File wsdl/soap/address.rb, line 28
  def parse_attr(attr, value)
    case attr
    when LocationAttrName
      @location = value.source
    else
      nil
    end
  end
parse_element(element)

[Source]

# File wsdl/soap/address.rb, line 24
  def parse_element(element)
    nil
  end


Class: WSDL::SOAP::Binding

Class | WSDL::SOAP::Binding
In: | wsdl/soap/binding.rb
Parent: | Info

Methods

new parse_attr parse_element

Attributes

style | [R]
transport | [R]

Public Class methods

new()

[Source]

# File wsdl/soap/binding.rb, line 20
  def initialize
    super
    @style = nil
    @transport = nil
  end

Public Instance methods

parse_attr(attr, value)

[Source]

# File 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
parse_element(element)

[Source]

# File wsdl/soap/binding.rb, line 26
  def parse_element(element)
    nil
  end


Class: WSDL::SOAP::Body

Class | WSDL::SOAP::Body
In: | 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()

[Source]

# File wsdl/soap/body.rb, line 22
  def initialize
    super
    @parts = nil
    @use = nil
    @encodingstyle = nil
    @namespace = nil
  end

Public Instance methods

parse_attr(attr, value)

[Source]

# File 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
parse_element(element)

[Source]

# File wsdl/soap/body.rb, line 30
  def parse_element(element)
    nil
  end


Class: WSDL::SOAP::CGIStubCreator

Class | WSDL::SOAP::CGIStubCreator
In: | wsdl/soap/cgiStubCreator.rb
Parent: | Object

Methods

dump new

Included Modules

ClassDefCreatorSupport

Attributes

definitions [R]

Public Class methods

new(definitions)

[Source]

# File wsdl/soap/cgiStubCreator.rb, line 24
  def initialize(definitions)
    @definitions = definitions
  end

Public Instance methods

dump(service_name)

[Source]

# File 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


Class: WSDL::SOAP::ClassDefCreator

Class | WSDL::SOAP::ClassDefCreator
In: | 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)

[Source]

# File 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

Public Instance methods

dump(type = nil)

[Source]

# File 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


Module: WSDL::SOAP::ClassDefCreatorSupport

Module | WSDL::SOAP::ClassDefCreatorSupport
In: | 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)

[Source]

# File wsdl/soap/classDefCreatorSupport.rb, line 30
  def basetype_mapped_class(name)
    ::SOAP::TypeMap[name]
  end
create_class_name(qname)

[Source]

# File 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
dq(ele)

[Source]

# File wsdl/soap/classDefCreatorSupport.rb, line 64
  def dq(ele)
    ele.dump
  end
dqname(qname)

[Source]

# File wsdl/soap/classDefCreatorSupport.rb, line 76
  def dqname(qname)
    qname.dump
  end
dump_method_signature(operation)

[Source]

# File 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
ndq(ele)

[Source]

# File wsdl/soap/classDefCreatorSupport.rb, line 68
  def ndq(ele)
    ele.nil? ? 'nil' : dq(ele)
  end
sym(ele)

[Source]

# File wsdl/soap/classDefCreatorSupport.rb, line 72
  def sym(ele)
    ':' + ele
  end


Class: WSDL::SOAP::ClientSkeltonCreator

Class | WSDL::SOAP::ClientSkeltonCreator
In: | wsdl/soap/clientSkeltonCreator.rb
Parent: | Object

Methods

dump new

Included Modules

ClassDefCreatorSupport

Attributes

definitions [R]

Public Class methods

new(definitions)

[Source]

# File wsdl/soap/clientSkeltonCreator.rb, line 22
  def initialize(definitions)
    @definitions = definitions
  end

Public Instance methods

dump(service_name)

[Source]

# File 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


Class: WSDL::SOAP::DriverCreator

Class | WSDL::SOAP::DriverCreator
In: | wsdl/soap/driverCreator.rb
Parent: | Object

Methods

dump new

Included Modules

ClassDefCreatorSupport

Attributes

definitions [R]

Public Class methods

new(definitions)

[Source]

# File wsdl/soap/driverCreator.rb, line 25
  def initialize(definitions)
    @definitions = definitions
  end

Public Instance methods

dump(porttype = nil)

[Source]

# File 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


Class: WSDL::SOAP::Fault

Class | WSDL::SOAP::Fault
In: | 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()

[Source]

# File wsdl/soap/fault.rb, line 22
  def initialize
    super
    @name = nil
    @use = nil
    @encodingstyle = nil
    @namespace = nil
  end

Public Instance methods

parse_attr(attr, value)

[Source]

# File 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
parse_element(element)

[Source]

# File wsdl/soap/fault.rb, line 34
  def parse_element(element)
    nil
  end
targetnamespace()

[Source]

# File wsdl/soap/fault.rb, line 30
  def targetnamespace
    parent.targetnamespace
  end


Class: WSDL::SOAP::Header

Class | WSDL::SOAP::Header
In: | 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()

[Source]

# File wsdl/soap/header.rb, line 25
  def initialize
    super
    @message = nil
    @part = nil
    @use = nil
    @encodingstyle = nil
    @namespace = nil
    @headerfault = nil
  end

Public Instance methods

find_message()

[Source]

# File wsdl/soap/header.rb, line 39
  def find_message
    root.message(@message) or raise RuntimeError.new("#{@message} not found")
  end
find_part()

[Source]

# File 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_attr(attr, value)

[Source]

# File 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
parse_element(element)

[Source]

# File 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
targetnamespace()

[Source]

# File wsdl/soap/header.rb, line 35
  def targetnamespace
    parent.targetnamespace
  end


Class: WSDL::SOAP::HeaderFault

Class | WSDL::SOAP::HeaderFault
In: | 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()

[Source]

# File wsdl/soap/headerfault.rb, line 23
  def initialize
    super
    @message = nil
    @part = nil
    @use = nil
    @encodingstyle = nil
    @namespace = nil
  end

Public Instance methods

parse_attr(attr, value)

[Source]

# File 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
parse_element(element)

[Source]

# File wsdl/soap/headerfault.rb, line 32
  def parse_element(element)
    nil
  end


Class: WSDL::SOAP::MappingRegistryCreator

Class | WSDL::SOAP::MappingRegistryCreator
In: | wsdl/soap/mappingRegistryCreator.rb
Parent: | Object

Methods

dump new

Included Modules

ClassDefCreatorSupport

Attributes

definitions [R]

Public Class methods

new(definitions)

[Source]

# File wsdl/soap/mappingRegistryCreator.rb, line 22
  def initialize(definitions)
    @definitions = definitions
    @complextypes = @definitions.collect_complextypes
    @types = nil
  end

Public Instance methods

dump(types)

[Source]

# File 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


Class: WSDL::SOAP::MethodDefCreator

Class | WSDL::SOAP::MethodDefCreator
In: | wsdl/soap/methodDefCreator.rb
Parent: | Object

Methods

collect_documentparameter collect_rpcparameter dump new

Included Modules

ClassDefCreatorSupport

Attributes

definitions [R]

Public Class methods

new(definitions)

[Source]

# File 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

Public Instance methods

collect_documentparameter(operation)

[Source]

# File 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
collect_rpcparameter(operation)

[Source]

# File 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
dump(porttype)

[Source]

# File 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


Class: WSDL::SOAP::Operation

Class | WSDL::SOAP::Operation
In: | 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()

[Source]

# File wsdl/soap/operation.rb, line 40
  def initialize
    super
    @soapaction = nil
    @style = nil
  end

Public Instance methods

input_info()

[Source]

# File wsdl/soap/operation.rb, line 66
  def input_info
    name_info = parent.find_operation.input_info
    param_info(name_info, parent.input)
  end
operation_style()

[Source]

# File 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
output_info()

[Source]

# File wsdl/soap/operation.rb, line 71
  def output_info
    name_info = parent.find_operation.output_info
    param_info(name_info, parent.output)
  end
parse_attr(attr, value)

[Source]

# File 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
parse_element(element)

[Source]

# File wsdl/soap/operation.rb, line 46
  def parse_element(element)
    nil
  end


Class: WSDL::SOAP::Operation::OperationInfo

Class | WSDL::SOAP::Operation::OperationInfo
In: | 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)

[Source]

# File 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


Class: WSDL::SOAP::ServantSkeltonCreator

Class | WSDL::SOAP::ServantSkeltonCreator
In: | wsdl/soap/servantSkeltonCreator.rb
Parent: | Object

Methods

dump new

Included Modules

ClassDefCreatorSupport XSD::CodeGen::GenSupport

Attributes

definitions [R]

Public Class methods

new(definitions)

[Source]

# File wsdl/soap/servantSkeltonCreator.rb, line 24
  def initialize(definitions)
    @definitions = definitions
  end

Public Instance methods

dump(porttype = nil)

[Source]

# File 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


Class: WSDL::SOAP::StandaloneServerStubCreator

Class | WSDL::SOAP::StandaloneServerStubCreator
In: | wsdl/soap/standaloneServerStubCreator.rb
Parent: | Object

Methods

dump new

Included Modules

ClassDefCreatorSupport

Attributes

definitions [R]

Public Class methods

new(definitions)

[Source]

# File wsdl/soap/standaloneServerStubCreator.rb, line 24
  def initialize(definitions)
    @definitions = definitions
  end

Public Instance methods

dump(service_name)

[Source]

# File 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


Class: WSDL::SOAP::WSDL2Ruby

Class | WSDL::SOAP::WSDL2Ruby
In: | wsdl/soap/wsdl2ruby.rb
Parent: | Object

Methods

new run

Attributes

basedir | [RW]
location | [RW]
logger | [RW]
opt | [R]

Public Class methods

new()

[Source]

# File wsdl/soap/wsdl2ruby.rb, line 41
  def initialize
    @location = nil
    @opt = {}
    @logger = Logger.new(STDERR)
    @basedir = nil
    @wsdl = nil
    @name = nil
  end

Public Instance methods

run()

[Source]

# File 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


Class: WSDL::Service

Class | WSDL::Service
In: | wsdl/service.rb
Parent: | Info

Methods

new parse_attr parse_element targetnamespace

Attributes

name | [R]
ports | [R]
soap_address | [R]

Public Class methods

new()

[Source]

# File wsdl/service.rb, line 21
  def initialize
    super
    @name = nil
    @ports = XSD::NamedElements.new
    @soap_address = nil
  end

Public Instance methods

parse_attr(attr, value)

[Source]

# File 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
parse_element(element)

[Source]

# File 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
targetnamespace()

[Source]

# File wsdl/service.rb, line 28
  def targetnamespace
    parent.targetnamespace
  end


Class: WSDL::Types

Class | WSDL::Types
In: | wsdl/types.rb
Parent: | Info

Methods

new parse_attr parse_element

Attributes

schemas [R]

Public Class methods

new()

[Source]

# File wsdl/types.rb, line 18
  def initialize
    super
    @schemas = []
  end

Public Instance methods

parse_attr(attr, value)

[Source]

# File wsdl/types.rb, line 37
  def parse_attr(attr, value)
    nil
  end
parse_element(element)

[Source]

# File 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


Module: WSDL::XMLSchema

Module | WSDL::XMLSchema
In: | wsdl/xmlSchema/xsd2ruby.rb wsdl/xmlSchema/unique.rb wsdl/xmlSchema/simpleType.rb wsdl/xmlSchema/simpleRestriction.rb wsdl/xmlSchema/simpleExtension.rb wsdl/xmlSchema/simpleContent.rb wsdl/xmlSchema/sequence.rb wsdl/xmlSchema/schema.rb wsdl/xmlSchema/pattern.rb wsdl/xmlSchema/parser.rb wsdl/xmlSchema/length.rb wsdl/xmlSchema/include.rb wsdl/xmlSchema/importer.rb wsdl/xmlSchema/import.rb wsdl/xmlSchema/enumeration.rb wsdl/xmlSchema/element.rb wsdl/xmlSchema/data.rb wsdl/xmlSchema/content.rb wsdl/xmlSchema/complexType.rb wsdl/xmlSchema/complexContent.rb wsdl/xmlSchema/choice.rb wsdl/xmlSchema/attribute.rb wsdl/xmlSchema/any.rb wsdl/xmlSchema/annotation.rb wsdl/xmlSchema/all.rb wsdl/soap/element.rb 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: | 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()

[Source]

# File wsdl/xmlSchema/all.rb, line 21
  def initialize
    super()
    @minoccurs = '1'
    @maxoccurs = '1'
    @elements = []
  end

Public Instance methods

<<(element)

[Source]

# File wsdl/xmlSchema/all.rb, line 36
  def <<(element)
    @elements << element
  end
elementformdefault()

[Source]

# File wsdl/xmlSchema/all.rb, line 32
  def elementformdefault
    parent.elementformdefault
  end
parse_attr(attr, value)

[Source]

# File 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
parse_element(element)

[Source]

# File 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
targetnamespace()

[Source]

# File wsdl/xmlSchema/all.rb, line 28
  def targetnamespace
    parent.targetnamespace
  end


Class: WSDL::XMLSchema::Annotation

Class | WSDL::XMLSchema::Annotation
In: | wsdl/xmlSchema/annotation.rb
Parent: | Info

Methods

new parse_attr parse_element

Public Class methods

new()

[Source]

# File wsdl/xmlSchema/annotation.rb, line 17
  def initialize
    super
  end

Public Instance methods

parse_attr(attr, value)

[Source]

# File wsdl/xmlSchema/annotation.rb, line 26
  def parse_attr(attr, value)
    # Accepts any attribute.
    true
  end
parse_element(element)

[Source]

# File wsdl/xmlSchema/annotation.rb, line 21
  def parse_element(element)
    # Accepts any element.
    self
  end


Class: WSDL::XMLSchema::Any

Class | WSDL::XMLSchema::Any
In: | 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()

[Source]

# File wsdl/xmlSchema/any.rb, line 22
  def initialize
    super()
    @maxoccurs = '1'
    @minoccurs = '1'
    @namespace = '##any'
    @process_contents = 'strict'
  end

Public Instance methods

parse_attr(attr, value)

[Source]

# File 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
parse_element(element)

[Source]

# File wsdl/xmlSchema/any.rb, line 34
  def parse_element(element)
    nil
  end
targetnamespace()

[Source]

# File wsdl/xmlSchema/any.rb, line 30
  def targetnamespace
    parent.targetnamespace
  end


Class: WSDL::XMLSchema::Attribute

Class | WSDL::XMLSchema::Attribute
In: | 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)

[Source]

# File 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(symbol)

[Source]

# File 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()

[Source]

# File 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

Public Instance methods

parse_attr(attr, value)

[Source]

# File 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
parse_element(element)

[Source]

# File wsdl/xmlSchema/attribute.rb, line 80
  def parse_element(element)
    case element
    when SimpleTypeName
      @local_simpletype = SimpleType.new
      @local_simpletype
    end
  end
refelement()

[Source]

# File wsdl/xmlSchema/attribute.rb, line 72
  def refelement
    @refelement ||= root.collect_attributes[@ref]
  end
targetnamespace()

[Source]

# File wsdl/xmlSchema/attribute.rb, line 76
  def targetnamespace
    parent.targetnamespace
  end


Class: WSDL::XMLSchema::Choice

Class | WSDL::XMLSchema::Choice
In: | 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()

[Source]

# File wsdl/xmlSchema/choice.rb, line 21
  def initialize
    super()
    @minoccurs = '1'
    @maxoccurs = '1'
    @elements = []
  end

Public Instance methods

<<(element)

[Source]

# File wsdl/xmlSchema/choice.rb, line 36
  def <<(element)
    @elements << element
  end
elementformdefault()

[Source]

# File wsdl/xmlSchema/choice.rb, line 32
  def elementformdefault
    parent.elementformdefault
  end
parse_attr(attr, value)

[Source]

# File 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
parse_element(element)

[Source]

# File 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
targetnamespace()

[Source]

# File wsdl/xmlSchema/choice.rb, line 28
  def targetnamespace
    parent.targetnamespace
  end


Class: WSDL::XMLSchema::ComplexContent

Class | WSDL::XMLSchema::ComplexContent
In: | wsdl/xmlSchema/complexContent.rb
Parent: | Info

Methods

basetype new parse_attr parse_element targetnamespace

Attributes

attributes | [R]
base | [RW]
content | [R]
derivetype | [R]

Public Class methods

new()

[Source]

# File wsdl/xmlSchema/complexContent.rb, line 23
  def initialize
    super
    @base = nil
    @derivetype = nil
    @content = nil
    @attributes = XSD::NamedElements.new
    @basetype = nil
  end

Public Instance methods

basetype()

[Source]

# File wsdl/xmlSchema/complexContent.rb, line 36
  def basetype
    @basetype ||= root.collect_complextypes[@base]
  end
parse_attr(attr, value)

[Source]

# File wsdl/xmlSchema/complexContent.rb, line 73
  def parse_attr(attr, value)
    if @derivetype.nil?
      return nil
    end
    case attr
    when BaseAttrName
      @base = value
    else
      nil
    end
  end
parse_element(element)

[Source]

# File wsdl/xmlSchema/complexContent.rb, line 40
  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
targetnamespace()

[Source]

# File wsdl/xmlSchema/complexContent.rb, line 32
  def targetnamespace
    parent.targetnamespace
  end


Class: WSDL::XMLSchema::ComplexType

Class | WSDL::XMLSchema::ComplexType
In: | wsdl/xmlSchema/complexType.rb 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)

[Source]

# File 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

Public Instance methods

all_elements=(elements)

[Source]

# File wsdl/xmlSchema/complexType.rb, line 95
  def all_elements=(elements)
    @content = All.new
    elements.each do |element|
      @content << element
    end
  end
check_type()

[Source]

# File 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_defined_complextype(name)

[Source]

# File 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
child_type(name = nil)

[Source]

# File 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
compoundtype()

[Source]

# File wsdl/soap/complexType.rb, line 18
  def compoundtype
    @compoundtype ||= check_type
  end
each_element() {|AnyAsElement| ...}

[Source]

# File 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
elementformdefault()

[Source]

# File wsdl/xmlSchema/complexType.rb, line 45
  def elementformdefault
    parent.elementformdefault
  end
find_aryelement()

[Source]

# File 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
find_arytype()

[Source]

# File 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_element(name)

[Source]

# File 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(name)

[Source]

# File 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
parse_attr(attr, value)

[Source]

# File 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
parse_element(element)

[Source]

# File 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
sequence_elements=(elements)

[Source]

# File wsdl/xmlSchema/complexType.rb, line 88
  def sequence_elements=(elements)
    @content = Sequence.new
    elements.each do |element|
      @content << element
    end
  end
targetnamespace()

[Source]

# File 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


Class: WSDL::XMLSchema::Content

Class | WSDL::XMLSchema::Content
In: | 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()

[Source]

# File wsdl/xmlSchema/content.rb, line 23
  def initialize
    super()
    @final = nil
    @mixed = false
    @type = nil
    @contents = []
    @elements = []
  end

Public Instance methods

<<(content)

[Source]

# File wsdl/xmlSchema/content.rb, line 36
  def <<(content)
    @contents << content
    update_elements
  end
each() {|content| ...}

[Source]

# File wsdl/xmlSchema/content.rb, line 41
  def each
    @contents.each do |content|
      yield content
    end
  end
parse_attr(attr, value)

[Source]

# File 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_element(element)

[Source]

# File 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_epilogue()

[Source]

# File wsdl/xmlSchema/content.rb, line 78
  def parse_epilogue
    update_elements
  end
targetnamespace()

[Source]

# File wsdl/xmlSchema/content.rb, line 32
  def targetnamespace
    parent.targetnamespace
  end


Class: WSDL::XMLSchema::Element

Class | WSDL::XMLSchema::Element
In: | wsdl/xmlSchema/element.rb 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)

[Source]

# File 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(symbol)

[Source]

# File 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(name = nil, type = nil)

[Source]

# File 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

Public Instance methods

attributes()

[Source]

# File wsdl/soap/element.rb, line 21
  def attributes
    @local_complextype.attributes
  end
elementform()

[Source]

# File wsdl/xmlSchema/element.rb, line 87
  def elementform
    self.form.nil? ? parent.elementformdefault : self.form
  end
elementformdefault()

[Source]

# File wsdl/xmlSchema/element.rb, line 83
  def elementformdefault
    parent.elementformdefault
  end
map_as_array?()

[Source]

# File wsdl/soap/element.rb, line 17
  def map_as_array?
    maxoccurs != '1'
  end
parse_attr(attr, value)

[Source]

# File 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
parse_element(element)

[Source]

# File 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
refelement()

[Source]

# File wsdl/xmlSchema/element.rb, line 75
  def refelement
    @refelement ||= (@ref ? root.collect_elements[@ref] : nil)
  end
targetnamespace()

[Source]

# File wsdl/xmlSchema/element.rb, line 79
  def targetnamespace
    parent.targetnamespace
  end


Class: WSDL::XMLSchema::Enumeration

Class | WSDL::XMLSchema::Enumeration
In: | wsdl/xmlSchema/enumeration.rb
Parent: | Info

Methods

new parse_attr parse_element

Public Class methods

new()

[Source]

# File wsdl/xmlSchema/enumeration.rb, line 17
  def initialize
    super
  end

Public Instance methods

parse_attr(attr, value)

[Source]

# File wsdl/xmlSchema/enumeration.rb, line 25
  def parse_attr(attr, value)
    case attr
    when ValueAttrName
      parent.enumeration << value.source
      value.source
    end
  end
parse_element(element)

[Source]

# File wsdl/xmlSchema/enumeration.rb, line 21
  def parse_element(element)
    nil
  end


Class: WSDL::XMLSchema::Import

Class | WSDL::XMLSchema::Import
In: | wsdl/xmlSchema/import.rb
Parent: | Info

Methods

new parse_attr parse_element

Attributes

content | [R]
namespace | [R]
schemalocation | [R]

Public Class methods

new()

[Source]

# File wsdl/xmlSchema/import.rb, line 22
  def initialize
    super
    @namespace = nil
    @schemalocation = nil
    @content = nil
  end

Public Instance methods

parse_attr(attr, value)

[Source]

# File 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
parse_element(element)

[Source]

# File wsdl/xmlSchema/import.rb, line 29
  def parse_element(element)
    nil
  end


Class: WSDL::XMLSchema::Importer

Class | WSDL::XMLSchema::Importer
In: | wsdl/xmlSchema/importer.rb
Parent: | Object

Methods

import import new

Public Class methods

import(location, originalroot = nil)

[Source]

# File wsdl/xmlSchema/importer.rb, line 18
  def self.import(location, originalroot = nil)
    new.import(location, originalroot)
  end
new()

[Source]

# File wsdl/xmlSchema/importer.rb, line 22
  def initialize
    @web_client = nil
  end

Public Instance methods

import(location, originalroot = nil)

[Source]

# File 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


Class: WSDL::XMLSchema::Include

Class | WSDL::XMLSchema::Include
In: | wsdl/xmlSchema/include.rb
Parent: | Info

Methods

new parse_attr parse_element

Attributes

content | [R]
schemalocation | [R]

Public Class methods

new()

[Source]

# File wsdl/xmlSchema/include.rb, line 21
  def initialize
    super
    @schemalocation = nil
    @content = nil
  end

Public Instance methods

parse_attr(attr, value)

[Source]

# File 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
parse_element(element)

[Source]

# File wsdl/xmlSchema/include.rb, line 27
  def parse_element(element)
    nil
  end


Class: WSDL::XMLSchema::Length

Class | WSDL::XMLSchema::Length
In: | wsdl/xmlSchema/length.rb
Parent: | Info

Methods

new parse_attr parse_element

Public Class methods

new()

[Source]

# File wsdl/xmlSchema/length.rb, line 17
  def initialize
    super
  end

Public Instance methods

parse_attr(attr, value)

[Source]

# File wsdl/xmlSchema/length.rb, line 25
  def parse_attr(attr, value)
    case attr
    when ValueAttrName
      value.source
    end
  end
parse_element(element)

[Source]

# File wsdl/xmlSchema/length.rb, line 21
  def parse_element(element)
    nil
  end


Class: WSDL::XMLSchema::Parser

Class | WSDL::XMLSchema::Parser
In: | 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 = {})

[Source]

# File 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

Public Instance methods

characters(text)

[Source]

# File 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
charset()

[Source]

# File wsdl/xmlSchema/parser.rb, line 67
  def charset
    @parser.charset
  end
end_element(name)

[Source]

# File 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
parse(string_or_readable)

[Source]

# File wsdl/xmlSchema/parser.rb, line 59
  def parse(string_or_readable)
    @parsestack = []
    @lastnode = nil
    @textbuf = ''
    @parser.do_parse(string_or_readable)
    @lastnode
  end
start_element(name, attrs)

[Source]

# File 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


Class: WSDL::XMLSchema::Parser::AttributeConstraintError

Class | WSDL::XMLSchema::Parser::AttributeConstraintError
In: | wsdl/xmlSchema/parser.rb
Parent: | FormatDecodeError


Class: WSDL::XMLSchema::Parser::ElementConstraintError

Class | WSDL::XMLSchema::Parser::ElementConstraintError
In: | wsdl/xmlSchema/parser.rb
Parent: | FormatDecodeError


Class: WSDL::XMLSchema::Parser::FormatDecodeError

Class | WSDL::XMLSchema::Parser::FormatDecodeError
In: | wsdl/xmlSchema/parser.rb
Parent: | ParseError


Class: WSDL::XMLSchema::Parser::ParseError

Class | WSDL::XMLSchema::Parser::ParseError
In: | wsdl/xmlSchema/parser.rb
Parent: | Error


Class: WSDL::XMLSchema::Parser::ParseFrame

Class | WSDL::XMLSchema::Parser::ParseFrame
In: | wsdl/xmlSchema/parser.rb
Parent: | Object

Methods

new

Attributes

name | [R]
node | [RW]
ns | [R]

Public Class methods

new(ns, name, node)

[Source]

# File wsdl/xmlSchema/parser.rb, line 41
    def initialize(ns, name, node)
      @ns = ns
      @name = name
      @node = node
    end


Class: WSDL::XMLSchema::Parser::UnexpectedElementError

Class | WSDL::XMLSchema::Parser::UnexpectedElementError
In: | wsdl/xmlSchema/parser.rb
Parent: | FormatDecodeError


Class: WSDL::XMLSchema::Parser::UnknownAttributeError

Class | WSDL::XMLSchema::Parser::UnknownAttributeError
In: | wsdl/xmlSchema/parser.rb
Parent: | FormatDecodeError


Class: WSDL::XMLSchema::Parser::UnknownElementError

Class | WSDL::XMLSchema::Parser::UnknownElementError
In: | wsdl/xmlSchema/parser.rb
Parent: | FormatDecodeError


Class: WSDL::XMLSchema::Pattern

Class | WSDL::XMLSchema::Pattern
In: | wsdl/xmlSchema/pattern.rb
Parent: | Info

Methods

new parse_attr parse_element

Public Class methods

new()

[Source]

# File wsdl/xmlSchema/pattern.rb, line 17
  def initialize
    super
  end

Public Instance methods

parse_attr(attr, value)

[Source]

# File 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
parse_element(element)

[Source]

# File wsdl/xmlSchema/pattern.rb, line 21
  def parse_element(element)
    nil
  end


Class: WSDL::XMLSchema::Schema

Class | WSDL::XMLSchema::Schema
In: | 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()

[Source]

# File 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
parse_element(element)

[Source]

# File wsdl/xmlSchema/schema.rb, line 132
  def self.parse_element(element)
    if element == SchemaName
      Schema.new
    else
      nil
    end
  end

Public Instance methods

collect_attributes()

[Source]

# File 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_complextypes()

[Source]

# File 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_elements()

[Source]

# File 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_simpletypes()

[Source]

# File 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
location()

[Source]

# File wsdl/xmlSchema/schema.rb, line 44
  def location
    @location || (root.nil? ? nil : root.location)
  end
location=(location)

[Source]

# File wsdl/xmlSchema/schema.rb, line 48
  def location=(location)
    @location = location
  end
parse_attr(attr, value)

[Source]

# File 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
parse_element(element)

[Source]

# File 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


Class: WSDL::XMLSchema::Sequence

Class | WSDL::XMLSchema::Sequence
In: | 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()

[Source]

# File wsdl/xmlSchema/sequence.rb, line 21
  def initialize
    super()
    @minoccurs = '1'
    @maxoccurs = '1'
    @elements = []
  end

Public Instance methods

<<(element)

[Source]

# File wsdl/xmlSchema/sequence.rb, line 36
  def <<(element)
    @elements << element
  end
elementformdefault()

[Source]

# File wsdl/xmlSchema/sequence.rb, line 32
  def elementformdefault
    parent.elementformdefault
  end
parse_attr(attr, value)

[Source]

# File 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
parse_element(element)

[Source]

# File 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
targetnamespace()

[Source]

# File wsdl/xmlSchema/sequence.rb, line 28
  def targetnamespace
    parent.targetnamespace
  end


Class: WSDL::XMLSchema::SimpleContent

Class | WSDL::XMLSchema::SimpleContent
In: | wsdl/xmlSchema/simpleContent.rb
Parent: | Info

Methods

base check_lexical_format new parse_element targetnamespace

Attributes

extension | [R]
restriction | [R]

Public Class methods

new()

[Source]

# File wsdl/xmlSchema/simpleContent.rb, line 25
  def initialize
    super
    @restriction = nil
    @extension = nil
  end

Public Instance methods

base()

[Source]

# File wsdl/xmlSchema/simpleContent.rb, line 31
  def base
    content.base
  end
check_lexical_format(value)

[Source]

# File wsdl/xmlSchema/simpleContent.rb, line 21
  def check_lexical_format(value)
    check(value)
  end
parse_element(element)

[Source]

# File 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
targetnamespace()

[Source]

# File wsdl/xmlSchema/simpleContent.rb, line 35
  def targetnamespace
    parent.targetnamespace
  end


Class: WSDL::XMLSchema::SimpleExtension

Class | WSDL::XMLSchema::SimpleExtension
In: | wsdl/xmlSchema/simpleExtension.rb
Parent: | Info

Methods

new parse_attr parse_element targetnamespace valid?

Attributes

attributes | [R]
base | [R]

Public Class methods

new()

[Source]

# File wsdl/xmlSchema/simpleExtension.rb, line 21
  def initialize
    super
    @base = nil
    @attributes = XSD::NamedElements.new
  end

Public Instance methods

parse_attr(attr, value)

[Source]

# File wsdl/xmlSchema/simpleExtension.rb, line 44
  def parse_attr(attr, value)
    case attr
    when BaseAttrName
      @base = value
    end
  end
parse_element(element)

[Source]

# File wsdl/xmlSchema/simpleExtension.rb, line 35
  def parse_element(element)
    case element
    when AttributeName
      o = Attribute.new
      @attributes << o
      o
    end
  end
targetnamespace()

[Source]

# File wsdl/xmlSchema/simpleExtension.rb, line 27
  def targetnamespace
    parent.targetnamespace
  end
valid?(value)

[Source]

# File wsdl/xmlSchema/simpleExtension.rb, line 31
  def valid?(value)
    true
  end


Class: WSDL::XMLSchema::SimpleRestriction

Class | WSDL::XMLSchema::SimpleRestriction
In: | 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()

[Source]

# File wsdl/xmlSchema/simpleRestriction.rb, line 23
  def initialize
    super
    @base = nil
    @enumeration = []   # NamedElements?
    @length = nil
    @pattern = nil
  end

Public Instance methods

parse_attr(attr, value)

[Source]

# File wsdl/xmlSchema/simpleRestriction.rb, line 49
  def parse_attr(attr, value)
    case attr
    when BaseAttrName
      @base = value
    end
  end
parse_element(element)

[Source]

# File 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
valid?(value)

[Source]

# File 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


Class: WSDL::XMLSchema::SimpleType

Class | WSDL::XMLSchema::SimpleType
In: | 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)

[Source]

# File wsdl/xmlSchema/simpleType.rb, line 37
  def initialize(name = nil)
    super()
    @name = name
    @restriction = nil
  end

Public Instance methods

base()

[Source]

# File wsdl/xmlSchema/simpleType.rb, line 29
  def base
    if @restriction
      @restriction.base
    else
      raise ArgumentError.new("incomplete simpleType")
    end
  end
check_lexical_format(value)

[Source]

# File wsdl/xmlSchema/simpleType.rb, line 21
  def check_lexical_format(value)
    if @restriction
      check_restriction(value)
    else
      raise ArgumentError.new("incomplete simpleType")
    end
  end
parse_attr(attr, value)

[Source]

# File wsdl/xmlSchema/simpleType.rb, line 55
  def parse_attr(attr, value)
    case attr
    when NameAttrName
      @name = XSD::QName.new(targetnamespace, value.source)
    end
  end
parse_element(element)

[Source]

# File wsdl/xmlSchema/simpleType.rb, line 47
  def parse_element(element)
    case element
    when RestrictionName
      @restriction = SimpleRestriction.new
      @restriction
    end
  end
targetnamespace()

[Source]

# File wsdl/xmlSchema/simpleType.rb, line 43
  def targetnamespace
    parent.targetnamespace
  end


Class: WSDL::XMLSchema::Unique

Class | WSDL::XMLSchema::Unique
In: | wsdl/xmlSchema/unique.rb
Parent: | Info

Methods

new parse_attr parse_element

Public Class methods

new()

[Source]

# File wsdl/xmlSchema/unique.rb, line 17
  def initialize
    super
  end

Public Instance methods

parse_attr(attr, value)

[Source]

# File wsdl/xmlSchema/unique.rb, line 26
  def parse_attr(attr, value)
    # Accepts any attribute.
    true
  end
parse_element(element)

[Source]

# File wsdl/xmlSchema/unique.rb, line 21
  def parse_element(element)
    # Accepts any element.
    self
  end


Class: WSDL::XMLSchema::XSD2Ruby

Class | WSDL::XMLSchema::XSD2Ruby
In: | wsdl/xmlSchema/xsd2ruby.rb
Parent: | Object

Methods

new run

Attributes

basedir | [RW]
location | [RW]
logger | [RW]
opt | [R]

Public Class methods

new()

[Source]

# File wsdl/xmlSchema/xsd2ruby.rb, line 35
  def initialize
    @location = nil
    @opt = {}
    @logger = Logger.new(STDERR)
    @basedir = nil
    @xsd = nil
    @name = nil
  end

Public Instance methods

run()

[Source]

# File 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


File: binding.rb

binding.rb

Path: | wsdl/binding.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/data.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/definitions.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/documentation.rb
Last Update: | Tue Nov 25 17:31:30 AUS Eastern Daylight Time 2003

WSDL4R - WSDL SOAP documentation element. Copyright (C) 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: import.rb

import.rb

Path: | wsdl/import.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/importer.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/info.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

WSDL4R - WSDL information base. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.


File: message.rb

message.rb

Path: | wsdl/message.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

WSDL4R - WSDL message definition. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: operation.rb

operation.rb

Path: | wsdl/operation.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

WSDL4R - WSDL operation definition. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: operationBinding.rb

operationBinding.rb

Path: | wsdl/operationBinding.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/param.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

WSDL4R - WSDL param definition. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: parser.rb

parser.rb

Path: | wsdl/parser.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/part.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

WSDL4R - WSDL part definition. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: port.rb

port.rb

Path: | wsdl/port.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

WSDL4R - WSDL port definition. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: portType.rb

portType.rb

Path: | wsdl/portType.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/service.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

WSDL4R - WSDL service definition. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info xsd/namedelements


File: address.rb

address.rb

Path: | wsdl/soap/address.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/soap/binding.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/soap/body.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/soap/cgiStubCreator.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/soap/classDefCreator.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/soap/classDefCreatorSupport.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/soap/clientSkeltonCreator.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/soap/complexType.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/soap/data.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/soap/definitions.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/soap/driverCreator.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/soap/element.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/soap/fault.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/soap/header.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/soap/headerfault.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/soap/mappingRegistryCreator.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/soap/methodDefCreator.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/soap/operation.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/soap/servantSkeltonCreator.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/soap/standaloneServerStubCreator.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/soap/wsdl2ruby.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: types.rb

types.rb

Path: | wsdl/types.rb
Last Update: | Tue Nov 25 17:31:30 AUS Eastern Daylight Time 2003

WSDL4R - WSDL types definition. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: wsdl.rb

wsdl.rb

Path: | wsdl/wsdl.rb
Last Update: | Tue Nov 25 17:31:30 AUS Eastern Daylight Time 2003

WSDL4R - Base definitions. Copyright (C) 2000, 2001, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/qname


File: all.rb

all.rb

Path: | wsdl/xmlSchema/all.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/xmlSchema/annotation.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/xmlSchema/any.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/xmlSchema/attribute.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/xmlSchema/choice.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/xmlSchema/complexContent.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/xmlSchema/complexType.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/xmlSchema/content.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/xmlSchema/data.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/xmlSchema/element.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/xmlSchema/enumeration.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/xmlSchema/import.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/xmlSchema/importer.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/xmlSchema/include.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/xmlSchema/length.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/xmlSchema/parser.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/xmlSchema/pattern.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/xmlSchema/schema.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/xmlSchema/sequence.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/xmlSchema/simpleContent.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/xmlSchema/simpleExtension.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/xmlSchema/simpleRestriction.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/xmlSchema/simpleType.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | wsdl/xmlSchema/unique.rb
Last Update: | Tue Nov 25 17:31:31 AUS Eastern Daylight Time 2003

WSDL4R - XMLSchema unique element. Copyright (C) 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: xsd2ruby.rb

xsd2ruby.rb

Path: | wsdl/xmlSchema/xsd2ruby.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: README.txt

README.txt

Path: | xmlrpc/README.txt
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

XMLRPC for Ruby, Standard Library Documentation

Overview

XMLRPC is a lightweight protocol that enables remote procedure calls over HTTP. It is defined at www.xmlrpc.com.

XMLRPC allows you to create simple distributed computing solutions that span computer languages. Its distinctive feature is its simplicity compared to other approaches like SOAP and CORBA.

The Ruby standard library package ‘xmlrpc’ enables you to create a server that implements remote procedures and a client that calls them. Very little code is required to achieve either of these.

Example

Try the following code. It calls a standard demonstration remote procedure.

  require 'xmlrpc/client'
  require 'pp'

  server = XMLRPC::Client.new2("http://xmlrpc-c.sourceforge.net/api/sample.php")
  result = server.call("sample.sumAndDifference", 5, 3)
  pp result

Documentation

See www.ntecs.de/projects/xmlrpc4r. There is plenty of detail there to use the client and implement a server.


Class: HttpServer

Class | HttpServer
In: | xmlrpc/httpserver.rb
Parent: | GServer

Methods

new

Classes and Modules

Class HttpServer::Request
Class HttpServer::Response
Class HttpServer::Table

Constants

CRLF | = | "\r\n" | Constants ————————————————
HTTP_PROTO | = | "HTTP/1.0"
SERVER_NAME | = | "HttpServer (Ruby #{RUBY_VERSION})"
DEFAULT_HEADER | = | { "Server" => SERVER_NAME
StatusCodeMapping | = | { 200 => "OK", 400 => "Bad Request", 403 => "Forbidden", 405 => "Method Not Allowed", 411 => "Length Required", 500 => "Internal Server Error" | Mapping of status code and error message

Public Class methods

new(handle_obj, port = 8080, host = DEFAULT_HOST, maxConnections = 4, stdlog = $stdout, audit = true, debug = true)

handle_obj specifies the object, that receives calls to request_handler and ip_auth_handler

[Source]

# File xmlrpc/httpserver.rb, line 18
  def initialize(handle_obj, port = 8080, host = DEFAULT_HOST, maxConnections = 4,
                 stdlog = $stdout, audit = true, debug = true)
    @handler = handle_obj
    super(port, host, maxConnections, stdlog, audit, debug)
  end


Class: HttpServer::Request

Class | HttpServer::Request
In: | xmlrpc/httpserver.rb
Parent: | Object

Classes ————————————————-

Methods

content_length new

Attributes

data | [R]
header | [R]
method | [R]
path | [R]
proto | [R]

Public Class methods

new(data, method=nil, path=nil, proto=nil)

[Source]

# File xmlrpc/httpserver.rb, line 53
    def initialize(data, method=nil, path=nil, proto=nil)
      @header, @data = Table.new, data
      @method, @path, @proto = method, path, proto
    end

Public Instance methods

content_length()

[Source]

# File xmlrpc/httpserver.rb, line 58
    def content_length
      len = @header['Content-Length']
      return nil if len.nil?
      return len.to_i
    end


Class: HttpServer::Response

Class | HttpServer::Response
In: | xmlrpc/httpserver.rb
Parent: | Object

Methods

new

Attributes

body | [RW]
header | [R]
status | [RW]
status_message | [RW]

Public Class methods

new(status=200)

[Source]

# File xmlrpc/httpserver.rb, line 70
    def initialize(status=200)
      @status = status
      @status_message = nil
      @header = Table.new
    end


Class: HttpServer::Table

Class | HttpServer::Table
In: | xmlrpc/httpserver.rb
Parent: | Object

a case-insensitive Hash class for HTTP header

Methods

[] []= each new update writeTo

Included Modules

Enumerable

Public Class methods

new(hash={})

[Source]

# File xmlrpc/httpserver.rb, line 84
    def initialize(hash={})
      @hash = hash
      update(hash)
    end

Public Instance methods

[](key)

[Source]

# File xmlrpc/httpserver.rb, line 89
    def [](key)
      @hash[key.to_s.capitalize]
    end
[]=(key, value)

[Source]

# File xmlrpc/httpserver.rb, line 93
    def []=(key, value)
      @hash[key.to_s.capitalize] = value
    end
each() {|k.capitalize, v| ...}

[Source]

# File xmlrpc/httpserver.rb, line 102
    def each
      @hash.each {|k,v| yield k.capitalize, v }
    end
update(hash)

[Source]

# File xmlrpc/httpserver.rb, line 97
    def update(hash)
      hash.each {|k,v| self[k] = v}
      self
    end
writeTo(port)

[Source]

# File xmlrpc/httpserver.rb, line 106
    def writeTo(port)
      each { |k,v| port << "#{k}: #{v}" << CRLF }
    end


Module: NQXML

Module | NQXML
In: | xmlrpc/parser.rb

add some methods to NQXML::Node

Classes and Modules

Class NQXML::Node


Class: NQXML::Node

Class | NQXML::Node
In: | xmlrpc/parser.rb
Parent: | Object

Methods

[] childNodes hasChildNodes nodeName nodeType nodeValue removeChild

Public Instance methods

[](index)

[Source]

# File xmlrpc/parser.rb, line 28
    def [] (index)
      @children[index]
    end
childNodes()

[Source]

# File xmlrpc/parser.rb, line 22
    def childNodes
      @children
    end
hasChildNodes()

[Source]

# File xmlrpc/parser.rb, line 25
    def hasChildNodes
      not @children.empty?
    end
nodeName()

[Source]

# File xmlrpc/parser.rb, line 45
    def nodeName
      #TODO: error when wrong Entity-type
      @entity.name
    end
nodeType()

[Source]

# File xmlrpc/parser.rb, line 32
    def nodeType
      if @entity.instance_of? NQXML::Text then :TEXT
      elsif @entity.instance_of? NQXML::Comment then :COMMENT
      #elsif @entity.instance_of? NQXML::Element then :ELEMENT
      elsif @entity.instance_of? NQXML::Tag then :ELEMENT
      else :ELSE
      end
    end
nodeValue()

[Source]

# File xmlrpc/parser.rb, line 41
    def nodeValue
      #TODO: error when wrong Entity-type
      @entity.text
    end
removeChild(node)

[Source]

# File xmlrpc/parser.rb, line 19
    def removeChild(node)
      @children.delete(node)
    end


Module: XMLRPC

Module | XMLRPC
In: | xmlrpc/utils.rb xmlrpc/server.rb xmlrpc/parser.rb xmlrpc/marshal.rb xmlrpc/datetime.rb xmlrpc/create.rb xmlrpc/config.rb xmlrpc/client.rb xmlrpc/base64.rb

$Id: config.rb,v 1.1 2003/07/19 10:05:54 matz Exp $ Configuration file for XML-RPC for Ruby

Methods

iPIMethods interface

Classes and Modules

Module XMLRPC::Config
Module XMLRPC::Convert
Module XMLRPC::Marshallable
Module XMLRPC::ParseContentType
Module XMLRPC::ParserWriterChooseMixin
Module XMLRPC::Service
Module XMLRPC::XMLParser
Module XMLRPC::XMLWriter
Class XMLRPC::Base64
Class XMLRPC::BasicServer
Class XMLRPC::CGIServer
Class XMLRPC::Client
Class XMLRPC::Create
Class XMLRPC::DateTime
Class XMLRPC::FaultException
Class XMLRPC::Marshal
Class XMLRPC::ModRubyServer
Class XMLRPC::Server
Class XMLRPC::WEBrickServlet

Public Class methods

iPIMethods(prefix)

short-cut for creating a PublicInstanceMethodsInterface

[Source]

# File xmlrpc/utils.rb, line 152
  def self.iPIMethods(prefix)
    Service::PublicInstanceMethodsInterface.new(prefix)
  end
interface(prefix, &p)

short-form to create a Service::Interface

[Source]

# File xmlrpc/utils.rb, line 147
  def self.interface(prefix, &p)
    Service::Interface.new(prefix, &p)
  end


Class: XMLRPC::Base64

Class | XMLRPC::Base64
In: | xmlrpc/base64.rb
Parent: | Object

Methods

decode decoded encode encoded new

Public Class methods

decode(str)

[Source]

# File xmlrpc/base64.rb, line 64
  def Base64.decode(str)
    str.gsub(/\s+/, "").unpack("m")[0]
  end
encode(str)

[Source]

# File xmlrpc/base64.rb, line 68
  def Base64.encode(str)
    [str].pack("m")
  end
new(str, state = :dec)

[Source]

# File xmlrpc/base64.rb, line 44
  def initialize(str, state = :dec)
    case state
    when :enc
      @str = Base64.decode(str)
    when :dec
      @str = str
    else
      raise ArgumentError, "wrong argument; either :enc or :dec"
    end
  end

Public Instance methods

decoded()

[Source]

# File xmlrpc/base64.rb, line 55
  def decoded
    @str
  end
encoded()

[Source]

# File xmlrpc/base64.rb, line 59
  def encoded
    Base64.encode(@str)
  end


Class: XMLRPC::BasicServer

Class | XMLRPC::BasicServer
In: | xmlrpc/server.rb
Parent: | Object

Methods

add_handler add_introspection add_multicall get_default_handler get_service_hook new process set_default_handler set_service_hook

Included Modules

ParserWriterChooseMixin ParseContentType

Constants

ERR_METHOD_MISSING | = | 1
ERR_UNCAUGHT_EXCEPTION | = | 2
ERR_MC_WRONG_PARAM | = | 3
ERR_MC_MISSING_PARAMS | = | 4
ERR_MC_MISSING_METHNAME | = | 5
ERR_MC_RECURSIVE_CALL | = | 6
ERR_MC_WRONG_PARAM_PARAMS | = | 7
ERR_MC_EXPECTED_STRUCT | = | 8

Public Class methods

new(class_delim=".")

[Source]

# File xmlrpc/server.rb, line 170
  def initialize(class_delim=".")
    @handler = []
    @default_handler = nil
    @service_hook = nil

    @class_delim = class_delim
    @create = nil
    @parser = nil

    add_multicall     if Config::ENABLE_MULTICALL
    add_introspection if Config::ENABLE_INTROSPECTION
  end

Public Instance methods

add_handler(prefix, obj_or_signature=nil, help=nil, &block)

[Source]

# File xmlrpc/server.rb, line 183
  def add_handler(prefix, obj_or_signature=nil, help=nil, &block)
    if block_given?
      # proc-handler
      @handler << [prefix, block, obj_or_signature, help]
    else
      if prefix.kind_of? String
        # class-handler
        raise ArgumentError, "Expected non-nil value" if obj_or_signature.nil?
        @handler << [prefix + @class_delim, obj_or_signature]
      elsif prefix.kind_of? XMLRPC::Service::BasicInterface
        # class-handler with interface
        # add all methods
        @handler += prefix.get_methods(obj_or_signature, @class_delim)
      else
        raise ArgumentError, "Wrong type for parameter 'prefix'"
      end
    end
    self
  end
add_introspection()

[Source]

# File xmlrpc/server.rb, line 263
  def add_introspection
    add_handler("system.listMethods",%w(array), "List methods available on this XML-RPC server") do
      methods = []
      @handler.each do |name, obj|
        if obj.kind_of? Proc
          methods << name
        else
          obj.methods.each {|meth| methods << name + meth}
        end
      end
      methods
    end

    add_handler("system.methodSignature", %w(array string), "Returns method signature") do |meth|
      sigs = []
      @handler.each do |name, obj, sig|
        if obj.kind_of? Proc and sig != nil and name == meth
          if sig[0].kind_of? Array
            # sig contains multiple signatures, e.g. [["array"], ["array", "string"]]
            sig.each {|s| sigs << s}
          else
            # sig is a single signature, e.g. ["array"]
            sigs << sig
          end
        end
      end
      sigs.uniq! || sigs  # remove eventually duplicated signatures
    end

    add_handler("system.methodHelp", %w(string string), "Returns help on using this method") do |meth|
      help = nil
      @handler.each do |name, obj, sig, hlp|
        if obj.kind_of? Proc and name == meth
          help = hlp
          break
        end
      end
      help || ""
    end

    self
  end
add_multicall()

[Source]

# File xmlrpc/server.rb, line 221
  def add_multicall
    add_handler("system.multicall", %w(array array), "Multicall Extension") do |arrStructs|
      unless arrStructs.is_a? Array
        raise XMLRPC::FaultException.new(ERR_MC_WRONG_PARAM, "system.multicall expects an array")
      end

      arrStructs.collect {|call|
        if call.is_a? Hash
          methodName = call["methodName"]
          params     = call["params"]

          if params.nil?
            multicall_fault(ERR_MC_MISSING_PARAMS, "Missing params")
          elsif methodName.nil?
            multicall_fault(ERR_MC_MISSING_METHNAME, "Missing methodName")
          else
            if methodName == "system.multicall"
              multicall_fault(ERR_MC_RECURSIVE_CALL, "Recursive system.multicall forbidden")
            else
              unless params.is_a? Array
                multicall_fault(ERR_MC_WRONG_PARAM_PARAMS, "Parameter params have to be an Array")
              else
                ok, val = call_method(methodName, *params)
                if ok
                  # correct return value
                  [val]
                else
                  # exception
                  multicall_fault(val.faultCode, val.faultString)
                end
              end
            end
          end

        else
          multicall_fault(ERR_MC_EXPECTED_STRUCT, "system.multicall expected struct")
        end
      }
    end # end add_handler
    self
  end
get_default_handler()

[Source]

# File xmlrpc/server.rb, line 212
  def get_default_handler
    @default_handler
  end
get_service_hook()

[Source]

# File xmlrpc/server.rb, line 203
  def get_service_hook
    @service_hook
  end
process(data)

[Source]

# File xmlrpc/server.rb, line 308
  def process(data)
    method, params = parser().parseMethodCall(data)
    handle(method, *params)
  end
set_default_handler(&handler)

[Source]

# File xmlrpc/server.rb, line 216
  def set_default_handler (&handler)
    @default_handler = handler
    self
  end
set_service_hook(&handler)

[Source]

# File xmlrpc/server.rb, line 207
  def set_service_hook(&handler)
    @service_hook = handler
    self
  end


Class: XMLRPC::CGIServer

Class | XMLRPC::CGIServer
In: | xmlrpc/server.rb
Parent: | BasicServer

Methods

new new serve

Public Class methods

new(*a)

[Source]

# File xmlrpc/server.rb, line 436
  def CGIServer.new(*a)
    @@obj = super(*a) if @@obj.nil?
    @@obj
  end
new(*a)

[Source]

# File xmlrpc/server.rb, line 441
  def initialize(*a)
    super(*a)
  end

Public Instance methods

serve()

[Source]

# File xmlrpc/server.rb, line 445
  def serve
    catch(:exit_serve) {
      length = ENV['CONTENT_LENGTH'].to_i

      http_error(405, "Method Not Allowed") unless ENV['REQUEST_METHOD'] == "POST"
      http_error(400, "Bad Request")        unless parse_content_type(ENV['CONTENT_TYPE']).first == "text/xml"
      http_error(411, "Length Required")    unless length > 0

      # TODO: do we need a call to binmode?
      $stdin.binmode if $stdin.respond_to? :binmode
      data = $stdin.read(length)

      http_error(400, "Bad Request")        if data.nil? or data.size != length

      http_write(process(data), "Content-type" => "text/xml; charset=utf-8")
    }
  end


Class: XMLRPC::Client

Class | XMLRPC::Client
In: | xmlrpc/client.rb
Parent: | Object

Methods

call call2 call2_async call_async multicall multicall2 multicall2_async multicall_async new new2 new3 password= proxy proxy2 proxy2_async proxy_async timeout= user=

Included Modules

ParserWriterChooseMixin ParseContentType

Classes and Modules

Class XMLRPC::Client::Proxy

Constants

USER_AGENT = "XMLRPC::Client (Ruby #{RUBY_VERSION})"

External Aliases

new2 | -> | new_from_uri
new3 | -> | new_from_hash

Attributes

cookie | [RW] | Cookie support
http_header_extra | [RW] | add additional HTTP headers to the request
http_last_response | [R] | makes last HTTP response accessible
password | [R] |
timeout | [R] |
user | [R] |

Public Class methods

new(host=nil, path=nil, port=nil, proxy_host=nil, proxy_port=nil, user=nil, password=nil, use_ssl=nil, timeout=nil)

Constructors ——————————————————————-

[Source]

# File xmlrpc/client.rb, line 295
    def initialize(host=nil, path=nil, port=nil, proxy_host=nil, proxy_port=nil,
                   user=nil, password=nil, use_ssl=nil, timeout=nil)

      @http_header_extra = nil
      @http_last_response = nil
      @cookie = nil

      @host       = host || "localhost"
      @path       = path || "/RPC2"
      @proxy_host = proxy_host
      @proxy_port = proxy_port
      @proxy_host ||= 'localhost' if @proxy_port != nil
      @proxy_port ||= 8080 if @proxy_host != nil
      @use_ssl    = use_ssl || false
      @timeout    = timeout || 30

      if use_ssl
        require "net/https"
        @port = port || 443
      else
        @port = port || 80
      end

      @user, @password = user, password

      set_auth

      # convert ports to integers
      @port = @port.to_i if @port != nil
      @proxy_port = @proxy_port.to_i if @proxy_port != nil

      # HTTP object for synchronous calls
      Net::HTTP.version_1_2
      @http = Net::HTTP.new(@host, @port, @proxy_host, @proxy_port)
      @http.use_ssl = @use_ssl if @use_ssl
      @http.read_timeout = @timeout
      @http.open_timeout = @timeout

      @parser = nil
      @create = nil
    end
new2(uri, proxy=nil, timeout=nil)

[Source]

# File xmlrpc/client.rb, line 340
    def new2(uri, proxy=nil, timeout=nil)
      if match = /^([^:]+):\/\/(([^@]+)@)?([^\/]+)(\/.*)?$/.match(uri)
        proto = match[1]
        user, passwd = (match[3] || "").split(":")
        host, port = match[4].split(":")
        path = match[5]

        if proto != "http" and proto != "https"
          raise "Wrong protocol specified. Only http or https allowed!"
        end

      else
        raise "Wrong URI as parameter!"
      end

      proxy_host, proxy_port = (proxy || "").split(":")

      self.new(host, path, port, proxy_host, proxy_port, user, passwd, (proto == "https"), timeout)
    end
new3(hash={})

[Source]

# File xmlrpc/client.rb, line 362
    def new3(hash={})

      # convert all keys into lowercase strings
      h = {}
      hash.each { |k,v| h[k.to_s.downcase] = v }

      self.new(h['host'], h['path'], h['port'], h['proxy_host'], h['proxy_port'], h['user'], h['password'],
               h['use_ssl'], h['timeout'])
    end

Public Instance methods

call(method, *args)

Call methods —————————————————————

[Source]

# File xmlrpc/client.rb, line 409
    def call(method, *args)
      ok, param = call2(method, *args)
      if ok
        param
      else
        raise param
      end
    end
call2(method, *args)

[Source]

# File xmlrpc/client.rb, line 418
    def call2(method, *args)
      request = create().methodCall(method, *args)
      data = do_rpc(request, false)
      parser().parseMethodResponse(data)
    end
call2_async(method, *args)

[Source]

# File xmlrpc/client.rb, line 433
    def call2_async(method, *args)
      request = create().methodCall(method, *args)
      data = do_rpc(request, true)
      parser().parseMethodResponse(data)
    end
call_async(method, *args)

[Source]

# File xmlrpc/client.rb, line 424
    def call_async(method, *args)
      ok, param = call2_async(method, *args)
      if ok
        param
      else
        raise param
      end
    end
multicall(*methods)

Multicall methods —————————————————————

[Source]

# File xmlrpc/client.rb, line 442
    def multicall(*methods)
      ok, params = multicall2(*methods)
      if ok
        params
      else
        raise params
      end
    end
multicall2(*methods)

[Source]

# File xmlrpc/client.rb, line 451
    def multicall2(*methods)
      gen_multicall(methods, false)
    end
multicall2_async(*methods)

[Source]

# File xmlrpc/client.rb, line 464
    def multicall2_async(*methods)
      gen_multicall(methods, true)
    end
multicall_async(*methods)

[Source]

# File xmlrpc/client.rb, line 455
    def multicall_async(*methods)
      ok, params = multicall2_async(*methods)
      if ok
        params
      else
        raise params
      end
    end
password=(new_password)

[Source]

# File xmlrpc/client.rb, line 402
    def password=(new_password)
      @password = new_password
      set_auth
    end
proxy(prefix=nil, *args)

Proxy generating methods ——————————————

[Source]

# File xmlrpc/client.rb, line 471
    def proxy(prefix=nil, *args)
      Proxy.new(self, prefix, args, :call)
    end
proxy2(prefix=nil, *args)

[Source]

# File xmlrpc/client.rb, line 475
    def proxy2(prefix=nil, *args)
      Proxy.new(self, prefix, args, :call2)
    end
proxy2_async(prefix=nil, *args)

[Source]

# File xmlrpc/client.rb, line 483
    def proxy2_async(prefix=nil, *args)
      Proxy.new(self, prefix, args, :call2_async)
    end
proxy_async(prefix=nil, *args)

[Source]

# File xmlrpc/client.rb, line 479
    def proxy_async(prefix=nil, *args)
      Proxy.new(self, prefix, args, :call_async)
    end
timeout=(new_timeout)

[Source]

# File xmlrpc/client.rb, line 391
    def timeout=(new_timeout)
      @timeout = new_timeout
      @http.read_timeout = @timeout
      @http.open_timeout = @timeout
    end
user=(new_user)

[Source]

# File xmlrpc/client.rb, line 397
    def user=(new_user)
      @user = new_user
      set_auth
    end


Class: XMLRPC::Client::Proxy

Class | XMLRPC::Client::Proxy
In: | xmlrpc/client.rb
Parent: | Object

Methods

method_missing new

Public Class methods

new(server, prefix, args=[], meth=:call, delim=".")

[Source]

# File xmlrpc/client.rb, line 598
      def initialize(server, prefix, args=[], meth=:call, delim=".")
        @server = server
        @prefix = prefix ? prefix + delim : ""
        @args   = args
        @meth   = meth
      end

Public Instance methods

method_missing(mid, *args)

[Source]

# File xmlrpc/client.rb, line 605
      def method_missing(mid, *args)
        pre = @prefix + mid.to_s
        arg = @args + args
        @server.send(@meth, pre, *arg)
      end


Module: XMLRPC::Config

Module | XMLRPC::Config
In: | xmlrpc/config.rb

Constants

DEFAULT_WRITER = XMLWriter::Simple # or XMLWriter::XMLParser
DEFAULT_PARSER = XMLParser::REXMLStreamParser available parser:
  * XMLParser::NQXMLTreeParser
  * XMLParser::NQXMLStreamParser
  * XMLParser::XMLTreeParser
  * XMLParser::XMLStreamParser (fastest)
  * XMLParser::REXMLStreamParser
  * XMLParser::XMLScanStreamParser
ENABLE_NIL_CREATE = false enable <nil/> tag
ENABLE_NIL_PARSER = false
ENABLE_BIGINT = false allows integers greater than 32-bit if true
ENABLE_MARSHALLING = true enable marshalling ruby objects which include XMLRPC::Marshallable
ENABLE_MULTICALL = false enable multiCall extension by default
ENABLE_INTROSPECTION = false enable Introspection extension by default


Module: XMLRPC::Convert

Module | XMLRPC::Convert
In: | xmlrpc/parser.rb

Methods

base64 boolean dateTime double fault int struct

Public Class methods

base64(str)

[Source]

# File xmlrpc/parser.rb, line 118
    def self.base64(str)
      XMLRPC::Base64.decode(str)
    end
boolean(str)

[Source]

# File xmlrpc/parser.rb, line 75
    def self.boolean(str)
      case str
      when "0" then false
      when "1" then true
      else
        raise "RPC-value of type boolean is wrong"
      end
    end
dateTime(str)

[Source]

# File xmlrpc/parser.rb, line 88
    def self.dateTime(str)
      case str
      when /^(-?\d\d\d\d)-?(\d\d)-?(\d\d)T(\d\d):(\d\d):(\d\d)(?:Z|([+-])(\d\d):?(\d\d))?$/
        a = [$1, $2, $3, $4, $5, $6].collect{|i| i.to_i}
        if $7
          ofs = $8.to_i*3600 + $9.to_i*60
          ofs = -ofs if $7=='+'
          utc = Time.utc(a.reverse) + ofs
          a = [ utc.year, utc.month, utc.day, utc.hour, utc.min, utc.sec ]
        end
        XMLRPC::DateTime.new(*a)
      when /^(-?\d\d)-?(\d\d)-?(\d\d)T(\d\d):(\d\d):(\d\d)(Z|([+-]\d\d):(\d\d))?$/
        a = [$1, $2, $3, $4, $5, $6].collect{|i| i.to_i}
        if a[0] < 70
          a[0] += 2000
        else
          a[0] += 1900
        end
        if $7
          ofs = $8.to_i*3600 + $9.to_i*60
          ofs = -ofs if $7=='+'
          utc = Time.utc(a.reverse) + ofs
          a = [ utc.year, utc.month, utc.day, utc.hour, utc.min, utc.sec ]
        end
        XMLRPC::DateTime.new(*a)
      else
        raise "wrong dateTime.iso8601 format " + str
      end
    end
double(str)

[Source]

# File xmlrpc/parser.rb, line 84
    def self.double(str)
      str.to_f
    end
fault(hash)

[Source]

# File xmlrpc/parser.rb, line 145
    def self.fault(hash)
      if hash.kind_of? Hash and hash.size == 2 and
        hash.has_key? "faultCode" and hash.has_key? "faultString" and
        hash["faultCode"].kind_of? Integer and hash["faultString"].kind_of? String

        XMLRPC::FaultException.new(hash["faultCode"], hash["faultString"])
      else
        raise "wrong fault-structure: #{hash.inspect}"
      end
    end
int(str)

[Source]

# File xmlrpc/parser.rb, line 71
    def self.int(str)
      str.to_i
    end
struct(hash)

[Source]

# File xmlrpc/parser.rb, line 122
    def self.struct(hash)
      # convert to marhalled object
      klass = hash["___class___"]
      if klass.nil? or Config::ENABLE_MARSHALLING == false
        hash
      else
        begin
          mod = Module
          klass.split("::").each {|const| mod = mod.const_get(const.strip)}

          obj = mod.allocate

          hash.delete "___class___"
          hash.each {|key, value|
            obj.instance_variable_set("@#{ key }", value) if key =~ /^([\w_][\w_0-9]*)$/
          }
          obj
        rescue
          hash
        end
      end
    end


Class: XMLRPC::Create

Class | XMLRPC::Create
In: | xmlrpc/create.rb
Parent: | Object

Methods

methodCall methodResponse new

Public Class methods

new(xml_writer = nil)

[Source]

# File xmlrpc/create.rb, line 105
    def initialize(xml_writer = nil)
      @writer = xml_writer || Config::DEFAULT_WRITER.new
    end

Public Instance methods

methodCall(name, *params)

[Source]

# File xmlrpc/create.rb, line 110
    def methodCall(name, *params)
      name = name.to_s

      if name !~ /[a-zA-Z0-9_.:\/]+/
        raise ArgumentError, "Wrong XML-RPC method-name"
      end

      parameter = params.collect do |param|
        @writer.ele("param", conv2value(param))
      end

      tree = @writer.document(
               @writer.pi("xml", 'version="1.0"'),
               @writer.ele("methodCall",
                 @writer.tag("methodName", name),
                 @writer.ele("params", *parameter)
               )
             )

      @writer.document_to_str(tree) + "\n"
    end
methodResponse(is_ret, *params)

generates a XML-RPC methodResponse document

if is_ret == false then the params array must contain only one element, which is a structure of a fault return-value.

if is_ret == true then a normal return-value of all the given params is created.

[Source]

# File xmlrpc/create.rb, line 144
    def methodResponse(is_ret, *params)

      if is_ret
        resp = params.collect do |param|
          @writer.ele("param", conv2value(param))
        end

        resp = [@writer.ele("params", *resp)]
      else
        if params.size != 1 or params[0] === XMLRPC::FaultException
          raise ArgumentError, "no valid fault-structure given"
        end
        resp = @writer.ele("fault", conv2value(params[0].to_h))
      end

      tree = @writer.document(
               @writer.pi("xml", 'version="1.0"'),
               @writer.ele("methodResponse", resp)
             )

      @writer.document_to_str(tree) + "\n"
    end


Class: XMLRPC::DateTime

Class | XMLRPC::DateTime
In: | xmlrpc/datetime.rb
Parent: | Object

Methods

== day= hour= min= mon= month= new sec= to_a to_date to_time year=

External Aliases

month -> mon

Attributes

day | [R]
hour | [R]
min | [R]
month | [R]
sec | [R]
year | [R]

Public Class methods

new(year, month, day, hour, min, sec)

[Source]

# File xmlrpc/datetime.rb, line 108
  def initialize(year, month, day, hour, min, sec)
    self.year, self.month, self.day = year, month, day
    self.hour, self.min, self.sec   = hour, min, sec
  end

Public Instance methods

==(o)

[Source]

# File xmlrpc/datetime.rb, line 129
  def ==(o)
    Array(self) == Array(o)
  end
day=(value)

[Source]

# File xmlrpc/datetime.rb, line 84
  def day= (value)
    raise ArgumentError, "date/time out of range" unless (1..31).include? value
    @day = value
  end
hour=(value)

[Source]

# File xmlrpc/datetime.rb, line 89
  def hour= (value)
    raise ArgumentError, "date/time out of range" unless (0..24).include? value
    @hour = value
  end
min=(value)

[Source]

# File xmlrpc/datetime.rb, line 94
  def min= (value)
    raise ArgumentError, "date/time out of range" unless (0..59).include? value
    @min = value
  end
mon=(value)

Alias for month=

month=(value)

[Source]

# File xmlrpc/datetime.rb, line 79
  def month= (value)
    raise ArgumentError, "date/time out of range" unless (1..12).include? value
    @month = value
  end
sec=(value)

[Source]

# File xmlrpc/datetime.rb, line 99
  def sec= (value)
    raise ArgumentError, "date/time out of range" unless (0..59).include? value
    @sec = value
  end
to_a()

[Source]

# File xmlrpc/datetime.rb, line 125
  def to_a
    [@year, @month, @day, @hour, @min, @sec]
  end
to_date()

[Source]

# File xmlrpc/datetime.rb, line 121
  def to_date
    Date.new(*to_a[0,3])
  end
to_time()

[Source]

# File xmlrpc/datetime.rb, line 113
  def to_time
    if @year >= 1970
      Time.gm(*to_a)
    else
      nil
    end
  end
year=(value)

[Source]

# File xmlrpc/datetime.rb, line 74
  def year= (value)
    raise ArgumentError, "date/time out of range" unless value.is_a? Integer
    @year = value
  end


Class: XMLRPC::FaultException

Class | XMLRPC::FaultException
In: | xmlrpc/parser.rb
Parent: | StandardError

Methods

new to_h

External Aliases

faultString -> message

Attributes

faultCode | [R]
faultString | [R]

Public Class methods

new(faultCode, faultString)

[Source]

# File xmlrpc/parser.rb, line 59
    def initialize(faultCode, faultString)
      @faultCode   = faultCode
      @faultString = faultString
    end

Public Instance methods

to_h()

returns a hash

[Source]

# File xmlrpc/parser.rb, line 65
    def to_h
      {"faultCode" => @faultCode, "faultString" => @faultString}
    end


Class: XMLRPC::Marshal

Class | XMLRPC::Marshal
In: | xmlrpc/marshal.rb
Parent: | Object

Methods

dump_call dump_call dump_response dump_response load_call load_call load_response load_response new

Included Modules

ParserWriterChooseMixin

External Aliases

dump_response | -> | dump
load_response | -> | load

Public Class methods

dump_call( methodName, *params )

[Source]

# File xmlrpc/marshal.rb, line 23
      def dump_call( methodName, *params )
        new.dump_call( methodName, *params )
      end
dump_response( param )

[Source]

# File xmlrpc/marshal.rb, line 27
      def dump_response( param )
        new.dump_response( param )
      end
load_call( stringOrReadable )

[Source]

# File xmlrpc/marshal.rb, line 31
      def load_call( stringOrReadable )
        new.load_call( stringOrReadable )
      end
load_response( stringOrReadable )

[Source]

# File xmlrpc/marshal.rb, line 35
      def load_response( stringOrReadable )
        new.load_response( stringOrReadable )
      end
new( parser = nil, writer = nil )

instance methods —————————-

[Source]

# File xmlrpc/marshal.rb, line 46
    def initialize( parser = nil, writer = nil )
      set_parser( parser )
      set_writer( writer )
    end

Public Instance methods

dump_call( methodName, *params )

[Source]

# File xmlrpc/marshal.rb, line 51
    def dump_call( methodName, *params )
      create.methodCall( methodName, *params )
    end
dump_response( param )

[Source]

# File xmlrpc/marshal.rb, line 55
    def dump_response( param )
      create.methodResponse( ! param.kind_of?( XMLRPC::FaultException ) , param )
    end
load_call( stringOrReadable )

returns [ methodname, params ]

[Source]

# File xmlrpc/marshal.rb, line 62
    def load_call( stringOrReadable )
      parser.parseMethodCall( stringOrReadable )
    end
load_response( stringOrReadable )

returns paramOrFault

[Source]

# File xmlrpc/marshal.rb, line 69
    def load_response( stringOrReadable )
      parser.parseMethodResponse( stringOrReadable )[1]
    end


Module: XMLRPC::Marshallable

Module | XMLRPC::Marshallable
In: | xmlrpc/utils.rb

This module enables a user-class to be marshalled by XML-RPC for Ruby into a Hash, with one additional key/value pair "class" => ClassName


Class: XMLRPC::ModRubyServer

Class | XMLRPC::ModRubyServer
In: | xmlrpc/server.rb
Parent: | BasicServer

Methods

new serve

Public Class methods

new(*a)

[Source]

# File xmlrpc/server.rb, line 513
  def initialize(*a)
    @ap = Apache::request
    super(*a)
  end

Public Instance methods

serve()

[Source]

# File xmlrpc/server.rb, line 518
  def serve
    catch(:exit_serve) {
      header = {}
      @ap.headers_in.each {|key, value| header[key.capitalize] = value}

      length = header['Content-length'].to_i

      http_error(405, "Method Not Allowed") unless @ap.request_method  == "POST"
      http_error(400, "Bad Request")        unless parse_content_type(header['Content-type']).first == "text/xml"
      http_error(411, "Length Required")    unless length > 0

      # TODO: do we need a call to binmode?
      @ap.binmode
      data = @ap.read(length)

      http_error(400, "Bad Request")        if data.nil? or data.size != length

      http_write(process(data), 200, "Content-type" => "text/xml; charset=utf-8")
    }
  end


Module: XMLRPC::ParseContentType

Module | XMLRPC::ParseContentType
In: | xmlrpc/utils.rb

Methods

parse_content_type

Public Instance methods

parse_content_type(str)

[Source]

# File xmlrpc/utils.rb, line 158
    def parse_content_type(str)
      a, *b = str.split(";")
      return a.strip, *b
    end


Module: XMLRPC::ParserWriterChooseMixin

Module | XMLRPC::ParserWriterChooseMixin
In: | xmlrpc/utils.rb

Methods

set_parser set_writer

Public Instance methods

set_parser(parser)

[Source]

# File xmlrpc/utils.rb, line 30
    def set_parser(parser)
      @parser = parser
      self
    end
set_writer(writer)

[Source]

# File xmlrpc/utils.rb, line 25
    def set_writer(writer)
      @create = Create.new(writer)
      self
    end


Class: XMLRPC::Server

Class | XMLRPC::Server
In: | xmlrpc/server.rb
Parent: | WEBrickServlet

Methods

new serve shutdown

Public Class methods

new(port=8080, host="127.0.0.1", maxConnections=4, stdlog=$stdout, audit=true, debug=true, *a)

[Source]

# File xmlrpc/server.rb, line 634
  def initialize(port=8080, host="127.0.0.1", maxConnections=4, stdlog=$stdout, audit=true, debug=true, *a)
    super(*a)
    require 'webrick'
    @server = WEBrick::HTTPServer.new(:Port => port, :BindAddress => host, :MaxClients => maxConnections,
                                      :Logger => WEBrick::Log.new(stdlog))
    @server.mount("/", self)
  end

Public Instance methods

serve()

[Source]

# File xmlrpc/server.rb, line 642
  def serve
    if RUBY_PLATFORM =~ /mingw|mswin32/
      signal = 1
    else
      signal = "HUP"
    end
    trap(signal) { @server.shutdown }

    @server.start
  end
shutdown()

[Source]

# File xmlrpc/server.rb, line 653
  def shutdown
    @server.shutdown
  end


Module: XMLRPC::Service

Module | XMLRPC::Service
In: | xmlrpc/utils.rb

Classes and Modules

Class XMLRPC::Service::BasicInterface
Class XMLRPC::Service::Interface
Class XMLRPC::Service::PublicInstanceMethodsInterface


Class: XMLRPC::Service::BasicInterface

Class | XMLRPC::Service::BasicInterface
In: | xmlrpc/utils.rb
Parent: | Object

base class for Service Interface definitions, used by BasicServer#add_handler

Methods

add_method new

Attributes

methods | [R]
prefix | [R]

Public Class methods

new(prefix)

[Source]

# File xmlrpc/utils.rb, line 66
    def initialize(prefix)
      @prefix = prefix
      @methods = []
    end

Public Instance methods

add_method(sig, help=nil, meth_name=nil)

[Source]

# File xmlrpc/utils.rb, line 71
    def add_method(sig, help=nil, meth_name=nil)
      mname = nil
      sig = [sig] if sig.kind_of? String

      sig = sig.collect do |s|
        name, si = parse_sig(s)
        raise "Wrong signatures!" if mname != nil and name != mname
        mname = name
        si
      end

      @methods << [mname, meth_name || mname, sig, help]
    end


Class: XMLRPC::Service::Interface

Class | XMLRPC::Service::Interface
In: | xmlrpc/utils.rb
Parent: | BasicInterface

class which wraps a Service Interface definition, used by BasicServer#add_handler

Methods

get_methods new

Public Class methods

new(prefix, &p)

[Source]

# File xmlrpc/utils.rb, line 106
    def initialize(prefix, &p)
      raise "No interface specified" if p.nil?
      super(prefix)
      instance_eval(&p)
    end

Public Instance methods

get_methods(obj, delim=".")

[Source]

# File xmlrpc/utils.rb, line 112
    def get_methods(obj, delim=".")
      prefix = @prefix + delim
      @methods.collect { |name, meth, sig, help|
        [prefix + name, obj.method(meth).to_proc, sig, help]
      }
    end


Class: XMLRPC::Service::PublicInstanceMethodsInterface

Class | XMLRPC::Service::PublicInstanceMethodsInterface
In: | xmlrpc/utils.rb
Parent: | BasicInterface

Methods

get_methods new

Public Class methods

new(prefix)

[Source]

# File xmlrpc/utils.rb, line 128
    def initialize(prefix)
      super(prefix)
    end

Public Instance methods

get_methods(obj, delim=".")

[Source]

# File xmlrpc/utils.rb, line 132
    def get_methods(obj, delim=".")
      prefix = @prefix + delim
      obj.class.public_instance_methods(false).collect { |name|
        [prefix + name, obj.method(name).to_proc, nil, nil]
      }
    end


Class: XMLRPC::WEBrickServlet

Class | XMLRPC::WEBrickServlet
In: | xmlrpc/server.rb
Parent: | BasicServer

Methods

get_instance get_valid_ip new require_path_info? service set_valid_ip

Public Class methods

new(*a)

[Source]

# File xmlrpc/server.rb, line 708
  def initialize(*a)
    super
    require "webrick/httpstatus"
    @valid_ip = nil
  end

Public Instance methods

get_instance(config, *options)

[Source]

# File xmlrpc/server.rb, line 720
  def get_instance(config, *options)
    # TODO: set config & options
    self
  end
get_valid_ip()

[Source]

# File xmlrpc/server.rb, line 733
  def get_valid_ip
    @valid_ip
  end
require_path_info?()

deprecated from WEBrick/1.2.2. but does not break anything.

[Source]

# File xmlrpc/server.rb, line 716
  def require_path_info?
    false
  end
service(request, response)

[Source]

# File xmlrpc/server.rb, line 737
  def service(request, response)

    if @valid_ip
      raise WEBrick::HTTPStatus::Forbidden unless @valid_ip.any? { |ip| request.peeraddr[3] =~ ip }
    end

    if request.request_method != "POST"
      raise WEBrick::HTTPStatus::MethodNotAllowed,
            "unsupported method `#{request.request_method}'."
    end

    if parse_content_type(request['Content-type']).first != "text/xml"
      raise WEBrick::HTTPStatus::BadRequest
    end

    length = (request['Content-length'] || 0).to_i

    raise WEBrick::HTTPStatus::LengthRequired unless length > 0

    data = request.body

    if data.nil? or data.size != length
      raise WEBrick::HTTPStatus::BadRequest
    end

    resp = process(data)
    if resp.nil? or resp.size <= 0
      raise WEBrick::HTTPStatus::InternalServerError
    end

    response.status = 200
    response['Content-Length'] = resp.size
    response['Content-Type']   = "text/xml; charset=utf-8"
    response.body = resp
  end
set_valid_ip(*ip_addr)

[Source]

# File xmlrpc/server.rb, line 725
  def set_valid_ip(*ip_addr)
    if ip_addr.size == 1 and ip_addr[0].nil?
      @valid_ip = nil
    else
      @valid_ip = ip_addr
    end
  end


Module: XMLRPC::XMLParser

Module | XMLRPC::XMLParser
In: | xmlrpc/parser.rb

Methods

each_installed_parser

Classes and Modules

Module XMLRPC::XMLParser::StreamParserMixin
Class XMLRPC::XMLParser::AbstractStreamParser
Class XMLRPC::XMLParser::AbstractTreeParser
Class XMLRPC::XMLParser::NQXMLStreamParser
Class XMLRPC::XMLParser::NQXMLTreeParser
Class XMLRPC::XMLParser::REXMLStreamParser
Class XMLRPC::XMLParser::XMLScanStreamParser
Class XMLRPC::XMLParser::XMLStreamParser
Class XMLRPC::XMLParser::XMLTreeParser

Constants

XMLParser | = | XMLTreeParser
NQXMLParser | = | NQXMLTreeParser
Classes | = | [XMLStreamParser, XMLTreeParser, NQXMLStreamParser, NQXMLTreeParser, REXMLStreamParser, XMLScanStreamParser]

Public Class methods

each_installed_parser() {|klass.new| ...}

yields an instance of each installed parser

[Source]

# File xmlrpc/parser.rb, line 800
    def self.each_installed_parser
      XMLRPC::XMLParser::Classes.each do |klass|
        begin
          yield klass.new
        rescue LoadError
        end
      end
    end


Class: XMLRPC::XMLParser::AbstractStreamParser

Class | XMLRPC::XMLParser::AbstractStreamParser
In: | xmlrpc/parser.rb
Parent: | Object

Methods

parseMethodCall parseMethodResponse

Public Instance methods

parseMethodCall(str)

[Source]

# File xmlrpc/parser.rb, line 473
      def parseMethodCall(str)
        parser = @parser_class.new
        parser.parse(str)
        raise "No valid method call - missing method name!" if parser.method_name.nil?
        [parser.method_name, parser.params]
      end
parseMethodResponse(str)

[Source]

# File xmlrpc/parser.rb, line 458
      def parseMethodResponse(str)
        parser = @parser_class.new
        parser.parse(str)
        raise "No valid method response!" if parser.method_name != nil
        if parser.fault != nil
          # is a fault structure
          [false, parser.fault]
        else
          # is a normal return value
          raise "Missing return value!" if parser.params.size == 0
          raise "Too many return values. Only one allowed!" if parser.params.size > 1
          [true, parser.params[0]]
        end
      end


Class: XMLRPC::XMLParser::AbstractTreeParser

Class | XMLRPC::XMLParser::AbstractTreeParser
In: | xmlrpc/parser.rb
Parent: | Object

Methods

parseMethodCall parseMethodResponse

Public Instance methods

parseMethodCall(str)

[Source]

# File xmlrpc/parser.rb, line 166
      def parseMethodCall(str)
        methodCall_document(createCleanedTree(str))
      end
parseMethodResponse(str)

[Source]

# File xmlrpc/parser.rb, line 162
      def parseMethodResponse(str)
        methodResponse_document(createCleanedTree(str))
      end


Class: XMLRPC::XMLParser::NQXMLStreamParser

Class | XMLRPC::XMLParser::NQXMLStreamParser
In: | xmlrpc/parser.rb
Parent: | AbstractStreamParser

Methods

new

Classes and Modules

Class XMLRPC::XMLParser::NQXMLStreamParser::XMLRPCParser

Public Class methods

new()

[Source]

# File xmlrpc/parser.rb, line 590
      def initialize
        require "nqxml/streamingparser"
        @parser_class = XMLRPCParser
      end


Class: XMLRPC::XMLParser::NQXMLStreamParser::XMLRPCParser

Class | XMLRPC::XMLParser::NQXMLStreamParser::XMLRPCParser
In: | xmlrpc/parser.rb
Parent: | Object

Methods

parse

Included Modules

StreamParserMixin

Public Instance methods

parse(str)

[Source]

# File xmlrpc/parser.rb, line 598
        def parse(str)
          parser = NQXML::StreamingParser.new(str)
          parser.each do |ele|
            case ele
            when NQXML::Text
              @data = ele.text
              #character(ele.text)
            when NQXML::Tag
              if ele.isTagEnd
                endElement(ele.name)
              else
                startElement(ele.name, ele.attrs)
              end
            end
          end # do
        end


Class: XMLRPC::XMLParser::NQXMLTreeParser

Class | XMLRPC::XMLParser::NQXMLTreeParser
In: | xmlrpc/parser.rb
Parent: | AbstractTreeParser

Methods

new

Public Class methods

new()

[Source]

# File xmlrpc/parser.rb, line 672
      def initialize
        require "nqxml/treeparser"
      end


Class: XMLRPC::XMLParser::REXMLStreamParser

Class | XMLRPC::XMLParser::REXMLStreamParser
In: | xmlrpc/parser.rb
Parent: | AbstractStreamParser

Methods

new

Classes and Modules

Class XMLRPC::XMLParser::REXMLStreamParser::StreamListener

Public Class methods

new()

[Source]

# File xmlrpc/parser.rb, line 699
      def initialize
        require "rexml/document"
        @parser_class = StreamListener
      end


Class: XMLRPC::XMLParser::REXMLStreamParser::StreamListener

Class | XMLRPC::XMLParser::REXMLStreamParser::StreamListener
In: | xmlrpc/parser.rb
Parent: | Object

Methods

method_missing parse

Included Modules

StreamParserMixin

External Aliases

startElement | -> | tag_start
endElement | -> | tag_end
character | -> | text
character | -> | cdata

Public Instance methods

method_missing(*a)

[Source]

# File xmlrpc/parser.rb, line 712
        def method_missing(*a)
          # ignore
        end
parse(str)

[Source]

# File xmlrpc/parser.rb, line 716
        def parse(str)
          parser = REXML::Document.parse_stream(str, self)
       end


Module: XMLRPC::XMLParser::StreamParserMixin

Module | XMLRPC::XMLParser::StreamParserMixin
In: | xmlrpc/parser.rb

Methods

character endElement new startElement

Attributes

fault | [R]
method_name | [R]
params | [R]

Public Class methods

new(*a)

[Source]

# File xmlrpc/parser.rb, line 486
      def initialize(*a)
        super(*a)
        @params = []
        @values = []
        @val_stack = []

        @names = []
        @name = []

        @structs = []
        @struct = {}

        @method_name = nil
        @fault = nil

        @data = nil
      end

Public Instance methods

character(data)

[Source]

# File xmlrpc/parser.rb, line 569
      def character(data)
        if @data
          @data << data
        else
          @data = data
        end
      end
endElement(name)

[Source]

# File xmlrpc/parser.rb, line 524
      def endElement(name)
        @data ||= ""
        case name
        when "string"
          @value = @data
        when "i4", "int"
          @value = Convert.int(@data)
        when "boolean"
          @value = Convert.boolean(@data)
        when "double"
          @value = Convert.double(@data)
        when "dateTime.iso8601"
          @value = Convert.dateTime(@data)
        when "base64"
          @value = Convert.base64(@data)
        when "value"
          @value = @data if @value.nil?
          @values << (@value == :nil ? nil : @value)
        when "array"
          @value = @values
          @values = @val_stack.pop
        when "struct"
          @value = Convert.struct(@struct)

          @name = @names.pop
          @struct = @structs.pop
        when "name"
          @name[0] = @data
        when "member"
          @struct[@name[0]] = @values.pop

        when "param"
          @params << @values[0]
          @values = []

        when "fault"
          @fault = Convert.fault(@values[0])

        when "methodName"
          @method_name = @data
        end

        @data = nil
      end
startElement(name, attrs=[])

[Source]

# File xmlrpc/parser.rb, line 504
      def startElement(name, attrs=[])
        @data = nil
        case name
        when "value"
          @value = nil
        when "nil"
          raise "wrong/unknown XML-RPC type 'nil'" unless Config::ENABLE_NIL_PARSER
          @value = :nil
        when "array"
          @val_stack << @values
          @values = []
        when "struct"
          @names << @name
          @name = []

          @structs << @struct
          @struct = {}
        end
      end


Class: XMLRPC::XMLParser::XMLScanStreamParser

Class | XMLRPC::XMLParser::XMLScanStreamParser
In: | xmlrpc/parser.rb
Parent: | AbstractStreamParser

Methods

new

Classes and Modules

Class XMLRPC::XMLParser::XMLScanStreamParser::XMLScanParser

Public Class methods

new()

[Source]

# File xmlrpc/parser.rb, line 724
      def initialize
        require "xmlscan/parser"
        @parser_class = XMLScanParser
      end


Class: XMLRPC::XMLParser::XMLScanStreamParser::XMLScanParser

Class | XMLRPC::XMLParser::XMLScanStreamParser::XMLScanParser
In: | xmlrpc/parser.rb
Parent: | Object

Methods

method_missing on_cdata on_chardata on_charref on_charref_hex on_entityref on_stag_end on_stag_end_empty parse

Included Modules

StreamParserMixin

Constants

Entities = { "lt" => "<", "gt" => ">", "amp" => "&", "quot" => '"', "apos" => "'"

External Aliases

startElement | -> | on_stag
endElement | -> | on_etag

Public Instance methods

method_missing(*a)

[Source]

# File xmlrpc/parser.rb, line 780
        def method_missing(*a)
        end
on_cdata(str)

[Source]

# File xmlrpc/parser.rb, line 759
        def on_cdata(str)
          character(str)
        end
on_chardata(str)

[Source]

# File xmlrpc/parser.rb, line 755
        def on_chardata(str)
          character(str)
        end
on_charref(code)

[Source]

# File xmlrpc/parser.rb, line 772
        def on_charref(code)
          character(code.chr)
        end
on_charref_hex(code)

[Source]

# File xmlrpc/parser.rb, line 776
        def on_charref_hex(code)
          character(code.chr)
        end
on_entityref(ent)

[Source]

# File xmlrpc/parser.rb, line 763
        def on_entityref(ent)
          str = Entities[ent]
          if str
            character(str)
          else
            raise "unknown entity"
          end
        end
on_stag_end(name)

[Source]

# File xmlrpc/parser.rb, line 748
        def on_stag_end(name); end
on_stag_end_empty(name)

[Source]

# File xmlrpc/parser.rb, line 750
        def on_stag_end_empty(name)
          startElement(name)
          endElement(name)
        end
parse(str)

[Source]

# File xmlrpc/parser.rb, line 740
        def parse(str)
          parser  = XMLScan::XMLParser.new(self)
          parser.parse(str)
        end


Class: XMLRPC::XMLParser::XMLStreamParser

Class | XMLRPC::XMLParser::XMLStreamParser
In: | xmlrpc/parser.rb
Parent: | AbstractStreamParser

Methods

new

Included Modules

StreamParserMixin

Public Class methods

new()

[Source]

# File xmlrpc/parser.rb, line 581
      def initialize
        require "xmlparser"
        @parser_class = Class.new(::XMLParser) {
          include StreamParserMixin
        }
      end


Class: XMLRPC::XMLParser::XMLTreeParser

Class | XMLRPC::XMLParser::XMLTreeParser
In: | xmlrpc/parser.rb
Parent: | AbstractTreeParser

Methods

new

Public Class methods

new()

[Source]

# File xmlrpc/parser.rb, line 620
      def initialize
        require "xmltreebuilder"

        # The new XMLParser library (0.6.2+) uses a slightly different DOM implementation.
        # The following code removes the differences between both versions.
        if defined? XML::DOM::Builder
          return if defined? XML::DOM::Node::DOCUMENT # code below has been already executed
          klass = XML::DOM::Node
          klass.const_set("DOCUMENT", klass::DOCUMENT_NODE)
          klass.const_set("TEXT", klass::TEXT_NODE)
          klass.const_set("COMMENT", klass::COMMENT_NODE)
          klass.const_set("ELEMENT", klass::ELEMENT_NODE)
        end
      end


Module: XMLRPC::XMLWriter

Module | XMLRPC::XMLWriter
In: | xmlrpc/create.rb

Methods

each_installed_writer

Classes and Modules

Class XMLRPC::XMLWriter::Abstract
Class XMLRPC::XMLWriter::Simple
Class XMLRPC::XMLWriter::XMLParser

Constants

Classes = [Simple, XMLParser]

Public Class methods

each_installed_writer() {|klass.new| ...}

yields an instance of each installed XML writer

[Source]

# File xmlrpc/create.rb, line 92
    def self.each_installed_writer
      XMLRPC::XMLWriter::Classes.each do |klass|
        begin
          yield klass.new
        rescue LoadError
        end
      end
    end


Class: XMLRPC::XMLWriter::Abstract

Class | XMLRPC::XMLWriter::Abstract
In: | xmlrpc/create.rb
Parent: | Object

Methods

ele tag

Public Instance methods

ele(name, *children)

[Source]

# File xmlrpc/create.rb, line 17
      def ele(name, *children)
        element(name, nil, *children)
      end
tag(name, txt)

[Source]

# File xmlrpc/create.rb, line 21
      def tag(name, txt)
        element(name, nil, text(txt))
      end


Class: XMLRPC::XMLWriter::Simple

Class | XMLRPC::XMLWriter::Simple
In: | xmlrpc/create.rb
Parent: | Abstract

Methods

document document_to_str element pi text

Public Instance methods

document(*params)

[Source]

# File xmlrpc/create.rb, line 33
      def document(*params)
        params.join("")
      end
document_to_str(doc)

[Source]

# File xmlrpc/create.rb, line 29
      def document_to_str(doc)
        doc
      end
element(name, attrs, *children)

[Source]

# File xmlrpc/create.rb, line 41
      def element(name, attrs, *children)
        raise "attributes not yet implemented" unless attrs.nil?
        if children.empty?
          "<#{name}/>"
        else
          "<#{name}>" + children.join("") + "</#{name}>"
        end
      end
pi(name, *params)

[Source]

# File xmlrpc/create.rb, line 37
      def pi(name, *params)
        "<?#{name} " + params.join(" ") + " ?>"
      end
text(txt)

[Source]

# File xmlrpc/create.rb, line 50
      def text(txt)
        cleaned = txt.dup
        cleaned.gsub!(/&/, '&amp;')
        cleaned.gsub!(/</, '&lt;')
        cleaned.gsub!(/>/, '&gt;')
        cleaned
      end


Class: XMLRPC::XMLWriter::XMLParser

Class | XMLRPC::XMLWriter::XMLParser
In: | xmlrpc/create.rb
Parent: | Abstract

Methods

document document_to_str element new pi text

Public Class methods

new()

[Source]

# File xmlrpc/create.rb, line 63
      def initialize
        require "xmltreebuilder"
      end

Public Instance methods

document(*params)

[Source]

# File xmlrpc/create.rb, line 71
      def document(*params)
        XML::SimpleTree::Document.new(*params)
      end
document_to_str(doc)

[Source]

# File xmlrpc/create.rb, line 67
      def document_to_str(doc)
        doc.to_s
      end
element(name, attrs, *children)

[Source]

# File xmlrpc/create.rb, line 79
      def element(name, attrs, *children)
        XML::SimpleTree::Element.new(name, attrs, *children)
      end
pi(name, *params)

[Source]

# File xmlrpc/create.rb, line 75
      def pi(name, *params)
        XML::SimpleTree::ProcessingInstruction.new(name, *params)
      end
text(txt)

[Source]

# File xmlrpc/create.rb, line 83
      def text(txt)
        XML::SimpleTree::Text.new(txt)
      end


File: base64.rb

base64.rb

Path: | xmlrpc/base64.rb
Last Update: | Sat Jul 19 20:05:54 AUS Eastern Standard Time 2003


File: client.rb

client.rb

Path: | xmlrpc/client.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

Required files

xmlrpc/parser xmlrpc/create xmlrpc/config xmlrpc/utils net/http net/https


File: config.rb

config.rb

Path: | xmlrpc/config.rb
Last Update: | Sat Jul 19 20:05:54 AUS Eastern Standard Time 2003

$Id: config.rb,v 1.1 2003/07/19 10:05:54 matz Exp $ Configuration file for XML-RPC for Ruby


File: create.rb

create.rb

Path: | xmlrpc/create.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

Creates XML-RPC call/response documents

Copyright (C) 2001, 2002, 2003 by Michael Neumann (mneumann@ntecs.de)

$Id: create.rb,v 1.1.2.1 2005/06/24 20:27:42 mneumann Exp $

Required files

date xmlrpc/base64 xmltreebuilder


File: datetime.rb

datetime.rb

Path: | xmlrpc/datetime.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

Required files

date


File: httpserver.rb

httpserver.rb

Path: | xmlrpc/httpserver.rb
Last Update: | Sat Jul 19 20:05:54 AUS Eastern Standard Time 2003

Implements a simple HTTP-server by using John W. Small’s (jsmall@laser.net) ruby-generic-server.

Copyright (C) 2001, 2002, 2003 by Michael Neumann (mneumann@ntecs.de)

$Id: httpserver.rb,v 1.1 2003/07/19 10:05:54 matz Exp $

Required files

gserver


File: marshal.rb

marshal.rb

Path: | xmlrpc/marshal.rb
Last Update: | Sat Jul 19 20:05:54 AUS Eastern Standard Time 2003

Marshalling of XML-RPC methodCall and methodResponse

Copyright (C) 2001, 2002, 2003 by Michael Neumann (mneumann@ntecs.de)

$Id: marshal.rb,v 1.1 2003/07/19 10:05:54 matz Exp $

Required files

xmlrpc/parser xmlrpc/create xmlrpc/config xmlrpc/utils


File: parser.rb

parser.rb

Path: | xmlrpc/parser.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

Parser for XML-RPC call and response

Copyright (C) 2001, 2002, 2003 by Michael Neumann (mneumann@ntecs.de)

$Id: parser.rb,v 1.3.2.3 2005/06/24 20:27:42 mneumann Exp $

Required files

date xmlrpc/base64 xmlrpc/datetime xmlparser nqxml/streamingparser xmltreebuilder nqxml/treeparser rexml/document xmlscan/parser


File: server.rb

server.rb

Path: | xmlrpc/server.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

Required files

xmlrpc/parser xmlrpc/create xmlrpc/config xmlrpc/utils webrick webrick/httpstatus


File: utils.rb

utils.rb

Path: | xmlrpc/utils.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

Defines ParserWriterChooseMixin, which makes it possible to choose a different XML writer and/or XML parser then the default one. The Mixin is used in client.rb (class Client) and server.rb (class BasicServer)

Copyright (C) 2001, 2002, 2003 by Michael Neumann (mneumann@ntecs.de)

$Id: utils.rb,v 1.2.2.1 2005/06/24 20:27:42 mneumann Exp $


Module: XSD

Module | XSD
In: | xsd/xmlparser.rb xsd/xmlparser/xmlscanner.rb xsd/xmlparser/xmlparser.rb xsd/xmlparser/rexmlparser.rb xsd/xmlparser/parser.rb xsd/qname.rb xsd/ns.rb xsd/namedelements.rb xsd/mapping.rb xsd/iconvcharset.rb xsd/datatypes1999.rb xsd/datatypes.rb xsd/codegen/moduledef.rb xsd/codegen/methoddef.rb xsd/codegen/gensupport.rb xsd/codegen/commentdef.rb xsd/codegen/classdef.rb xsd/charset.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: | 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)

[Source]

# File xsd/charset.rb, line 116
  def Charset.charset_label(encoding)
    CharsetMap[encoding.upcase]
  end
charset_str(label)

[Source]

# File 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
encoding()

handlers

[Source]

# File xsd/charset.rb, line 84
  def Charset.encoding
    @internal_encoding
  end
encoding=(encoding)

[Source]

# File xsd/charset.rb, line 88
  def Charset.encoding=(encoding)
    warn("xsd charset is set to #{encoding}") if $DEBUG
    @internal_encoding = encoding
  end
encoding_conv(str, enc_from, enc_to)

[Source]

# File 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
encoding_from_xml(str, charset)

[Source]

# File xsd/charset.rb, line 101
  def Charset.encoding_from_xml(str, charset)
    encoding_conv(str, charset_str(charset), @internal_encoding)
  end
encoding_to_xml(str, charset)

[Source]

# File xsd/charset.rb, line 97
  def Charset.encoding_to_xml(str, charset)
    encoding_conv(str, @internal_encoding, charset_str(charset))
  end
init()

[Source]

# File 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
is_ces(str, code = $KCODE)

[Source]

# File 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
is_euc(str)

[Source]

# File xsd/charset.rb, line 162
  def Charset.is_euc(str)
    EUCRegexp =~ str
  end
is_sjis(str)

[Source]

# File xsd/charset.rb, line 166
  def Charset.is_sjis(str)
    SJISRegexp =~ str
  end
is_us_ascii(str)

[Source]

# File xsd/charset.rb, line 154
  def Charset.is_us_ascii(str)
    USASCIIRegexp =~ str
  end
is_utf8(str)

[Source]

# File xsd/charset.rb, line 158
  def Charset.is_utf8(str)
    UTF8Regexp =~ str
  end
xml_encoding_label()

[Source]

# File xsd/charset.rb, line 93
  def Charset.xml_encoding_label
    charset_label(@internal_encoding)
  end


Class: XSD::Charset::CharsetConversionError

Class | XSD::Charset::CharsetConversionError
In: | xsd/charset.rb
Parent: | CharsetError


Class: XSD::Charset::CharsetError

Class | XSD::Charset::CharsetError
In: | xsd/charset.rb
Parent: | XSDError


Class: XSD::Charset::UnknownCharsetError

Class | XSD::Charset::UnknownCharsetError
In: | xsd/charset.rb
Parent: | CharsetError


Class: XSD::Charset::XSDError

Class | XSD::Charset::XSDError
In: | xsd/charset.rb
Parent: | StandardError


Module: XSD::CodeGen

Module | XSD::CodeGen
In: | xsd/codegen/moduledef.rb xsd/codegen/methoddef.rb xsd/codegen/gensupport.rb xsd/codegen/commentdef.rb xsd/codegen/classdef.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: | xsd/codegen/classdef.rb
Parent: | ModuleDef

Methods

def_attr def_classvar dump new

Included Modules

GenSupport

Public Class methods

new(name, baseclass = nil)

[Source]

# File xsd/codegen/classdef.rb, line 21
  def initialize(name, baseclass = nil)
    super(name)
    @baseclass = baseclass
    @classvar = []
    @attrdef = []
  end

Public Instance methods

def_attr(attrname, writable = true, varname = nil)

[Source]

# File 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
def_classvar(var, value)

[Source]

# File 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
dump()

[Source]

# File 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


Module: XSD::CodeGen::CommentDef

Module | XSD::CodeGen::CommentDef
In: | xsd/codegen/commentdef.rb

Included Modules

GenSupport

Attributes

comment [RW]


Module: XSD::CodeGen::GenSupport

Module | XSD::CodeGen::GenSupport
In: | xsd/codegen/gensupport.rb

Methods

capitalize format keyword? safeconstname safeconstname? safemethodname safemethodname? safevarname safevarname? uncapitalize

Public Instance methods

capitalize(target)

[Source]

# File xsd/codegen/gensupport.rb, line 58
  def capitalize(target)
    target.sub(/^([a-z])/) { $1.tr!('[a-z]', '[A-Z]') }
  end
format(str, indent = nil)

[Source]

# File 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
keyword?(word)

[Source]

# File xsd/codegen/gensupport.rb, line 114
  def keyword?(word)
    KEYWORD.key?(word)
  end
safeconstname(name)

[Source]

# File 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?(name)

[Source]

# File xsd/codegen/gensupport.rb, line 79
  def safeconstname?(name)
    /\A[A-Z][a-zA-Z0-9_]*\z/ =~ name and !keyword?(name)
  end
safemethodname(name)

[Source]

# File 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?(name)

[Source]

# File xsd/codegen/gensupport.rb, line 94
  def safemethodname?(name)
    /\A[a-zA-Z_][a-zA-Z0-9_]*[=!?]?\z/ =~ name
  end
safevarname(name)

[Source]

# File 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?(name)

[Source]

# File xsd/codegen/gensupport.rb, line 109
  def safevarname?(name)
    /\A[a-z_][a-zA-Z0-9_]*\z/ =~ name and !keyword?(name)
  end
uncapitalize(target)

[Source]

# File xsd/codegen/gensupport.rb, line 63
  def uncapitalize(target)
    target.sub(/^([A-Z])/) { $1.tr!('[A-Z]', '[a-z]') }
  end


Class: XSD::CodeGen::MethodDef

Class | XSD::CodeGen::MethodDef
In: | 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?| ...}

[Source]

# File 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

Public Instance methods

dump()

[Source]

# File 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


Class: XSD::CodeGen::ModuleDef

Class | XSD::CodeGen::ModuleDef
In: | 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)

[Source]

# File xsd/codegen/moduledef.rb, line 22
  def initialize(name)
    @name = name
    @comment = nil
    @const = []
    @code = []
    @requirepath = []
    @methoddef = []
  end

Public Instance methods

add_method(m, visibility = :public)

[Source]

# File xsd/codegen/moduledef.rb, line 60
  def add_method(m, visibility = :public)
    @methoddef << [visibility, m]
  end
def_code(code)

[Source]

# File xsd/codegen/moduledef.rb, line 42
  def def_code(code)
    @code << code
  end
def_const(const, value)

[Source]

# File 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_method(name, *params) {|if block_given?| ...}

[Source]

# File xsd/codegen/moduledef.rb, line 46
  def def_method(name, *params)
    add_method(MethodDef.new(name, *params) { yield if block_given? }, :public)
  end
def_privatemethod(name, *params) {|if block_given?| ...}

[Source]

# File xsd/codegen/moduledef.rb, line 56
  def def_privatemethod(name, *params)
    add_method(MethodDef.new(name, *params) { yield if block_given? }, :private)
  end
def_protectedmethod(name, *params) {|if block_given?| ...}

[Source]

# File xsd/codegen/moduledef.rb, line 51
  def def_protectedmethod(name, *params)
    add_method(MethodDef.new(name, *params) { yield if block_given? },
      :protected)
  end
def_publicmethod(name, *params)

Alias for def_method

def_require(path)

[Source]

# File xsd/codegen/moduledef.rb, line 31
  def def_require(path)
    @requirepath << path
  end
dump()

[Source]

# File 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


Class: XSD::Error

Class | XSD::Error
In: | xsd/datatypes.rb
Parent: | StandardError


Module: XSD::FloatConstants

Module | XSD::FloatConstants
In: | 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: | xsd/iconvcharset.rb
Parent: | Object

Methods

safe_iconv

Public Class methods

safe_iconv(to, from, str)

[Source]

# File 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


Module: XSD::Mapping

Module | XSD::Mapping
In: | 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)

[Source]

# File 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(stream)

[Source]

# File xsd/mapping.rb, line 34
  def self.xml2obj(stream)
    parser = SOAP::Parser.new(MappingOpt)
    soap = parser.parse(stream)
    SOAP::Mapping.soap2obj(soap, MappingRegistry)
  end


Class: XSD::NS

Class | XSD::NS
In: | xsd/ns.rb
Parent: | Object

Methods

assign assigned? assigned_tag? 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 = {})

[Source]

# File 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

Public Instance methods

assign(ns, tag = nil)

[Source]

# File 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?(ns)

[Source]

# File xsd/ns.rb, line 56
  def assigned?(ns)
    @default_namespace == ns or @ns2tag.key?(ns)
  end
assigned_tag?(tag)

[Source]

# File xsd/ns.rb, line 60
  def assigned_tag?(tag)
    @tag2ns.key?(tag)
  end
clone_ns()

[Source]

# File 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
compare(ns, name, rhs)

[Source]

# File 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
each_ns() {|ns, tag| ...}

[Source]

# File xsd/ns.rb, line 126
  def each_ns
    @ns2tag.each do |ns, tag|
      yield(ns, tag)
    end
  end
name(name)

[Source]

# File 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
parse(str, local = false)

[Source]

# File 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(elem)

For local attribute key parsing

  <foo xmlns="urn:a" xmlns:n1="urn:a" bar="1" n1:baz="2" />
    =>
  {}bar, {urn:a}baz

[Source]

# File 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


Class: XSD::NS::Assigner

Class | XSD::NS::Assigner
In: | xsd/ns.rb
Parent: | Object

Methods

assign new

Public Class methods

new()

[Source]

# File xsd/ns.rb, line 17
    def initialize
      @count = 0
    end

Public Instance methods

assign(ns)

[Source]

# File xsd/ns.rb, line 21
    def assign(ns)
      @count += 1
      "n#{@count}"
    end


Class: XSD::NS::FormatError

Class | XSD::NS::FormatError
In: | xsd/ns.rb
Parent: | Error


Class: XSD::NSDBase

Class | XSD::NSDBase
In: | 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)

[Source]

# File xsd/datatypes.rb, line 92
  def self.inherited(klass)
    @@types << klass
  end
new()

[Source]

# File xsd/datatypes.rb, line 100
  def initialize
  end
types()

[Source]

# File xsd/datatypes.rb, line 96
  def self.types
    @@types
  end

Public Instance methods

init(type)

[Source]

# File xsd/datatypes.rb, line 103
  def init(type)
    @type = type
  end


Class: XSD::NamedElements

Class | XSD::NamedElements
In: | xsd/namedelements.rb
Parent: | Object

Methods

+ << [] concat delete dup each empty? find_name freeze keys new size

Included Modules

Enumerable

Constants

Empty = NamedElements.new.freeze

Public Class methods

new()

[Source]

# File xsd/namedelements.rb, line 15
  def initialize
    @elements = []
    @cache = {}
  end

Public Instance methods

+(rhs)

[Source]

# File xsd/namedelements.rb, line 71
  def +(rhs)
    o = NamedElements.new
    o.elements = @elements + rhs.elements
    o
  end
<<(rhs)

[Source]

# File xsd/namedelements.rb, line 62
  def <<(rhs)
    @elements << rhs
    self
  end
[](idx)

[Source]

# File 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
concat(rhs)

[Source]

# File xsd/namedelements.rb, line 77
  def concat(rhs)
    @elements.concat(rhs.elements)
    self
  end
delete(rhs)

[Source]

# File xsd/namedelements.rb, line 67
  def delete(rhs)
    @elements.delete(rhs)
  end
dup()

[Source]

# File xsd/namedelements.rb, line 20
  def dup
    o = NamedElements.new
    o.elements = @elements.dup
    o
  end
each() {|element| ...}

[Source]

# File xsd/namedelements.rb, line 56
  def each
    @elements.each do |element|
      yield(element)
    end
  end
empty?()

[Source]

# File xsd/namedelements.rb, line 32
  def empty?
    size == 0
  end
find_name(name)

[Source]

# File xsd/namedelements.rb, line 48
  def find_name(name)
    @elements.find { |item| item.name.name == name }
  end
freeze()

[Source]

# File xsd/namedelements.rb, line 26
  def freeze
    super
    @elements.freeze
    self
  end
keys()

[Source]

# File xsd/namedelements.rb, line 52
  def keys
    collect { |element| element.name }
  end
size()

[Source]

# File xsd/namedelements.rb, line 36
  def size
    @elements.size
  end


Class: XSD::QName

Class | XSD::QName
In: | 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)

[Source]

# File xsd/qname.rb, line 17
  def initialize(namespace = nil, name = nil)
    @namespace = namespace
    @name = name
    @source = nil
  end

Public Instance methods

==(rhs)

[Source]

# File xsd/qname.rb, line 43
  def ==(rhs)
    !rhs.nil? and @namespace == rhs.namespace and @name == rhs.name
  end
===(rhs)

[Source]

# File xsd/qname.rb, line 47
  def ===(rhs)
    (self == rhs)
  end
dump()

[Source]

# File 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
dup_name(name)

[Source]

# File xsd/qname.rb, line 23
  def dup_name(name)
    XSD::QName.new(@namespace, name)
  end
eql?(rhs)

[Source]

# File xsd/qname.rb, line 51
  def eql?(rhs)
    (self == rhs)
  end
hash()

[Source]

# File xsd/qname.rb, line 55
  def hash
    @namespace.hash ^ @name.hash
  end
inspect()

[Source]

# File xsd/qname.rb, line 63
  def inspect
    sprintf("#<%s:0x%x %s>", self.class.name, __id__,
      "{#{ namespace }}#{ name }")
  end
match(rhs)

[Source]

# File 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
parse(str)

[Source]

# File xsd/qname.rb, line 69
  def parse(str)
    NormalizedNameRegexp =~ str
    self.new($1, $2)
  end
to_s()

[Source]

# File xsd/qname.rb, line 59
  def to_s
    "{#{ namespace }}#{ name }"
  end


Class: XSD::ValueSpaceError

Class | XSD::ValueSpaceError
In: | xsd/datatypes.rb
Parent: | Error


Module: XSD::XMLParser

Module | XSD::XMLParser
In: | xsd/xmlparser.rb xsd/xmlparser/xmlscanner.rb xsd/xmlparser/xmlparser.rb xsd/xmlparser/rexmlparser.rb 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)

[Source]

# File xsd/xmlparser.rb, line 16
  def create_parser(host, opt)
    XSD::XMLParser::Parser.create_parser(host, opt)
  end
filter_ns(ns, attrs)

[Source]

# File 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


Class: XSD::XMLParser::Parser

Class | XSD::XMLParser::Parser
In: | 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)

[Source]

# File xsd/xmlparser/parser.rb, line 36
  def self.add_factory(factory)
    if $DEBUG
      puts "Set #{ factory } as XML processor."
    end
    @@parser_factory = factory
  end
create_parser(host, opt = {})

[Source]

# File xsd/xmlparser/parser.rb, line 32
  def self.create_parser(host, opt = {})
    @@parser_factory.new(host, opt)
  end
factory()

[Source]

# File xsd/xmlparser/parser.rb, line 28
  def self.factory
    @@parser_factory
  end
new(host, opt = {})

[Source]

# File xsd/xmlparser/parser.rb, line 47
  def initialize(host, opt = {})
    @host = host
    @charset = opt[:charset] || nil
  end

Public Instance methods

parse(string_or_readable)

[Source]

# File xsd/xmlparser/parser.rb, line 52
  def parse(string_or_readable)
    @textbuf = ''
    prologue
    do_parse(string_or_readable)
    epilogue
  end


Class: XSD::XMLParser::Parser::ElementConstraintError

Class | XSD::XMLParser::Parser::ElementConstraintError
In: | xsd/xmlparser/parser.rb
Parent: | FormatDecodeError


Class: XSD::XMLParser::Parser::FormatDecodeError

Class | XSD::XMLParser::Parser::FormatDecodeError
In: | xsd/xmlparser/parser.rb
Parent: | ParseError


Class: XSD::XMLParser::Parser::ParseError

Class | XSD::XMLParser::Parser::ParseError
In: | xsd/xmlparser/parser.rb
Parent: | Error


Class: XSD::XMLParser::Parser::UnexpectedElementError

Class | XSD::XMLParser::Parser::UnexpectedElementError
In: | xsd/xmlparser/parser.rb
Parent: | FormatDecodeError


Class: XSD::XMLParser::Parser::UnknownAttributeError

Class | XSD::XMLParser::Parser::UnknownAttributeError
In: | xsd/xmlparser/parser.rb
Parent: | FormatDecodeError


Class: XSD::XMLParser::Parser::UnknownElementError

Class | XSD::XMLParser::Parser::UnknownElementError
In: | xsd/xmlparser/parser.rb
Parent: | FormatDecodeError


Class: XSD::XMLParser::REXMLParser

Class | XSD::XMLParser::REXMLParser
In: | 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)

[Source]

# File 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()

[Source]

# File xsd/xmlparser/rexmlparser.rb, line 30
  def epilogue
  end
tag_end(name)

[Source]

# File xsd/xmlparser/rexmlparser.rb, line 37
  def tag_end(name)
    end_element(name)
  end
tag_start(name, attrs)

[Source]

# File xsd/xmlparser/rexmlparser.rb, line 33
  def tag_start(name, attrs)
    start_element(name, attrs)
  end
text(text)

[Source]

# File xsd/xmlparser/rexmlparser.rb, line 41
  def text(text)
    characters(text)
  end
xmldecl(version, encoding, standalone)

[Source]

# File xsd/xmlparser/rexmlparser.rb, line 45
  def xmldecl(version, encoding, standalone)
    # Version should be checked.
  end


Class: XSD::XMLParser::XMLParser

Class | XSD::XMLParser::XMLParser
In: | 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)

[Source]

# File 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


Class: XSD::XMLParser::XMLParser::Listener

Class | XSD::XMLParser::XMLParser::Listener
In: | xsd/xmlparser/xmlparser.rb
Parent: | XML::Parser

Included Modules

XML::Encoding_ja


Class: XSD::XMLParser::XMLScanner

Class | XSD::XMLParser::XMLScanner
In: | 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)

[Source]

# File 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
on_attr_charref(code)

[Source]

# File xsd/xmlparser/xmlscanner.rb, line 123
  def on_attr_charref(code)
    @curattr << [code].pack('U')
  end
on_attr_charref_hex(code)

[Source]

# File xsd/xmlparser/xmlscanner.rb, line 127
  def on_attr_charref_hex(code)
    on_attr_charref(code)
  end
on_attr_entityref(ref)

[Source]

# File xsd/xmlparser/xmlscanner.rb, line 119
  def on_attr_entityref(ref)
    @curattr << ENTITY_REF_MAP[ref]
  end
on_attr_value(str)

[Source]

# File xsd/xmlparser/xmlscanner.rb, line 115
  def on_attr_value(str)
    @curattr << str
  end
on_attribute(name)

[Source]

# File xsd/xmlparser/xmlscanner.rb, line 111
  def on_attribute(name)
    @attrs[name] = @curattr = ''
  end
on_chardata(str)

def on_pi(target, pi); end

[Source]

# File xsd/xmlparser/xmlscanner.rb, line 81
  def on_chardata(str)
    characters(str)
  end
on_charref(code)

[Source]

# File xsd/xmlparser/xmlscanner.rb, line 95
  def on_charref(code)
    characters([code].pack('U'))
  end
on_charref_hex(code)

[Source]

# File xsd/xmlparser/xmlscanner.rb, line 99
  def on_charref_hex(code)
    on_charref(code)
  end
on_entityref(ref)

[Source]

# File xsd/xmlparser/xmlscanner.rb, line 91
  def on_entityref(ref)
    characters(ENTITY_REF_MAP[ref])
  end
on_etag(name)

def on_cdata(str); end

[Source]

# File xsd/xmlparser/xmlscanner.rb, line 87
  def on_etag(name)
    end_element(name)
  end
on_stag(name)

def on_end_document; end

[Source]

# File xsd/xmlparser/xmlscanner.rb, line 107
  def on_stag(name)
    @attrs = {}
  end
on_stag_end(name)

[Source]

# File xsd/xmlparser/xmlscanner.rb, line 138
  def on_stag_end(name)
    start_element(name, @attrs)
  end
on_stag_end_empty(name)

def on_attribute_end(name); end

[Source]

# File xsd/xmlparser/xmlscanner.rb, line 133
  def on_stag_end_empty(name)
    on_stag_end(name)
    on_etag(name)
  end
on_xmldecl_encoding(str)

[Source]

# File xsd/xmlparser/xmlscanner.rb, line 63
  def on_xmldecl_encoding(str)
    self.scanner_kcode = str
  end
on_xmldecl_version(str)

def on_xmldecl; end

[Source]

# File xsd/xmlparser/xmlscanner.rb, line 59
  def on_xmldecl_version(str)
    # 1.0 expected.
  end
parse_error(msg)

[Source]

# File xsd/xmlparser/xmlscanner.rb, line 41
  def parse_error(msg)
    raise ParseError.new(msg)
  end
scanner_kcode=(charset)

[Source]

# File xsd/xmlparser/xmlscanner.rb, line 28
  def scanner_kcode=(charset)
    @scanner.kcode = XSD::Charset.charset_str(charset) if charset
    self.xmldecl_encoding = charset
  end
valid_error(msg)

[Source]

# File xsd/xmlparser/xmlscanner.rb, line 49
  def valid_error(msg)
    raise NotValidError.new(msg)
  end
warning(msg)

[Source]

# File xsd/xmlparser/xmlscanner.rb, line 53
  def warning(msg)
    p msg if $DEBUG
  end
wellformed_error(msg)

[Source]

# File xsd/xmlparser/xmlscanner.rb, line 45
  def wellformed_error(msg)
    raise NotWellFormedError.new(msg)
  end


Class: XSD::XSDAnySimpleType

Class | XSD::XSDAnySimpleType
In: | 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)

[Source]

# File xsd/datatypes.rb, line 121
  def initialize(value = nil)
    init(Type, value)
  end

Public Instance methods

check_lexical_format(value)

true or raise

[Source]

# File xsd/datatypes.rb, line 126
  def check_lexical_format(value)
    screen_data(value)
    true
  end
set(value)

set accepts a string which follows lexical space (ex. String: "+123"), or an object which follows canonical space (ex. Integer: 123).

[Source]

# File 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()

to_s creates a string which follows lexical space (ex. String: "123").

[Source]

# File xsd/datatypes.rb, line 145
  def to_s()
    if @is_nil
      ""
    else
      _to_s
    end
  end


Class: XSD::XSDAnyURI

Class | XSD::XSDAnyURI
In: | xsd/datatypes.rb
Parent: | XSDAnySimpleType

Methods

new

Constants

Type = QName.new(Namespace, AnyURILiteral)

Public Class methods

new(value = nil)

[Source]

# File xsd/datatypes.rb, line 929
  def initialize(value = nil)
    init(Type, value)
  end


Class: XSD::XSDBase64Binary

Class | XSD::XSDBase64Binary
In: | 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.

[Source]

# File xsd/datatypes.rb, line 903
  def initialize(value = nil)
    init(Type, value)
  end

Public Instance methods

set_encoded(value)

[Source]

# File 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()

[Source]

# File xsd/datatypes.rb, line 915
  def string
    @data.unpack("m")[0]
  end


Class: XSD::XSDBoolean

Class | XSD::XSDBoolean
In: | xsd/datatypes.rb
Parent: | XSDAnySimpleType

Methods

new

Constants

Type = QName.new(Namespace, BooleanLiteral)

Public Class methods

new(value = nil)

[Source]

# File xsd/datatypes.rb, line 207
  def initialize(value = nil)
    init(Type, value)
  end


Class: XSD::XSDByte

Class | XSD::XSDByte
In: | xsd/datatypes.rb
Parent: | XSDShort

Methods

new

Constants

Type = QName.new(Namespace, ByteLiteral)

Public Class methods

new(value = nil)

[Source]

# File xsd/datatypes.rb, line 1145
  def initialize(value = nil)
    init(Type, value)
  end


Class: XSD::XSDDate

Class | XSD::XSDDate
In: | xsd/datatypes.rb
Parent: | XSDAnySimpleType

Methods

new

Included Modules

XSDDateTimeImpl

Constants

Type = QName.new(Namespace, DateLiteral)

Public Class methods

new(value = nil)

[Source]

# File xsd/datatypes.rb, line 704
  def initialize(value = nil)
    init(Type, value)
  end


Class: XSD::XSDDateTime

Class | XSD::XSDDateTime
In: | xsd/datatypes.rb
Parent: | XSDAnySimpleType

Methods

new

Included Modules

XSDDateTimeImpl

Constants

Type = QName.new(Namespace, DateTimeLiteral)

Public Class methods

new(value = nil)

[Source]

# File xsd/datatypes.rb, line 591
  def initialize(value = nil)
    init(Type, value)
  end


Module: XSD::XSDDateTimeImpl

Module | XSD::XSDDateTimeImpl
In: | 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)

[Source]

# File xsd/datatypes.rb, line 582
  def add_tz(s)
    s + of2tz(@data.offset)
  end
of2tz(offset)

[Source]

# File 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(t)

[Source]

# File 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
to_date()

[Source]

# File 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()

[Source]

# File xsd/datatypes.rb, line 530
  def to_datetime
    data
  end
to_obj(klass)

[Source]

# File 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()

[Source]

# File 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
tz2of(str)

[Source]

# File 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


Class: XSD::XSDDecimal

Class | XSD::XSDDecimal
In: | xsd/datatypes.rb
Parent: | XSDAnySimpleType

Methods

new nonzero?

Constants

Type = QName.new(Namespace, DecimalLiteral)

Public Class methods

new(value = nil)

[Source]

# File xsd/datatypes.rb, line 232
  def initialize(value = nil)
    init(Type, value)
  end

Public Instance methods

nonzero?()

[Source]

# File xsd/datatypes.rb, line 236
  def nonzero?
    (@number != '0')
  end


Class: XSD::XSDDouble

Class | XSD::XSDDouble
In: | 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)

[Source]

# File xsd/datatypes.rb, line 372
  def initialize(value = nil)
    init(Type, value)
  end


Class: XSD::XSDDuration

Class | XSD::XSDDuration
In: | 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)

[Source]

# File xsd/datatypes.rb, line 433
  def initialize(value = nil)
    init(Type, value)
  end


Class: XSD::XSDFloat

Class | XSD::XSDFloat
In: | xsd/datatypes.rb
Parent: | XSDAnySimpleType

Methods

new

Included Modules

FloatConstants

Constants

Type = QName.new(Namespace, FloatLiteral)

Public Class methods

new(value = nil)

[Source]

# File xsd/datatypes.rb, line 306
  def initialize(value = nil)
    init(Type, value)
  end


Class: XSD::XSDGDay

Class | XSD::XSDGDay
In: | xsd/datatypes.rb
Parent: | XSDAnySimpleType

Methods

new

Included Modules

XSDDateTimeImpl

Constants

Type = QName.new(Namespace, GDayLiteral)

Public Class methods

new(value = nil)

[Source]

# File xsd/datatypes.rb, line 824
  def initialize(value = nil)
    init(Type, value)
  end


Class: XSD::XSDGMonth

Class | XSD::XSDGMonth
In: | xsd/datatypes.rb
Parent: | XSDAnySimpleType

Methods

new

Included Modules

XSDDateTimeImpl

Constants

Type = QName.new(Namespace, GMonthLiteral)

Public Class methods

new(value = nil)

[Source]

# File xsd/datatypes.rb, line 850
  def initialize(value = nil)
    init(Type, value)
  end


Class: XSD::XSDGMonthDay

Class | XSD::XSDGMonthDay
In: | xsd/datatypes.rb
Parent: | XSDAnySimpleType

Methods

new

Included Modules

XSDDateTimeImpl

Constants

Type = QName.new(Namespace, GMonthDayLiteral)

Public Class methods

new(value = nil)

[Source]

# File xsd/datatypes.rb, line 797
  def initialize(value = nil)
    init(Type, value)
  end


Class: XSD::XSDGYear

Class | XSD::XSDGYear
In: | xsd/datatypes.rb
Parent: | XSDAnySimpleType

Methods

new

Included Modules

XSDDateTimeImpl

Constants

Type = QName.new(Namespace, GYearLiteral)

Public Class methods

new(value = nil)

[Source]

# File xsd/datatypes.rb, line 767
  def initialize(value = nil)
    init(Type, value)
  end


Class: XSD::XSDGYearMonth

Class | XSD::XSDGYearMonth
In: | xsd/datatypes.rb
Parent: | XSDAnySimpleType

Methods

new

Included Modules

XSDDateTimeImpl

Constants

Type = QName.new(Namespace, GYearMonthLiteral)

Public Class methods

new(value = nil)

[Source]

# File xsd/datatypes.rb, line 736
  def initialize(value = nil)
    init(Type, value)
  end


Class: XSD::XSDHexBinary

Class | XSD::XSDHexBinary
In: | 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.

[Source]

# File xsd/datatypes.rb, line 876
  def initialize(value = nil)
    init(Type, value)
  end

Public Instance methods

set_encoded(value)

[Source]

# File 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()

[Source]

# File xsd/datatypes.rb, line 888
  def string
    [@data].pack("H*")
  end


Class: XSD::XSDInt

Class | XSD::XSDInt
In: | xsd/datatypes.rb
Parent: | XSDLong

Methods

new

Constants

Type = QName.new(Namespace, IntLiteral)

Public Class methods

new(value = nil)

[Source]

# File xsd/datatypes.rb, line 1109
  def initialize(value = nil)
    init(Type, value)
  end


Class: XSD::XSDInteger

Class | XSD::XSDInteger
In: | xsd/datatypes.rb
Parent: | XSDDecimal

Methods

new

Constants

Type | = | QName.new(Namespace, IntegerLiteral)
PositiveMinInclusive | = | 1

Public Class methods

new(value = nil)

[Source]

# File xsd/datatypes.rb, line 1006
  def initialize(value = nil)
    init(Type, value)
  end


Class: XSD::XSDLong

Class | XSD::XSDLong
In: | xsd/datatypes.rb
Parent: | XSDInteger

Methods

new

Constants

Type = QName.new(Namespace, LongLiteral)

Public Class methods

new(value = nil)

[Source]

# File xsd/datatypes.rb, line 1091
  def initialize(value = nil)
    init(Type, value)
  end


Class: XSD::XSDNegativeInteger

Class | XSD::XSDNegativeInteger
In: | xsd/datatypes.rb
Parent: | XSDNonPositiveInteger

Methods

new

Constants

Type = QName.new(Namespace, NegativeIntegerLiteral)

Public Class methods

new(value = nil)

[Source]

# File xsd/datatypes.rb, line 1073
  def initialize(value = nil)
    init(Type, value)
  end


Class: XSD::XSDNil

Class | XSD::XSDNil
In: | xsd/datatypes.rb
Parent: | XSDAnySimpleType

Methods

new

Constants

Type | = | QName.new(Namespace, NilLiteral)
Value | = | 'true'

Public Class methods

new(value = nil)

[Source]

# File xsd/datatypes.rb, line 178
  def initialize(value = nil)
    init(Type, value)
  end


Class: XSD::XSDNonNegativeInteger

Class | XSD::XSDNonNegativeInteger
In: | xsd/datatypes.rb
Parent: | XSDInteger

Methods

new

Constants

Type = QName.new(Namespace, NonNegativeIntegerLiteral)

Public Class methods

new(value = nil)

[Source]

# File xsd/datatypes.rb, line 1163
  def initialize(value = nil)
    init(Type, value)
  end


Class: XSD::XSDNonPositiveInteger

Class | XSD::XSDNonPositiveInteger
In: | xsd/datatypes.rb
Parent: | XSDInteger

Methods

new

Constants

Type = QName.new(Namespace, NonPositiveIntegerLiteral)

Public Class methods

new(value = nil)

[Source]

# File xsd/datatypes.rb, line 1055
  def initialize(value = nil)
    init(Type, value)
  end


Class: XSD::XSDNormalizedString

Class | XSD::XSDNormalizedString
In: | xsd/datatypes.rb
Parent: | XSDString

Derived types

Methods

new

Constants

Type = QName.new(Namespace, NormalizedStringLiteral)

Public Class methods

new(value = nil)

[Source]

# File xsd/datatypes.rb, line 989
  def initialize(value = nil)
    init(Type, value)
  end


Class: XSD::XSDPositiveInteger

Class | XSD::XSDPositiveInteger
In: | xsd/datatypes.rb
Parent: | XSDNonNegativeInteger

Methods

new

Constants

Type = QName.new(Namespace, PositiveIntegerLiteral)

Public Class methods

new(value = nil)

[Source]

# File xsd/datatypes.rb, line 1253
  def initialize(value = nil)
    init(Type, value)
  end


Class: XSD::XSDQName

Class | XSD::XSDQName
In: | xsd/datatypes.rb
Parent: | XSDAnySimpleType

Methods

new

Constants

Type = QName.new(Namespace, QNameLiteral)

Public Class methods

new(value = nil)

[Source]

# File xsd/datatypes.rb, line 947
  def initialize(value = nil)
    init(Type, value)
  end


Class: XSD::XSDShort

Class | XSD::XSDShort
In: | xsd/datatypes.rb
Parent: | XSDInt

Methods

new

Constants

Type = QName.new(Namespace, ShortLiteral)

Public Class methods

new(value = nil)

[Source]

# File xsd/datatypes.rb, line 1127
  def initialize(value = nil)
    init(Type, value)
  end


Class: XSD::XSDString

Class | XSD::XSDString
In: | xsd/datatypes.rb
Parent: | XSDAnySimpleType

Primitive datatypes.

Methods

new

Constants

Type = QName.new(Namespace, StringLiteral)

Public Class methods

new(value = nil)

[Source]

# File xsd/datatypes.rb, line 190
  def initialize(value = nil)
    init(Type, value)
  end


Class: XSD::XSDTime

Class | XSD::XSDTime
In: | xsd/datatypes.rb
Parent: | XSDAnySimpleType

Methods

new

Included Modules

XSDDateTimeImpl

Constants

Type = QName.new(Namespace, TimeLiteral)

Public Class methods

new(value = nil)

[Source]

# File xsd/datatypes.rb, line 654
  def initialize(value = nil)
    init(Type, value)
  end


Class: XSD::XSDUnsignedByte

Class | XSD::XSDUnsignedByte
In: | xsd/datatypes.rb
Parent: | XSDUnsignedShort

Methods

new

Constants

Type = QName.new(Namespace, UnsignedByteLiteral)

Public Class methods

new(value = nil)

[Source]

# File xsd/datatypes.rb, line 1235
  def initialize(value = nil)
    init(Type, value)
  end


Class: XSD::XSDUnsignedInt

Class | XSD::XSDUnsignedInt
In: | xsd/datatypes.rb
Parent: | XSDUnsignedLong

Methods

new

Constants

Type = QName.new(Namespace, UnsignedIntLiteral)

Public Class methods

new(value = nil)

[Source]

# File xsd/datatypes.rb, line 1199
  def initialize(value = nil)
    init(Type, value)
  end


Class: XSD::XSDUnsignedLong

Class | XSD::XSDUnsignedLong
In: | xsd/datatypes.rb
Parent: | XSDNonNegativeInteger

Methods

new

Constants

Type = QName.new(Namespace, UnsignedLongLiteral)

Public Class methods

new(value = nil)

[Source]

# File xsd/datatypes.rb, line 1181
  def initialize(value = nil)
    init(Type, value)
  end


Class: XSD::XSDUnsignedShort

Class | XSD::XSDUnsignedShort
In: | xsd/datatypes.rb
Parent: | XSDUnsignedInt

Methods

new

Constants

Type = QName.new(Namespace, UnsignedShortLiteral)

Public Class methods

new(value = nil)

[Source]

# File xsd/datatypes.rb, line 1217
  def initialize(value = nil)
    init(Type, value)
  end


File: charset.rb

charset.rb

Path: | xsd/charset.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

XSD4R - Charset handling library. Copyright (C) 2001, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/iconvcharset nkf uconv


File: codegen.rb

codegen.rb

Path: | xsd/codegen.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

XSD4R - Generating code library Copyright (C) 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/codegen/gensupport xsd/codegen/moduledef xsd/codegen/classdef xsd/codegen/methoddef


File: classdef.rb

classdef.rb

Path: | xsd/codegen/classdef.rb
Last Update: | Sat Oct 15 23:44:32 AUS Eastern Standard Time 2005

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: | xsd/codegen/commentdef.rb
Last Update: | Sat Oct 15 23:44:32 AUS Eastern Standard Time 2005

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: | xsd/codegen/gensupport.rb
Last Update: | Sat Oct 15 23:44:32 AUS Eastern Standard Time 2005

XSD4R - Code generation support Copyright (C) 2004, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.


File: methoddef.rb

methoddef.rb

Path: | xsd/codegen/methoddef.rb
Last Update: | Sat Oct 15 23:44:32 AUS Eastern Standard Time 2005

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: | xsd/codegen/moduledef.rb
Last Update: | Sat Oct 15 23:44:32 AUS Eastern Standard Time 2005

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: datatypes.rb

datatypes.rb

Path: | xsd/datatypes.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: datatypes1999.rb

datatypes1999.rb

Path: | xsd/datatypes1999.rb
Last Update: | Tue Nov 25 17:31:31 AUS Eastern Daylight Time 2003

XSD4R - XML Schema Datatype 1999 support Copyright (C) 2001, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/datatypes


File: iconvcharset.rb

iconvcharset.rb

Path: | xsd/iconvcharset.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

XSD4R - Charset handling with iconv. Copyright (C) 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

iconv


File: mapping.rb

mapping.rb

Path: | xsd/mapping.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | xsd/namedelements.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

XSD4R - WSDL named element collection. Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.


File: ns.rb

ns.rb

Path: | xsd/ns.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

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: | xsd/qname.rb
Last Update: | Sat Oct 15 23:44:31 AUS Eastern Standard Time 2005

XSD4R - XML QName definition. Copyright (C) 2002, 2003, 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.


File: xmlparser.rb

xmlparser.rb

Path: | xsd/xmlparser.rb
Last Update: | Sat Oct 15 23:44:32 AUS Eastern Standard Time 2005

XSD4R - XML Instance parser library. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/xmlparser/parser


File: parser.rb

parser.rb

Path: | xsd/xmlparser/parser.rb
Last Update: | Tue Nov 25 17:31:31 AUS Eastern Daylight Time 2003

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: | xsd/xmlparser/rexmlparser.rb
Last Update: | Tue Nov 25 17:31:31 AUS Eastern Daylight Time 2003

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: | xsd/xmlparser/xmlparser.rb
Last Update: | Tue Nov 25 17:31:31 AUS Eastern Daylight Time 2003

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: | xsd/xmlparser/xmlscanner.rb
Last Update: | Sat Oct 15 23:44:32 AUS Eastern Standard Time 2005

XSD4R - XMLScan XML parser library. Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/xmlparser xmlscan/scanner


Module: YAML

Module | YAML
In: | yaml.rb yaml/ypath.rb yaml/yamlnode.rb yaml/types.rb yaml/tag.rb yaml/syck.rb yaml/stream.rb yaml/loader.rb yaml/error.rb yaml/encoding.rb yaml/dbm.rb yaml/constants.rb yaml/basenode.rb yaml/baseemitter.rb

Constants used throughout the library

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

Resolver | = | YAML::Syck::Resolver
DefaultResolver | = | YAML::Syck::DefaultResolver
GenericResolver | = | YAML::Syck::GenericResolver
Parser | = | YAML::Syck::Parser
Emitter | = | YAML::Syck::Emitter
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"
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

Public Class methods

add_builtin_type( type_tag, &transfer_proc )

Add a transfer method for a builtin type

[Source]

# File 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_domain_type( domain, type_tag, &transfer_proc )

Add a global handler for a YAML domain type.

[Source]

# File 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_private_type( type_re, &transfer_proc )

Add a private document type

[Source]

# File yaml.rb, line 320
        def YAML.add_private_type( type_re, &transfer_proc )
            resolver.add_type( "x-private:" + type_re, transfer_proc )
        end
add_ruby_type( type, &transfer_proc )

Add a transfer method for a builtin type

[Source]

# File yaml.rb, line 313
        def YAML.add_ruby_type( type, &transfer_proc )
            resolver.add_type( "tag:ruby.yaml.org,2002:#{ type_tag }", transfer_proc )
        end
detect_implicit( val )

Detect typing of a string

[Source]

# File yaml.rb, line 327
    def YAML.detect_implicit( val )
        resolver.detect_implicit( val )
    end
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"

[Source]

# File yaml.rb, line 116
        def YAML.dump( obj, io = nil )
        obj.to_yaml( io || io2 = StringIO.new )
        io || ( io2.rewind; io2.read )
        end
dump_stream( *objs )

Returns a YAML stream containing each of the items in objs, each having their own document.

  YAML.dump_stream( 0, [], {} )
    #=> --- 0
        --- []
        --- {}

[Source]

# File yaml.rb, line 288
        def YAML.dump_stream( *objs )
                d = YAML::Stream.new
        objs.each do |doc|
                        d.add( doc )
        end
        d.emit
        end
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

[Source]

# File yaml.rb, line 216
        def YAML.each_document( io, &block )
                yp = parser.load_documents( io, &block )
    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

[Source]

# File yaml.rb, line 246
        def YAML.each_node( io, &doc_proc )
                yp = generic_parser.load_documents( io, &doc_proc )
    end
emitter()

Returns a new default emitter

[Source]

# File yaml.rb, line 101
    def YAML.emitter; Emitter.new.set_resolver( YAML.resolver ); end
escape( value, skip = "" )

Escape the string, condensing common escapes

[Source]

# File 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
generic_parser()

Returns a new generic parser

[Source]

# File yaml.rb, line 97
    def YAML.generic_parser; Parser.new.set_resolver( GenericResolver ); end
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

[Source]

# File yaml.rb, line 132
        def YAML.load( io )
                yp = parser.load( io )
        end
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

[Source]

# File yaml.rb, line 231
        def YAML.load_documents( io, &doc_proc )
                YAML.each_document( io, &doc_proc )
    end
load_file( filepath )

Load a document from the file located at filepath.

  YAML.load_file( 'animals.yaml' )
     #=> ['badger', 'elephant', 'tiger']

[Source]

# File yaml.rb, line 142
    def YAML.load_file( filepath )
        File.open( filepath ) do |f|
            load( f )
        end
    end
load_stream( io )

Loads all documents from the current io stream, returning a +YAML::Stream+ object containing all loaded documents.

[Source]

# File 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
make_stream( io )

Class method for creating streams

[Source]

# File 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
object_maker( obj_class, val )

Allocate blank object

[Source]

# File 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
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>

[Source]

# File yaml.rb, line 175
        def YAML.parse( io )
                yp = generic_parser.load( io )
        end
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

[Source]

# File yaml.rb, line 261
        def YAML.parse_documents( io, &doc_proc )
                YAML.each_node( io, &doc_proc )
    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">]>

[Source]

# File yaml.rb, line 199
    def YAML.parse_file( filepath )
        File.open( filepath ) do |f|
            parse( f )
        end
    end
parser()

Returns a new default parser

[Source]

# File yaml.rb, line 95
    def YAML.parser; Parser.new.set_resolver( YAML.resolver ); end
quick_emit( oid, opts = {}, &e )

Allocate an Emitter if needed

[Source]

# File 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
read_type_class( type, obj_class )

Method to extract colon-seperated type and class, returning the type and the constant of the class

[Source]

# File 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
resolver()

Returns the default resolver

[Source]

# File yaml.rb, line 99
    def YAML.resolver; DefaultResolver; end
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

[Source]

# File 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()

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

[Source]

# File yaml/tag.rb, line 48
    def YAML.tagged_classes
        @@tagged_classes
    end
tagurize( val )

Convert a type_id to a taguri

[Source]

# File yaml.rb, line 334
    def YAML.tagurize( val )
        resolver.tagurize( val )
    end
transfer( type_id, obj )

Apply a transfer method to a Ruby object

[Source]

# File yaml.rb, line 341
    def YAML.transfer( type_id, obj )
        resolver.transfer( YAML.tagurize( type_id ), obj )
    end
try_implicit( obj )

Apply any implicit a node may qualify for

[Source]

# File yaml.rb, line 348
        def YAML.try_implicit( obj )
                YAML.transfer( YAML.detect_implicit( obj ), obj )
        end
unescape( value )

Unescape the condenses escapes

[Source]

# File 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


Class: Array

Class | Array
In: | yaml/rubytypes.rb
Parent: | Object

Methods

to_yaml yaml_initialize

Public Instance methods

to_yaml( opts = {} )

[Source]

# File 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
yaml_initialize( tag, val )

[Source]

# File yaml/rubytypes.rb, line 105
    def yaml_initialize( tag, val ); concat( val.to_a ); end


Class: Class

Class | Class
In: | yaml/rubytypes.rb
Parent: | Object

Methods

to_yaml

Public Instance methods

to_yaml( opts = {} )

[Source]

# File yaml/rubytypes.rb, line 5
        def to_yaml( opts = {} )
                raise TypeError, "can't dump anonymous class %s" % self.class
        end


Class: Date

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

Methods

to_yaml

Public Instance methods

to_yaml( opts = {} )

[Source]

# File yaml/rubytypes.rb, line 348
        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


Class: Exception

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

Methods

to_yaml yaml_new

Public Class methods

yaml_new( klass, tag, val )

[Source]

# File 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

Public Instance methods

to_yaml( opts = {} )

[Source]

# File 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


Class: FalseClass

Class | FalseClass
In: | yaml/rubytypes.rb
Parent: | Object

Methods

to_yaml

Public Instance methods

to_yaml( opts = {} )

[Source]

# File yaml/rubytypes.rb, line 390
        def to_yaml( opts = {} )
                YAML::quick_emit( nil, opts ) do |out|
            out.scalar( taguri, "false", :plain )
        end
        end


Class: Fixnum

Class | Fixnum
In: | yaml/rubytypes.rb
Parent: | Object


Class: Float

Class | Float
In: | yaml/rubytypes.rb
Parent: | Object


Class: Hash

Class | Hash
In: | yaml/rubytypes.rb
Parent: | Object

Methods

to_yaml yaml_initialize

Public Instance methods

to_yaml( opts = {} )

[Source]

# File 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
yaml_initialize( tag, val )

[Source]

# File 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


Class: NilClass

Class | NilClass
In: | yaml/rubytypes.rb
Parent: | Object

Methods

to_yaml

Public Instance methods

to_yaml( opts = {} )

[Source]

# File yaml/rubytypes.rb, line 399
        def to_yaml( opts = {} )
                YAML::quick_emit( nil, opts ) do |out|
            out.scalar( taguri, "", :plain )
        end
        end


Class: Numeric

Class | Numeric
In: | yaml/rubytypes.rb
Parent: | Object

Methods

to_yaml

Public Instance methods

to_yaml( opts = {} )

[Source]

# File yaml/rubytypes.rb, line 356
        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( taguri, str, :plain )
        end
        end


Class: Object

Class | Object
In: | yaml/rubytypes.rb
Parent: | Object

Methods

to_yaml to_yaml_properties to_yaml_style

Public Instance methods

to_yaml( opts = {} )

[Source]

# File 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_yaml_properties()

[Source]

# File yaml/rubytypes.rb, line 13
    def to_yaml_properties; instance_variables.sort; end
to_yaml_style()

[Source]

# File yaml/rubytypes.rb, line 12
    def to_yaml_style; end


Class: Range

Class | Range
In: | yaml/rubytypes.rb
Parent: | Object

Methods

to_yaml yaml_new

Public Class methods

yaml_new( klass, tag, val )

[Source]

# File yaml/rubytypes.rb, line 200
    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

Public Instance methods

to_yaml( opts = {} )

[Source]

# File yaml/rubytypes.rb, line 228
        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


Class: Regexp

Class | Regexp
In: | yaml/rubytypes.rb
Parent: | Object

Methods

to_yaml yaml_new

Public Class methods

yaml_new( klass, tag, val )

[Source]

# File yaml/rubytypes.rb, line 254
    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

Public Instance methods

to_yaml( opts = {} )

[Source]

# File yaml/rubytypes.rb, line 277
        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


Class: String

Class | String
In: | yaml/rubytypes.rb
Parent: | Object

Methods

is_binary_data? is_complex_yaml? to_yaml yaml_new

Public Class methods

yaml_new( klass, tag, val )

[Source]

# File 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

Public Instance methods

is_binary_data?()

[Source]

# File yaml/rubytypes.rb, line 145
    def is_binary_data?
        ( self.count( "^ -~", "^\r\n" ) / self.size > 0.3 || self.count( "\x00" ) > 0 ) unless empty?
    end
is_complex_yaml?()

[Source]

# File yaml/rubytypes.rb, line 142
    def is_complex_yaml?
        to_yaml_style or not to_yaml_properties.empty? or self =~ /\n.+/
    end
to_yaml( opts = {} )

[Source]

# File 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


Class: StringIO

Class | StringIO
In: | yaml/stringio.rb
Parent: | Object

StringIO based on code by MoonWolf

Methods

eof eof? new pos readline rewind seek

Public Class methods

new(string="")

[Source]

# File yaml/stringio.rb, line 9
        def initialize(string="")
            @string=string
            @pos=0
            @eof=(string.size==0)
        end

Public Instance methods

eof()

[Source]

# File yaml/stringio.rb, line 17
        def eof
            @eof
        end
eof?()

Alias for eof

pos()

[Source]

# File yaml/stringio.rb, line 14
        def pos
            @pos
        end
readline(rs=$/)

[Source]

# File 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()

[Source]

# File yaml/stringio.rb, line 35
        def rewind
            seek(0,0)
        end
seek(offset,whence)

[Source]

# File 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


Class: Struct

Class | Struct
In: | yaml/rubytypes.rb
Parent: | Object

Methods

to_yaml yaml_new yaml_tag_class_name yaml_tag_read_class

Public Class methods

yaml_new( klass, tag, val )

[Source]

# File 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
yaml_tag_class_name()

[Source]

# File yaml/rubytypes.rb, line 50
    def self.yaml_tag_class_name; self.name.gsub( "Struct::", "" ); end
yaml_tag_read_class( name )

[Source]

# File yaml/rubytypes.rb, line 51
    def self.yaml_tag_read_class( name ); "Struct::#{ name }"; end

Public Instance methods

to_yaml( opts = {} )

[Source]

# File 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


Class: Symbol

Class | Symbol
In: | yaml/rubytypes.rb
Parent: | Object

Methods

to_yaml yaml_new

Public Class methods

yaml_new( klass, tag, val )

[Source]

# File yaml/rubytypes.rb, line 184
    def Symbol.yaml_new( klass, tag, val )
        if String === val
            val.intern
        else
            raise YAML::TypeError, "Invalid Symbol: " + val.inspect
        end
    end

Public Instance methods

to_yaml( opts = {} )

[Source]

# File yaml/rubytypes.rb, line 191
        def to_yaml( opts = {} )
                YAML::quick_emit( nil, opts ) do |out|
            out.scalar( "tag:yaml.org,2002:str", self.inspect, :plain )
        end
        end


Class: Time

Class | Time
In: | yaml/rubytypes.rb
Parent: | Object

Methods

to_yaml yaml_new

Public Class methods

yaml_new( klass, tag, val )

[Source]

# File yaml/rubytypes.rb, line 302
    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

Public Instance methods

to_yaml( opts = {} )

[Source]

# File yaml/rubytypes.rb, line 311
        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


Class: TrueClass

Class | TrueClass
In: | yaml/rubytypes.rb
Parent: | Object

Methods

to_yaml

Public Instance methods

to_yaml( opts = {} )

[Source]

# File yaml/rubytypes.rb, line 381
        def to_yaml( opts = {} )
                YAML::quick_emit( nil, opts ) do |out|
            out.scalar( taguri, "true", :plain )
        end
        end


Module: YAML::BaseEmitter

Module | YAML::BaseEmitter
In: | 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

[Source]

# File yaml/baseemitter.rb, line 28
        def binary_base64( value )
            self << "!binary "
            self.node_text( [value].pack("m"), '|' )
        end
double( value )

Emit double-quoted string

[Source]

# File yaml/baseemitter.rb, line 89
                def double( value )
                        "\"#{YAML.escape( value )}\""
                end
fold( value )

Folding paragraphs within a column

[Source]

# File 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
indent( mod = nil )

Write a current indent

[Source]

# File 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!()

Add indent to the buffer

[Source]

# File yaml/baseemitter.rb, line 127
                def indent!
                        self << indent
                end
indent_text( text, mod, first_line = true )

Write a text block with the current indent

[Source]

# File 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
map( type, &e )

Quick mapping

[Source]

# File 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
node_text( value, block = nil )

Emit plain, normal flowing text

[Source]

# File 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
options( opt = nil )

[Source]

# File yaml/baseemitter.rb, line 13
        def options( opt = nil )
            if opt
                @options[opt] || YAML::DEFAULTS[opt]
            else
                @options
            end
        end
options=( opt )

[Source]

# File yaml/baseemitter.rb, line 21
        def options=( opt )
            @options = opt
        end
seq( type, &e )

Quick sequence

[Source]

# File 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
seq_map_shortcut()

[Source]

# File 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
simple( value )

Emit a simple, unqouted string

[Source]

# File yaml/baseemitter.rb, line 81
                def simple( value )
            @seq_map = false
            self << value.to_s
                end
single( value )

Emit single-quoted string

[Source]

# File yaml/baseemitter.rb, line 96
                def single( value )
                        "'#{value}'"
                end


Module: YAML::BaseNode

Module | YAML::BaseNode
In: | 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.

[Source]

# File 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
at( seg )

[Source]

# File 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
children()

[Source]

# File 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()

[Source]

# File 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()

[Source]

# File yaml/basenode.rb, line 210
        def emit
            transform.to_yaml
        end
match_path( ypath_str )

YPath search returning a complete depth array

[Source]

# File 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( ypath, depth )

Search a node for a single YPath segment

[Source]

# File 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
search( ypath_str )

Search for YPath entry and return a list of qualified paths.

[Source]

# File 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
select( ypath_str )

Search for YPath entry and return qualified nodes.

[Source]

# File 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!( ypath_str )

Search for YPath entry and return transformed nodes.

[Source]

# File 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


Class: YAML::DBM

Class | YAML::DBM
In: | 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 )

[Source]

# File yaml/dbm.rb, line 11
    def []( key )
        fetch( key )
    end
[]=( key, val )

[Source]

# File yaml/dbm.rb, line 14
    def []=( key, val )
        store( key, val )
    end
delete( key )

[Source]

# File yaml/dbm.rb, line 35
    def delete( key )
        v = super( key )
        if String === v
            v = YAML::load( v )
        end
        v
    end
delete_if() {|k, fetch( k )| ...}

[Source]

# File 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
each()

Alias for each_pair

each_pair() {|k, fetch( k ) }| ...}

[Source]

# File yaml/dbm.rb, line 52
    def each_pair
        keys.each { |k| yield k, fetch( k ) }
        self
    end
each_value() {|YAML::load( v ) }| ...}

[Source]

# File yaml/dbm.rb, line 56
    def each_value
        super { |v| yield YAML::load( v ) }
        self
    end
fetch( keystr, ifnone = nil ) {|keystr| ...}

[Source]

# File 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
has_value?( val )

[Source]

# File yaml/dbm.rb, line 63
    def has_value?( val )
        each_value { |v| return true if v == val }
        return false
    end
index( keystr )

[Source]

# File yaml/dbm.rb, line 29
    def index( keystr )
        super( keystr.to_yaml )
    end
invert()

[Source]

# File yaml/dbm.rb, line 67
    def invert
        h = {}
        keys.each { |k| h[ self.fetch( k ) ] = k }
        h
    end
reject() {|k, v| ...}

[Source]

# File yaml/dbm.rb, line 48
    def reject
        hsh = self.to_hash
        hsh.reject { |k,v| yield k, v }
    end
replace( hsh )

[Source]

# File yaml/dbm.rb, line 72
    def replace( hsh )
        clear
        update( hsh )
    end
select( *keys ) {|k, v| ...}

[Source]

# File 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
shift()

[Source]

# File yaml/dbm.rb, line 76
    def shift
        a = super
        a[1] = YAML::load( a[1] ) if a
        a
    end
store( key, val )

[Source]

# File yaml/dbm.rb, line 88
    def store( key, val )
        super( key, val.to_yaml )
        val
    end
to_a()

[Source]

# File yaml/dbm.rb, line 98
    def to_a
        a = []
        keys.each { |k| a.push [ k, self.fetch( k ) ] }
        a
    end
to_hash()

[Source]

# File yaml/dbm.rb, line 103
    def to_hash
        h = {}
        keys.each { |k| h[ k ] = self.fetch( k ) }
        h
    end
update( hsh )

[Source]

# File yaml/dbm.rb, line 92
    def update( hsh )
        hsh.keys.each do |k|
            self.store( k, hsh.fetch( k ) )
        end
        self
    end
values()

[Source]

# File yaml/dbm.rb, line 60
    def values
        super.collect { |v| YAML::load( v ) }
    end
values_at( *keys )

[Source]

# File yaml/dbm.rb, line 32
    def values_at( *keys )
        keys.collect { |k| fetch( k ) }
    end


Class: YAML::DomainType

Class | YAML::DomainType
In: | 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 )

[Source]

# File yaml/types.rb, line 33
        def initialize( domain, type, val )
            @domain = domain; @type_id = type; @value = val
            @value.taguri = "tag:#{ @domain }:#{ @type_id }"
        end
tag_subclasses?()

[Source]

# File yaml/types.rb, line 30
        def self.tag_subclasses?; false; end

Public Instance methods

to_yaml( opts = {} )

[Source]

# File yaml/types.rb, line 37
        def to_yaml( opts = {} )
            @value.to_yaml( opts )
        end


Class: YAML::Error

Class | YAML::Error
In: | yaml/error.rb
Parent: | StandardError

YAML Error classes


Class: YAML::Loader

Class | YAML::Loader
In: | 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: | yaml/baseemitter.rb
Parent: | Array

Emitter helper classes

Methods

add

Public Instance methods

add( k, v )

[Source]

# File yaml/baseemitter.rb, line 236
        def add( k, v )
            push [k, v]
        end


Class: YAML::Object

Class | YAML::Object
In: | yaml/types.rb
Parent: | Object

Unresolved objects

Methods

tag_subclasses? to_yaml

Public Class methods

tag_subclasses?()

[Source]

# File yaml/types.rb, line 48
        def self.tag_subclasses?; false; end

Public Instance methods

to_yaml( opts = {} )

[Source]

# File 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


Class: YAML::Omap

Class | YAML::Omap
In: | yaml/types.rb
Parent: | ::Array

Builtin collection: !omap

Methods

[] [] []= has_key? is_complex_yaml? to_yaml yaml_initialize

Public Class methods

[]( *vals )

[Source]

# File 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

Public Instance methods

[]( k )

[Source]

# File yaml/types.rb, line 109
        def []( k )
            self.assoc( k ).to_a[1]
        end
[]=( k, *rest )

[Source]

# File 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?( k )

[Source]

# File yaml/types.rb, line 121
        def has_key?( k )
            self.assoc( k ) ? true : false
        end
is_complex_yaml?()

[Source]

# File yaml/types.rb, line 124
        def is_complex_yaml?
            true
        end
to_yaml( opts = {} )

[Source]

# File 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( tag, val )

[Source]

# File 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


Class: YAML::Pairs

Class | YAML::Pairs
In: | yaml/types.rb
Parent: | ::Array

Builtin collection: !pairs

Methods

[] [] []= has_key? is_complex_yaml? to_yaml yaml_initialize

Public Class methods

[]( *vals )

[Source]

# File 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

Public Instance methods

[]( k )

[Source]

# File yaml/types.rb, line 164
        def []( k )
            self.assoc( k ).to_a
        end
[]=( k, val )

[Source]

# File yaml/types.rb, line 167
        def []=( k, val )
            self << [ k, val ]
            val
        end
has_key?( k )

[Source]

# File yaml/types.rb, line 171
        def has_key?( k )
            self.assoc( k ) ? true : false
        end
is_complex_yaml?()

[Source]

# File yaml/types.rb, line 174
        def is_complex_yaml?
            true
        end
to_yaml( opts = {} )

[Source]

# File 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
yaml_initialize( tag, val )

[Source]

# File 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


Class: YAML::ParseError

Class | YAML::ParseError
In: | yaml/error.rb
Parent: | Error


Class: YAML::PrivateType

Class | YAML::PrivateType
In: | 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 )

[Source]

# File yaml/types.rb, line 15
        def initialize( type, val )
            @type_id = type; @value = val
            @value.taguri = "x-private:#{ @type_id }"
        end
tag_subclasses?()

[Source]

# File yaml/types.rb, line 12
        def self.tag_subclasses?; false; end

Public Instance methods

to_yaml( opts = {} )

[Source]

# File yaml/types.rb, line 19
        def to_yaml( opts = {} )
            @value.to_yaml( opts )
        end


Class: YAML::Sequence

Class | YAML::Sequence
In: | yaml/baseemitter.rb
Parent: | Array

Methods

add

Public Instance methods

add( v )

[Source]

# File yaml/baseemitter.rb, line 242
        def add( v )
            push v
        end


Class: YAML::Set

Class | YAML::Set
In: | yaml/types.rb
Parent: | ::Hash

Builtin collection: !set


Class: YAML::SpecialHash

Class | YAML::SpecialHash
In: | 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()

[Source]

# File yaml/types.rb, line 65
        def inspect
            self.default.to_s
        end
to_s()

[Source]

# File yaml/types.rb, line 68
        def to_s
            self.default.to_s
        end
to_yaml( opts = {} )

[Source]

# File yaml/types.rb, line 77
        def to_yaml( opts = {} )
            opts[:DefaultKey] = self.default
            super( opts )
        end
update( h )

[Source]

# File yaml/types.rb, line 71
        def update( h )
            if YAML::SpecialHash === h
                @default = h.default if h.default
            end
            super( h )
        end


Class: YAML::Store

Class | YAML::Store
In: | yaml/store.rb
Parent: | PStore

Methods

dump load load_file new

Public Class methods

new( *o )

[Source]

# File 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

Public Instance methods

dump(table)

[Source]

# File yaml/store.rb, line 18
  def dump(table)
    @table.to_yaml(@opt)
  end
load(content)

[Source]

# File yaml/store.rb, line 22
  def load(content)
    YAML::load(content)
  end
load_file(file)

[Source]

# File yaml/store.rb, line 26
  def load_file(file)
    YAML::load(file)
  end


Class: YAML::Stream

Class | YAML::Stream
In: | 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 = {} )

[Source]

# File yaml/stream.rb, line 10
                def initialize( opts = {} )
                        @options = opts
                        @documents = []
                end

Public Instance methods

[]( i )

[Source]

# File yaml/stream.rb, line 15
        def []( i )
            @documents[ i ]
        end
add( doc )

[Source]

# File yaml/stream.rb, line 19
                def add( doc )
                        @documents << doc
                end
edit( doc_num, doc )

[Source]

# File yaml/stream.rb, line 23
                def edit( doc_num, doc )
                        @documents[ doc_num ] = doc
                end
emit( io = nil )

[Source]

# File 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


Module: YAML::Syck

Module | YAML::Syck
In: | yaml/syck.rb

Classes and Modules

Class YAML::Syck::Node


Class: YAML::Syck::Node

Class | YAML::Syck::Node
In: | yaml/syck.rb
Parent: | Object

Mixin BaseNode functionality

Included Modules

YAML::BaseNode


Class: YAML::TypeError

Class | YAML::TypeError
In: | yaml/error.rb
Parent: | StandardError


Class: YAML::YPath

Class | YAML::YPath
In: | 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 )| ...}

[Source]

# File 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
new( str )

[Source]

# File 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


Class: YAML::YamlNode

Class | YAML::YamlNode
In: | 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 )

[Source]

# File 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

Public Instance methods

transform()

Transform this node fully into a native type

[Source]

# File 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


File: yaml.rb

yaml.rb

Path: | yaml.rb
Last Update: | Sat Oct 15 23:44:28 AUS Eastern Standard Time 2005

-*- mode: ruby; ruby-indent-level: 4; tab-width: 4 -*- vim: sw=4 ts=4 $Id: yaml.rb,v 1.9.2.10 2005/09/20 09:22:01 matz Exp $

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: baseemitter.rb

baseemitter.rb

Path: | yaml/baseemitter.rb
Last Update: | Sat Oct 15 23:44:32 AUS Eastern Standard Time 2005

BaseEmitter

Required files

yaml/constants yaml/encoding yaml/error


File: basenode.rb

basenode.rb

Path: | yaml/basenode.rb
Last Update: | Sat Oct 15 23:44:32 AUS Eastern Standard Time 2005

YAML::BaseNode class

Required files

yaml/ypath


File: constants.rb

constants.rb

Path: | yaml/constants.rb
Last Update: | Wed Jun 11 00:15:27 AUS Eastern Standard Time 2003

Constants used throughout the library


File: dbm.rb

dbm.rb

Path: | yaml/dbm.rb
Last Update: | Fri Jul 25 04:56:09 AUS Eastern Standard Time 2003

Required files

yaml dbm


File: encoding.rb

encoding.rb

Path: | yaml/encoding.rb
Last Update: | Sat Oct 15 23:44:32 AUS Eastern Standard Time 2005

Handle Unicode-to-Internal conversion


File: error.rb

error.rb

Path: | yaml/error.rb
Last Update: | Sat Oct 15 23:44:32 AUS Eastern Standard Time 2005

Error messages and exception class


File: loader.rb

loader.rb

Path: | yaml/loader.rb
Last Update: | Sun May 11 05:55:18 AUS Eastern Standard Time 2003

YAML::Loader class .. type handling ..


File: rubytypes.rb

rubytypes.rb

Path: | yaml/rubytypes.rb
Last Update: | Sat Oct 15 23:44:32 AUS Eastern Standard Time 2005

-*- mode: ruby; ruby-indent-level: 4; tab-width: 4 -*- vim: sw=4 ts=4

Required files

date


File: store.rb

store.rb

Path: | yaml/store.rb
Last Update: | Sat Oct 15 23:44:32 AUS Eastern Standard Time 2005

YAML::Store

Required files

yaml pstore


File: stream.rb

stream.rb

Path: | yaml/stream.rb
Last Update: | Sat Oct 15 23:44:32 AUS Eastern Standard Time 2005


File: stringio.rb

stringio.rb

Path: | yaml/stringio.rb
Last Update: | Sat May 10 07:25:50 AUS Eastern Standard Time 2003

Limited StringIO if no core lib is available

Required files

stringio


File: syck.rb

syck.rb

Path: | yaml/syck.rb
Last Update: | Sat Oct 15 23:44:32 AUS Eastern Standard Time 2005

YAML::Syck module .. glues syck and yaml.rb together ..

Required files

syck yaml/basenode


File: tag.rb

tag.rb

Path: | yaml/tag.rb
Last Update: | Sat Oct 15 23:44:32 AUS Eastern Standard Time 2005

-*- mode: ruby; ruby-indent-level: 4; tab-width: 4 -*- vim: sw=4 ts=4 $Id: tag.rb,v 1.1.2.2 2005/09/27 22:57:53 nobu Exp $

yaml/tag.rb: methods for associating a taguri to a class.

Author: why the lucky stiff


File: types.rb

types.rb

Path: | yaml/types.rb
Last Update: | Sat Oct 15 23:44:32 AUS Eastern Standard Time 2005

-*- mode: ruby; ruby-indent-level: 4 -*- vim: sw=4

Classes required by the full core typeset


File: yamlnode.rb

yamlnode.rb

Path: | yaml/yamlnode.rb
Last Update: | Sat May 10 07:25:50 AUS Eastern Standard Time 2003

YAML::YamlNode class

Required files

yaml/basenode


File: ypath.rb

ypath.rb

Path: | yaml/ypath.rb
Last Update: | Sat May 10 19:43:54 AUS Eastern Standard Time 2003

YAML::YPath


Module: Zlib

Module | Zlib
In: | zlib/zlib.c

The Zlib module contains several classes for compressing and decompressing streams, and for working with "gzip" files.

Classes

Following are the classes that are most likely to be of interest to the user: Zlib::Inflate Zlib::Deflate Zlib::GzipReader Zlib::GzipWriter

There are two important base classes for the classes above: Zlib::ZStream and Zlib::GzipFile. Everything else is an error class.

Constants

Here’s a list.

  Zlib::VERSION
      The Ruby/zlib version string.

  Zlib::ZLIB_VERSION
      The string which represents the version of zlib.h.

  Zlib::BINARY
  Zlib::ASCII
  Zlib::UNKNOWN
      The integers representing data types which Zlib::ZStream#data_type
      method returns.

  Zlib::NO_COMPRESSION
  Zlib::BEST_SPEED
  Zlib::BEST_COMPRESSION
  Zlib::DEFAULT_COMPRESSION
      The integers representing compression levels which are an argument
      for Zlib::Deflate.new, Zlib::Deflate#deflate, and so on.

  Zlib::FILTERED
  Zlib::HUFFMAN_ONLY
  Zlib::DEFAULT_STRATEGY
      The integers representing compression methods which are an argument
      for Zlib::Deflate.new and Zlib::Deflate#params.

  Zlib::DEF_MEM_LEVEL
  Zlib::MAX_MEM_LEVEL
      The integers representing memory levels which are an argument for
      Zlib::Deflate.new, Zlib::Deflate#params, and so on.

  Zlib::MAX_WBITS
      The default value of windowBits which is an argument for
      Zlib::Deflate.new and Zlib::Inflate.new.

  Zlib::NO_FLUSH
  Zlib::SYNC_FLUSH
  Zlib::FULL_FLUSH
  Zlib::FINISH
      The integers to control the output of the deflate stream, which are
      an argument for Zlib::Deflate#deflate and so on.

  Zlib::OS_CODE
  Zlib::OS_MSDOS
  Zlib::OS_AMIGA
  Zlib::OS_VMS
  Zlib::OS_UNIX
  Zlib::OS_VMCMS
  Zlib::OS_ATARI
  Zlib::OS_OS2
  Zlib::OS_MACOS
  Zlib::OS_ZSYSTEM
  Zlib::OS_CPM
  Zlib::OS_TOPS20
  Zlib::OS_WIN32
  Zlib::OS_QDOS
  Zlib::OS_RISCOS
  Zlib::OS_UNKNOWN
      The return values of Zlib::GzipFile#os_code method.

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

Public Instance 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.

[Source]

/*
 * 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);
}
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.

[Source]

/*
 * 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()

Returns the table for calculating CRC checksum as an array.

[Source]

/*
 * 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;
}
zlib_version()

Returns the string which represents the version of zlib library.

[Source]

/*
 * 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;
}


Class: Zlib::BufError

Class | Zlib::BufError
In: | zlib/zlib.c
Parent: | Zlib::Error


Class: Zlib::DataError

Class | Zlib::DataError
In: | zlib/zlib.c
Parent: | Zlib::Error


Class: Zlib::Deflate

Class | Zlib::Deflate
In: | 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?

[Source]

/*
 * 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;
}
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!

[Source]

/*
 * 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;
}

Public Instance methods

<<(p1)

Same as IO.

[Source]

/*
 * 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;
}
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!

[Source]

/*
 * 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;
}
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!

[Source]

/*
 * 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;
}
initialize_copy()

Duplicates the deflate stream.

[Source]

/*
 * 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;
}
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!

[Source]

/*
 * 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) {
    if (RTEST(ruby_debug)) {
        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(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!

[Source]

/*
 * 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;
}


Class: Zlib::Error

Class | Zlib::Error
In: | 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: | 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.

[Source]

/*
 * 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;
    }
}

Public Instance methods

close()

Closes the GzipFile object. This method calls close method of the associated IO object. Returns the associated IO object.

[Source]

/*
 * 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;
}
closed?()

Same as IO.

[Source]

/*
 * 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;
}
comment()

Returns comments recorded in the gzip file header, or nil if the comments is not present.

[Source]

/*
 * 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;
}
crc()

Returns CRC value of the uncompressed data.

[Source]

/*
 * Returns CRC value of the uncompressed data.
 */
static VALUE
rb_gzfile_crc(obj)
    VALUE obj;
{
    return rb_uint2inum(get_gzfile(obj)->crc);
}
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.

[Source]

/*
 * 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;
}
level()

Returns compression level.

[Source]

/*
 * Returns compression level.
 */
static VALUE
rb_gzfile_level(obj)
    VALUE obj;
{
    return INT2FIX(get_gzfile(obj)->level);
}
mtime()

Returns last modification time recorded in the gzip file header.

[Source]

/*
 * 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);
}
orig_name()

Returns original filename recorded in the gzip file header, or nil if original filename is not present.

[Source]

/*
 * 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;
}
os_code()

Returns OS code number recorded in the gzip file header.

[Source]

/*
 * 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);
}
sync()

Same as IO.

[Source]

/*
 * Same as IO.
 */
static VALUE
rb_gzfile_sync(obj)
    VALUE obj;
{
    return (get_gzfile(obj)->z.flags & GZFILE_FLAG_SYNC) ? Qtrue : Qfalse;
}
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.

[Source]

/*
 * 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;
}
to_io()

Same as IO.

[Source]

/*
 * Same as IO.
 */
static VALUE
rb_gzfile_to_io(obj)
    VALUE obj;
{
    return get_gzfile(obj)->io;
}


Class: Zlib::GzipFile::CRCError

Class | Zlib::GzipFile::CRCError
In: | 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: | 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: | 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: | zlib/zlib.c
Parent: | Zlib::GzipFile::Error

Raised when gzip file footer is not found.


Class: Zlib::GzipReader

Class | Zlib::GzipReader
In: | 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.

[Source]

/*
 * 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;
}
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.

[Source]

/*
 * 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");
}

Public Instance methods

each(...)

See Zlib::GzipReader documentation for a description.

[Source]

/*
 * 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_byte()

See Zlib::GzipReader documentation for a description.

[Source]

/*
 * 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;
}
each_line(...)

See Zlib::GzipReader documentation for a description.

[Source]

/*
 * 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;
}
eof()

???

[Source]

/*
 * ???
 */
static VALUE
rb_gzfile_eof_p(obj)
    VALUE obj;
{
    struct gzfile *gz = get_gzfile(obj);
    return GZFILE_IS_FINISHED(gz) ? Qtrue : Qfalse;
}
eof?()

???

[Source]

/*
 * ???
 */
static VALUE
rb_gzfile_eof_p(obj)
    VALUE obj;
{
    struct gzfile *gz = get_gzfile(obj);
    return GZFILE_IS_FINISHED(gz) ? Qtrue : Qfalse;
}
getc()

See Zlib::GzipReader documentation for a description.

[Source]

/*
 * 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;
}
gets(...)

See Zlib::GzipReader documentation for a description.

[Source]

/*
 * 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;
}
lineno()

???

[Source]

/*
 * ???
 */
static VALUE
rb_gzfile_lineno(obj)
    VALUE obj;
{
    return INT2NUM(get_gzfile(obj)->lineno);
}
lineno=(p1)

???

[Source]

/*
 * ???
 */
static VALUE
rb_gzfile_set_lineno(obj, lineno)
    VALUE obj, lineno;
{
    struct gzfile *gz = get_gzfile(obj);
    gz->lineno = NUM2INT(lineno);
    return lineno;
}
pos()

???

[Source]

/*
 * ???
 */
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);
}
read(...)

See Zlib::GzipReader documentation for a description.

[Source]

/*
 * 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);
}
readchar()

See Zlib::GzipReader documentation for a description.

[Source]

/*
 * 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;
}
readline(...)

See Zlib::GzipReader documentation for a description.

[Source]

/*
 * 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;
}
readlines(...)

See Zlib::GzipReader documentation for a description.

[Source]

/*
 * 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;
}
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.

[Source]

/*
 * 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);
}
tell()

???

[Source]

/*
 * ???
 */
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);
}
ungetc(p1)

See Zlib::GzipReader documentation for a description.

[Source]

/*
 * 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;
}
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.

[Source]

/*
 * 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);
}


Class: Zlib::GzipWriter

Class | Zlib::GzipWriter
In: | 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.

[Source]

/*
 * 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;
}
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.

[Source]

/*
 * 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");
}

Public Instance methods

<<(p1)

Same as IO.

comment=(p1)

???

[Source]

/*
 * ???
 */
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;
}
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.

[Source]

/*
 * 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;
}
mtime=(p1)

???

[Source]

/*
 * ???
 */
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=(p1)

???

[Source]

/*
 * ???
 */
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;
}
pos()

???

[Source]

/*
 * ???
 */
static VALUE
rb_gzfile_total_in(obj)
    VALUE obj;
{
    return rb_uint2inum(get_gzfile(obj)->z.stream.total_in);
}
print(...)

Same as IO.

printf(...)

Same as IO.

putc(p1)

Same as IO.

[Source]

/*
 * 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;
}
puts(...)

Same as IO.

tell()

???

[Source]

/*
 * ???
 */
static VALUE
rb_gzfile_total_in(obj)
    VALUE obj;
{
    return rb_uint2inum(get_gzfile(obj)->z.stream.total_in);
}
write(p1)

Same as IO.

[Source]

/*
 * 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);
}


Class: Zlib::Inflate

Class | Zlib::Inflate
In: | 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

[Source]

/*
 * 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;
}
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!

[Source]

/*
 * 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;
}

Public Instance methods

<<(p1)

Same as IO.

[Source]

/*
 * 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;
}
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!

[Source]

/*
 * 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;
}
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!

[Source]

/*
 * 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;
}
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.

[Source]

/*
 * 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?()

Quoted verbatim from original documentation:

  What is this?

:)

[Source]

/*
 * 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;
}


Class: Zlib::MemError

Class | Zlib::MemError
In: | zlib/zlib.c
Parent: | Zlib::Error


Class: Zlib::NeedDict

Class | Zlib::NeedDict
In: | zlib/zlib.c
Parent: | Zlib::Error


Class: Zlib::StreamEnd

Class | Zlib::StreamEnd
In: | zlib/zlib.c
Parent: | Zlib::Error


Class: Zlib::StreamError

Class | Zlib::StreamError
In: | zlib/zlib.c
Parent: | Zlib::Error


Class: Zlib::VersionError

Class | Zlib::VersionError
In: | zlib/zlib.c
Parent: | Zlib::Error


Class: Zlib::ZStream

Class | Zlib::ZStream
In: | 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.

[Source]

/*
 * Returns the adler-32 checksum.
 */
static VALUE
rb_zstream_adler(obj)
    VALUE obj;
{
    return rb_uint2inum(get_zstream(obj)->stream.adler);
}
avail_in()

Returns bytes of data in the input buffer. Normally, returns 0.

[Source]

/*
 * 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));
}
avail_out()

Returns number of bytes of free spaces in output buffer. Because the free space is allocated automatically, this method returns 0 normally.

[Source]

/*
 * 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=(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.

[Source]

/*
 * 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;
}
close()

Closes the stream. All operations on the closed stream will raise an exception.

[Source]

/*
 * 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;
}
closed?()

Returns true if the stream is closed.

[Source]

/*
 * 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;
}
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.

[Source]

/*
 * 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);
}
end()

Closes the stream. All operations on the closed stream will raise an exception.

[Source]

/*
 * 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;
}
ended?()

Returns true if the stream is closed.

[Source]

/*
 * 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;
}
finish()

Finishes the stream and flushes output buffer. See Zlib::Deflate#finish and Zlib::Inflate#finish for details of this behavior.

[Source]

/*
 * 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;
}
finished?()

Returns true if the stream is finished.

[Source]

/*
 * 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;
}
flush_next_in()

Flushes input buffer and returns all data in that buffer.

[Source]

/*
 * 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()

Flushes output buffer and returns all data in that buffer.

[Source]

/*
 * 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;
}
reset()

Resets and initializes the stream. All data in both input and output buffer are discarded.

[Source]

/*
 * 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;
}
stream_end?()

Returns true if the stream is finished.

[Source]

/*
 * 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;
}
total_in()

Returns the total bytes of the input data to the stream. FIXME

[Source]

/*
 * 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()

Returns the total bytes of the output data from the stream. FIXME

[Source]

/*
 * 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);
}


File: zlib.c

zlib.c

Path: | zlib/zlib.c
Last Update: | Sat Oct 15 23:44:27 AUS Eastern Standard Time 2005