diff options
Diffstat (limited to 'lib')
268 files changed, 3565 insertions, 3565 deletions
diff --git a/lib/English.rb b/lib/English.rb index 1a0e11de74..4fd53c5ec6 100644 --- a/lib/English.rb +++ b/lib/English.rb @@ -11,7 +11,7 @@ # With English: # # require "English" -# +# # $OUTPUT_FIELD_SEPARATOR = ' -- ' # "waterbuffalo" =~ /buff/ # print $LOADED_FEATURES, $POSTMATCH, $PID, "\n" @@ -83,7 +83,7 @@ alias $DEFAULT_OUTPUT $> # of the contents of all the files # given as command-line arguments, or <tt>$stdin</tt> # (in the case where there are no -# arguments). <tt>$<</tt> supports methods similar to a +# arguments). <tt>$<</tt> supports methods similar to a # +File+ object: # +inmode+, +close+, # <tt>closed?</tt>, +each+, @@ -91,7 +91,7 @@ alias $DEFAULT_OUTPUT $> # +eof+, <tt>eof?</tt>, +file+, # +filename+, +fileno+, # +getc+, +gets+, +lineno+, -# <tt>lineno=</tt>, +path+, +# <tt>lineno=</tt>, +path+, # +pos+, <tt>pos=</tt>, # +read+, +readchar+, # +readline+, +readlines+, @@ -139,12 +139,12 @@ alias $ARGV $* alias $MATCH $& # The string preceding the match in the last -# successful pattern match. This variable is local to +# successful pattern match. This variable is local to # the current scope. Read only. Thread local. alias $PREMATCH $` # The string following the match in the last -# successful pattern match. This variable is local to +# successful pattern match. This variable is local to # the current scope. Read only. Thread local. alias $POSTMATCH $' diff --git a/lib/base64.rb b/lib/base64.rb index ebd796eccd..383acacef9 100644 --- a/lib/base64.rb +++ b/lib/base64.rb @@ -8,12 +8,12 @@ # # == Example # -# A simple encoding and decoding. -# +# A simple encoding and decoding. +# # require "base64" # # enc = Base64.encode64('Send reinforcements') -# # -> "U2VuZCByZWluZm9yY2VtZW50cw==\n" +# # -> "U2VuZCByZWluZm9yY2VtZW50cw==\n" # plain = Base64.decode64(enc) # # -> "Send reinforcements" # diff --git a/lib/benchmark.rb b/lib/benchmark.rb index 380c364398..9a0bbef596 100644 --- a/lib/benchmark.rb +++ b/lib/benchmark.rb @@ -1,13 +1,13 @@ =begin # -# benchmark.rb - a performance benchmarking library -# +# benchmark.rb - a performance benchmarking library +# # $Id$ -# -# Created by Gotoken ([email protected]). +# +# Created by Gotoken ([email protected]). # # Documentation by Gotoken (original RD), Lyle Johnson (RDoc conversion), and -# Gavin Sinclair (editing). +# Gavin Sinclair (editing). # =end @@ -26,15 +26,15 @@ # 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' @@ -45,7 +45,7 @@ # x.report { n.times do ; a = "1"; end } # x.report { 1.upto(n) do ; a = "1"; end } # end -# +# # The result: # # user system total real @@ -63,14 +63,14 @@ # 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 @@ -79,21 +79,21 @@ # 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) @@ -103,7 +103,7 @@ # using the #benchmark method: # # require 'benchmark' -# include Benchmark # we need the CAPTION and FMTSTR constants +# include Benchmark # we need the CAPTION and FMTSTR constants # # n = 50000 # Benchmark.benchmark(" "*7 + CAPTION, 7, FMTSTR, ">total:", ">avg:") do |x| @@ -112,9 +112,9 @@ # 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) @@ -145,10 +145,10 @@ module Benchmark # suitable for nearly all benchmarking requirements. See the examples in # Benchmark, and the #bm and #bmbm methods. # - # Example: + # Example: # # require 'benchmark' - # include Benchmark # we need the CAPTION and FMTSTR constants + # include Benchmark # we need the CAPTION and FMTSTR constants # # n = 50000 # Benchmark.benchmark(" "*7 + CAPTION, 7, FMTSTR, ">total:", ">avg:") do |x| @@ -157,16 +157,16 @@ module Benchmark # tu = x.report("upto:") { 1.upto(n) do ; a = "1"; end } # [tf+tt+tu, (tf+tt+tu)/3] # end - # + # # <i>Generates:</i> - # + # # 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) - # + # def benchmark(caption = "", label_width = nil, fmtstr = nil, *labels) # :yield: report sync = STDOUT.sync @@ -177,7 +177,7 @@ module Benchmark 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), + print((labels.shift || t.label || "").ljust(label_width), t.format(fmtstr)) } STDOUT.sync = sync @@ -186,7 +186,7 @@ module Benchmark # 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 @@ -195,9 +195,9 @@ module Benchmark # x.report("times:") { n.times do ; a = "1"; end } # x.report("upto:") { 1.upto(n) do ; a = "1"; end } # end - # + # # <i>Generates:</i> - # + # # user system total real # for: 1.050000 0.000000 1.050000 ( 0.503462) # times: 1.533333 0.016667 1.550000 ( 0.735473) @@ -224,21 +224,21 @@ module Benchmark # 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 - # + # # <i>Generates:</i> - # + # # 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) @@ -267,7 +267,7 @@ module Benchmark ets = sum.format("total: %tsec") printf("%s %s\n\n", "-"*(width+CAPTION.length-ets.length-1), ets) - + # take print ' '*width, CAPTION list = [] @@ -285,7 +285,7 @@ module Benchmark ary end - # + # # Returns the time used to execute the given block as a # Benchmark::Tms object. # @@ -293,10 +293,10 @@ module Benchmark 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, + 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 @@ -323,8 +323,8 @@ module Benchmark # Usually, one doesn't call this method directly, as new # Job objects are created by the #bmbm method. # _width_ is a initial value for the label offset used in formatting; - # the #bmbm method passes its _width_ argument to this constructor. - # + # the #bmbm method passes its _width_ argument to this constructor. + # def initialize(width) @width = width @list = [] @@ -343,11 +343,11 @@ module Benchmark end alias report item - + # An array of 2-element arrays, consisting of label and block pairs. attr_reader :list - - # Length of the widest label in the #list, plus one. + + # Length of the widest label in the #list, plus one. attr_reader :width end @@ -363,10 +363,10 @@ module Benchmark # # Returns an initialized Report instance. # Usually, one doesn't call this method directly, as new - # Report objects are created by the #benchmark and #bm methods. - # _width_ and _fmtstr_ are the label offset and - # format string used by Tms#format. - # + # Report objects are created by the #benchmark and #bm methods. + # _width_ and _fmtstr_ are the label offset and + # format string used by Tms#format. + # def initialize(width = 0, fmtstr = nil) @width, @fmtstr = width, fmtstr end @@ -398,50 +398,50 @@ module Benchmark # User CPU time attr_reader :utime - + # System CPU time attr_reader :stime - + # User CPU time of children attr_reader :cutime - + # System CPU time of children attr_reader :cstime - + # Elapsed real time attr_reader :real - - # Total time, that is _utime_ + _stime_ + _cutime_ + _cstime_ + + # Total time, that is _utime_ + _stime_ + _cutime_ + _cstime_ attr_reader :total - + # Label attr_reader :label # # Returns an initialized Tms object which has - # _u_ as the user CPU time, _s_ as the system CPU time, + # _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. - # + # as the label. + # 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 - # + # # 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_). - # + # def add(&blk) # :yield: - self + Benchmark::measure(&blk) + self + Benchmark::measure(&blk) end - # + # # An in-place version of #add. - # + # def add! - t = Benchmark::measure(&blk) + t = Benchmark::measure(&blk) @utime = utime + t.utime @stime = stime + t.stime @cutime = cutime + t.cutime @@ -450,32 +450,32 @@ module Benchmark self end - # + # # 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. - # + # This method and #/() are useful for taking statistics. + # def +(other); memberwise(:+, other) end - + # # Returns a new Tms object obtained by memberwise subtraction # of the individual times for the other Tms object from those of this # Tms object. # def -(other); memberwise(:-, other) end - + # # Returns a new Tms object obtained by memberwise multiplication # of the individual times for this Tms object by _x_. # def *(x); memberwise(:*, x) end - # + # # 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. - # + # This method and #+() are useful for taking statistics. + # def /(x); memberwise(:/, x) end # @@ -486,15 +486,15 @@ module Benchmark # # <tt>%u</tt>:: Replaced by the user CPU time, as reported by Tms#utime. # <tt>%y</tt>:: Replaced by the system CPU time, as reported by #stime (Mnemonic: y of "s*y*stem") - # <tt>%U</tt>:: Replaced by the children's user CPU time, as reported by Tms#cutime + # <tt>%U</tt>:: Replaced by the children's user CPU time, as reported by Tms#cutime # <tt>%Y</tt>:: Replaced by the children's system CPU time, as reported by Tms#cstime # <tt>%t</tt>:: Replaced by the total CPU time, as reported by Tms#total # <tt>%r</tt>:: Replaced by the elapsed real time, as reported by Tms#real # <tt>%n</tt>:: 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. - # + # def format(arg0 = nil, *args) fmtstr = (arg0 || FMTSTR).dup fmtstr.gsub!(/(%[-+\.\d]*)n/){"#{$1}s" % label} @@ -507,19 +507,19 @@ module Benchmark arg0 ? Kernel::format(fmtstr, *args) : fmtstr end - # + # # Same as #format. - # + # def to_s format end - # + # # 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. - # + # def to_a [@label, @utime, @stime, @cutime, @cstime, @real] end @@ -548,7 +548,7 @@ module Benchmark # The default caption string (heading above the output times). CAPTION = Benchmark::Tms::CAPTION - # The default format string used to display times. See also Benchmark::Tms#format. + # The default format string used to display times. See also Benchmark::Tms#format. FMTSTR = Benchmark::Tms::FMTSTR end diff --git a/lib/cgi.rb b/lib/cgi.rb index 6acf05b382..6355a92804 100644 --- a/lib/cgi.rb +++ b/lib/cgi.rb @@ -1,14 +1,14 @@ -# +# # cgi.rb - cgi support library -# +# # Copyright (C) 2000 Network Applied Communication Laboratory, Inc. -# +# # Copyright (C) 2000 Information-technology Promotion Agency, Japan # # Author: Wakou Aoyama <[email protected]> # -# Documentation: Wakou Aoyama (RDoc'd and embellished by William Webber) -# +# Documentation: Wakou Aoyama (RDoc'd and embellished by William Webber) +# # == Overview # # The Common Gateway Interface (CGI) is a simple protocol @@ -18,7 +18,7 @@ # 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 @@ -75,18 +75,18 @@ raise "Please, use ruby 1.9.0 or later." if RUBY_VERSION < "1.9.0" # # # For each of these variables, there is a corresponding attribute with the -# same name, except all lower case and without a preceding HTTP_. +# 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 +# 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 +# For instance, suppose the request contains the parameter # "favourite_colours" with the multiple values "blue" and "green". The # following behaviour would occur: # @@ -105,7 +105,7 @@ raise "Please, use ruby 1.9.0 or later." if RUBY_VERSION < "1.9.0" # # === Multipart requests # -# If a request's method is POST and its content type is multipart/form-data, +# 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 @@ -136,7 +136,7 @@ raise "Please, use ruby 1.9.0 or later." if RUBY_VERSION < "1.9.0" # # 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 +# 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 @@ -150,57 +150,57 @@ raise "Please, use ruby 1.9.0 or later." if RUBY_VERSION < "1.9.0" # 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 +# +# 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' @@ -208,37 +208,37 @@ raise "Please, use ruby 1.9.0 or later." if RUBY_VERSION < "1.9.0" # 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 @@ -262,7 +262,7 @@ raise "Please, use ruby 1.9.0 or later." if RUBY_VERSION < "1.9.0" # end # end # end -# +# # # add HTML generation methods # CGI.new("html3") # html3.2 # CGI.new("html4") # html4.01 (Strict) diff --git a/lib/cgi/cookie.rb b/lib/cgi/cookie.rb index befe1402e6..5c2cd62a27 100644 --- a/lib/cgi/cookie.rb +++ b/lib/cgi/cookie.rb @@ -15,16 +15,16 @@ # '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' @@ -48,7 +48,7 @@ class CGI # 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 + # false). Secure cookies are only transmitted to HTTPS # servers. # # These keywords correspond to attributes of the cookie object. diff --git a/lib/cgi/core.rb b/lib/cgi/core.rb index 95cf423d83..69c7f28603 100644 --- a/lib/cgi/core.rb +++ b/lib/cgi/core.rb @@ -13,7 +13,7 @@ class CGI REVISION = '$Id$' #:nodoc: - NEEDS_BINMODE = true if /WIN/i.match(RUBY_PLATFORM) + NEEDS_BINMODE = true if /WIN/i.match(RUBY_PLATFORM) # Path separators in different environments. PATH_SEPARATOR = {'UNIX'=>'/', 'WINDOWS'=>'\\', 'MACINTOSH'=>':'} @@ -48,7 +48,7 @@ class CGI # :startdoc: - def env_table + def env_table ENV end @@ -79,7 +79,7 @@ class CGI # 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 + # 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. @@ -89,19 +89,19 @@ class CGI # 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 + # 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", @@ -116,9 +116,9 @@ class CGI # "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" @@ -137,8 +137,8 @@ class CGI # "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. + # + # This method does not perform charset conversion. def header(options='text/html') if options.is_a?(String) content_type = options @@ -277,13 +277,13 @@ class CGI # # 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'], @@ -296,16 +296,16 @@ class CGI # "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 + # the content is converted to this charset, and the language is set # to "ja". def out(options = "text/html") # :yield: @@ -358,7 +358,7 @@ class CGI # Mixin module. It provides the follow functionality groups: # - # 1. Access to CGI environment variables as methods. See + # 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. @@ -617,7 +617,7 @@ class CGI # Get the value for the parameter with a given key. # - # If the parameter has multiple values, only the first will be + # If the parameter has multiple values, only the first will be # retrieved; use #params() to get the array of values. def [](key) params = @params[key] @@ -658,7 +658,7 @@ class CGI # This default value default is "UTF-8" # If you want to change the default accept character set # when create a new CGI instance, set this: - # + # # CGI.accept_charset = "EUC-JP" # @@ -700,11 +700,11 @@ class CGI # # == block # - # When you use a block, you can write a process + # When you use a block, you can write a process # that query encoding is invalid. Example: # # encoding_error={} - # cgi=CGI.new(:accept_charset=>"EUC-JP") do |name,value| + # cgi=CGI.new(:accept_charset=>"EUC-JP") do |name,value| # encoding_error[key] = value # end # diff --git a/lib/cgi/html.rb b/lib/cgi/html.rb index 62f1fc1898..8ee38000c5 100644 --- a/lib/cgi/html.rb +++ b/lib/cgi/html.rb @@ -66,7 +66,7 @@ class CGI # Modules Http3, Http4, etc., contain more basic HTML-generation methods # (:title, :center, etc.). # - # See class CGI for a detailed example. + # See class CGI for a detailed example. # module HtmlExtension @@ -99,7 +99,7 @@ class CGI end end - # Generate a Document Base URI element as a String. + # 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. @@ -179,10 +179,10 @@ class CGI # # checkbox("name") # # = checkbox("NAME" => "name") - # + # # checkbox("name", "value") # # = checkbox("NAME" => "name", "VALUE" => "value") - # + # # checkbox("name", "value", true) # # = checkbox("NAME" => "name", "VALUE" => "value", "CHECKED" => true) def checkbox(name = "", value = nil, checked = nil) @@ -220,23 +220,23 @@ class CGI # # <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"]) def checkbox_group(name = "", *values) @@ -272,13 +272,13 @@ class CGI # # 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"> def file_field(name = "", size = 20, maxlength = nil) @@ -298,7 +298,7 @@ class CGI # # +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". + # defaults to "application/x-www-form-urlencoded". # # Alternatively, the attributes can be specified as a hash. # @@ -306,19 +306,19 @@ class CGI # # 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> 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 } + "ENCTYPE" => enctype } else unless method.has_key?("METHOD") method["METHOD"] = "post" @@ -350,10 +350,10 @@ class CGI # # 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"> def hidden(name = "", value = nil) @@ -376,36 +376,36 @@ class CGI # 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" } # def html(attributes = {}) # :yield: @@ -444,17 +444,17 @@ class CGI # Generate an Image Button Input element as a string. # - # +src+ is the URL of the image to use for the button. +name+ + # +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"> def image_button(src = "", name = nil, alt = nil) @@ -480,7 +480,7 @@ class CGI # # 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"> def img(src = "", alt = "", width = nil, height = nil) @@ -506,15 +506,15 @@ class CGI # # 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> def multipart_form(action = nil, enctype = "multipart/form-data") attributes = if action == nil - { "METHOD" => "post", "ENCTYPE" => enctype } + { "METHOD" => "post", "ENCTYPE" => enctype } elsif action.kind_of?(String) { "METHOD" => "post", "ACTION" => action, - "ENCTYPE" => enctype } + "ENCTYPE" => enctype } else unless action.has_key?("METHOD") action["METHOD"] = "post" @@ -542,13 +542,13 @@ class CGI # # 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"> def password_field(name = "", value = nil, size = 40, maxlength = nil) @@ -584,21 +584,21 @@ class CGI # # <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"> @@ -649,10 +649,10 @@ class CGI # # 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"> def radio_button(name = "", value = nil, checked = nil) @@ -670,28 +670,28 @@ class CGI # # 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"]) def radio_group(name = "", *values) @@ -723,10 +723,10 @@ class CGI # # reset # # <INPUT TYPE="reset"> - # + # # reset("reset") # # <INPUT TYPE="reset" VALUE="reset"> - # + # # reset("VALUE" => "reset", "ID" => "foo") # # <INPUT TYPE="reset" VALUE="reset" ID="foo"> def reset(value = nil, name = nil) @@ -750,13 +750,13 @@ class CGI # # 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"> def submit(value = nil, name = nil) @@ -779,16 +779,16 @@ class CGI # # 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"> def text_field(name = "", value = nil, size = 40, maxlength = nil) diff --git a/lib/cgi/session.rb b/lib/cgi/session.rb index 2b5aa846d9..65d6442b37 100644 --- a/lib/cgi/session.rb +++ b/lib/cgi/session.rb @@ -13,7 +13,7 @@ # # 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. +# 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 @@ -28,7 +28,7 @@ require 'tmpdir' class CGI - # Class representing an HTTP session. See documentation for the file + # Class representing an HTTP session. See documentation for the file # cgi/session.rb for an introduction to HTTP sessions. # # == Lifecycle @@ -47,7 +47,7 @@ class CGI # == 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 + # 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). # @@ -60,21 +60,21 @@ class CGI # # == Storing session state # - # The caller can specify what form of storage to use for the session's + # 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 + # 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 + # 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, + # 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 + # Custom storage types can also be created by defining a class with # the following methods: # # new(session, options) @@ -99,14 +99,14 @@ class CGI # 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 + # 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. @@ -124,10 +124,10 @@ class CGI # 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 + # '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 + # # coerce to String: cgi[] returns the # # string-like CGI::QueryExtension::Value # session['user_name'] = cgi['user_name'].to_s # elsif !session['user_name'] @@ -143,11 +143,11 @@ class CGI # 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 + # # 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 + # 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) @@ -172,7 +172,7 @@ class CGI # The session id is an MD5 hash based upon the time, # a random number, and a constant string. This routine # is used internally for automatically generated - # session ids. + # session ids. def create_new_id require 'securerandom' begin @@ -205,7 +205,7 @@ class CGI # 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, + # 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+ @@ -220,7 +220,7 @@ class CGI # 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 + # 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. @@ -232,10 +232,10 @@ class CGI # +option+ is also passed on to the session storage class initializer; 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. + # to add hidden input elements to forms. # # *WARNING* the +output_hidden+ # fields are surrounded by a <fieldset> tag in HTML 4 generation, which @@ -294,7 +294,7 @@ class CGI "expires" => option['session_expires'], "domain" => option['session_domain'], "secure" => option['session_secure'], - "path" => + "path" => if option['session_path'] option['session_path'] elsif ENV["SCRIPT_NAME"] @@ -323,11 +323,11 @@ class CGI # Store session data on the server. For some session storage types, # this is a no-op. - def update + def update @dbman.update end - # Store session data on the server and close the session storage. + # Store session data on the server and close the session storage. # For some session storage types, this is a no-op. def close @dbman.close @@ -359,7 +359,7 @@ class CGI # created. The session id must only contain alphanumeric # characters; automatically generated session ids observe # this requirement. - # + # # +option+ is a hash of options for the initializer. The # following options are recognised: # @@ -450,7 +450,7 @@ class CGI # 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 + # data will only persist for as long as the ruby interpreter # instance does. class MemoryStore GLOBAL_HASH_TABLE = {} #:nodoc: diff --git a/lib/cgi/session/pstore.rb b/lib/cgi/session/pstore.rb index 3cd3e46000..a63d7d3984 100644 --- a/lib/cgi/session/pstore.rb +++ b/lib/cgi/session/pstore.rb @@ -2,7 +2,7 @@ # cgi/session/pstore.rb - persistent storage of marshalled session data # # Documentation: William Webber ([email protected]) -# +# # == Overview # # This file provides the CGI::Session::PStore class, which builds @@ -29,7 +29,7 @@ class CGI # created. The session id must only contain alphanumeric # characters; automatically generated session ids observe # this requirement. - # + # # +option+ is a hash of options for the initializer. The # following options are recognised: # @@ -77,7 +77,7 @@ class CGI end # Save session state to the session's PStore file. - def update + def update @p.transaction do @p['hash'] = @hash end diff --git a/lib/cgi/util.rb b/lib/cgi/util.rb index 991b68ce73..b7b0233b4d 100644 --- a/lib/cgi/util.rb +++ b/lib/cgi/util.rb @@ -119,7 +119,7 @@ class CGI # print CGI::unescapeElement( # CGI::escapeHTML('<BR><A HREF="url"></A>'), "A", "IMG") # # "<BR><A HREF="url"></A>" - # + # # print CGI::unescapeElement( # CGI::escapeHTML('<BR><A HREF="url"></A>'), ["A", "IMG"]) # # "<BR><A HREF="url"></A>" @@ -161,7 +161,7 @@ class CGI # # <BODY> # # </BODY> # # </HTML> - # + # # print CGI::pretty("<HTML><BODY></BODY></HTML>", "\t") # # <HTML> # # <BODY> diff --git a/lib/csv.rb b/lib/csv.rb index 8adc2973b9..a5f670c059 100644 --- a/lib/csv.rb +++ b/lib/csv.rb @@ -5,38 +5,38 @@ # Created by James Edward Gray II on 2005-10-31. # Copyright 2005 James Edward Gray II. You can redistribute or modify this code # under the terms of Ruby's license. -# +# # See CSV for documentation. -# +# # == Description -# +# # Welcome to the new and improved CSV. -# +# # This version of the CSV library began its life as FasterCSV. FasterCSV was # intended as a replacement to Ruby's then standard CSV library. It was # designed to address concerns users of that library had and it had three # primary goals: -# +# # 1. Be significantly faster than CSV while remaining a pure Ruby library. # 2. Use a smaller and easier to maintain code base. (FasterCSV eventually # grew larger, was also but considerably richer in features. The parsing # core remains quite small.) # 3. Improve on the CSV interface. -# +# # Obviously, the last one is subjective. I did try to defer to the original # interface whenever I didn't have a compelling reason to change it though, so # hopefully this won't be too radically different. -# +# # We must have met our goals because FasterCSV was renamed to CSV and replaced # the original library. -# +# # == What's Different From the Old CSV? -# +# # I'm sure I'll miss something, but I'll try to mention most of the major # differences I am aware of, to help others quickly get up to speed: -# +# # === CSV Parsing -# +# # * This parser is m17n aware. See CSV for full details. # * This library has a stricter parser and will throw MalformedCSVErrors on # problematic data. @@ -46,9 +46,9 @@ # * The old library returned empty lines as <tt>[nil]</tt>. This library calls # them <tt>[]</tt>. # * This library has a much faster parser. -# +# # === Interface -# +# # * CSV now uses Hash-style parameters to set options. # * CSV no longer has generate_row() or parse_row(). # * The old CSV's Reader and Writer classes have been dropped. @@ -60,33 +60,33 @@ # * CSV no longer supports partial reads. It works line-by-line. # * CSV no longer allows the instance methods to override the separators for # performance reasons. They must be set in the constructor. -# +# # If you use this library and find yourself missing any functionality I have # trimmed, please {let me know}[mailto:[email protected]]. -# +# # == Documentation -# +# # See CSV for documentation. -# +# # == What is CSV, really? -# +# # CSV maintains a pretty strict definition of CSV taken directly from # {the RFC}[http://www.ietf.org/rfc/rfc4180.txt]. I relax the rules in only one # place and that is to make using this library easier. CSV will parse all valid # CSV. -# +# # What you don't want to do is feed CSV invalid data. Because of the way the # CSV format works, it's common for a parser to need to read until the end of # the file to be sure a field is invalid. This eats a lot of time and memory. -# +# # Luckily, when working with invalid CSV, Ruby's built-in methods will almost # always be superior in every way. For example, parsing non-quoted fields is as # easy as: -# +# # data.split(",") -# +# # == Questions and/or Comments -# +# # Feel free to email {James Edward Gray II}[mailto:[email protected]] # with any questions. @@ -95,139 +95,139 @@ require "English" require "date" require "stringio" -# +# # This class provides a complete interface to CSV files and data. It offers # tools to enable you to read and write to and from Strings or IO objects, as # needed. -# +# # == Reading -# +# # === From a File -# +# # ==== A Line at a Time -# +# # CSV.foreach("path/to/file.csv") do |row| # # use row here... # end -# +# # ==== All at Once -# +# # arr_of_arrs = CSV.read("path/to/file.csv") -# +# # === From a String -# +# # ==== A Line at a Time -# +# # CSV.parse("CSV,data,String") do |row| # # use row here... # end -# +# # ==== All at Once -# +# # arr_of_arrs = CSV.parse("CSV,data,String") -# +# # == Writing -# +# # === To a File -# +# # CSV.open("path/to/file.csv", "wb") do |csv| # csv << ["row", "of", "CSV", "data"] # csv << ["another", "row"] # # ... # end -# +# # === To a String -# +# # csv_string = CSV.generate do |csv| # csv << ["row", "of", "CSV", "data"] # csv << ["another", "row"] # # ... # end -# +# # == Convert a Single Line -# +# # csv_string = ["CSV", "data"].to_csv # to CSV # csv_array = "CSV,String".parse_csv # from CSV -# +# # == Shortcut Interface -# +# # CSV { |csv_out| csv_out << %w{my data here} } # to $stdout # CSV(csv = "") { |csv_str| csv_str << %w{my data here} } # to a String # CSV($stderr) { |csv_err| csv_err << %w{my data here} } # to $stderr -# +# # == CSV and Character Encodings (M17n or Multilingualization) -# +# # This new CSV parser is m17n savvy. The parser works in the Encoding of the IO # or String object being read from or written to. Your data is never transcoded # (unless you ask Ruby to transcode it for you) and will literally be parsed in # the Encoding it is in. Thus CSV will return Arrays or Rows of Strings in the # Encoding of your data. This is accomplished by transcoding the parser itself # into your Encoding. -# +# # Some transcoding must take place, of course, to accomplish this multiencoding # support. For example, <tt>:col_sep</tt>, <tt>:row_sep</tt>, and # <tt>:quote_char</tt> must be transcoded to match your data. Hopefully this # makes the entire process feel transparent, since CSV's defaults should just # magically work for you data. However, you can set these values manually in # the target Encoding to avoid the translation. -# +# # It's also important to note that while all of CSV's core parser is now # Encoding agnostic, some features are not. For example, the built-in # converters will try to transcode data to UTF-8 before making conversions. # Again, you can provide custom converters that are aware of your Encodings to # avoid this translation. It's just too hard for me to support native # conversions in all of Ruby's Encodings. -# +# # Anyway, the practical side of this is simple: make sure IO and String objects # passed into CSV have the proper Encoding set and everything should just work. # CSV methods that allow you to open IO objects (CSV::foreach(), CSV::open(), # CSV::read(), and CSV::readlines()) do allow you to specify the Encoding. -# +# # One minor exception comes when generating CSV into a String with an Encoding # that is not ASCII compatible. There's no existing data for CSV to use to # prepare itself and thus you will probably need to manually specify the desired # Encoding for most of those cases. It will try to guess using the fields in a # row of output though, when using CSV::generate_line() or Array#to_csv(). -# +# # I try to point out any other Encoding issues in the documentation of methods # as they come up. -# +# # This has been tested to the best of my ability with all non-"dummy" Encodings # Ruby ships with. However, it is brave new code and may have some bugs. # Please feel free to {report}[mailto:[email protected]] any issues you # find with it. -# +# class CSV # The version of the installed library. VERSION = "2.4.5".freeze - - # + + # # A CSV::Row is part Array and part Hash. It retains an order for the fields # and allows duplicates just as an Array would, but also allows you to access # fields by name just as you could if they were in a Hash. - # + # # All rows returned by CSV will be constructed from this class, if header row # processing is activated. - # + # class Row - # + # # Construct a new CSV::Row from +headers+ and +fields+, which are expected # to be Arrays. If one Array is shorter than the other, it will be padded # with +nil+ objects. - # + # # The optional +header_row+ parameter can be set to +true+ to indicate, via # CSV::Row.header_row?() and CSV::Row.field_row?(), that this is a header # row. Otherwise, the row is assumes to be a field row. - # + # # A CSV::Row object supports the following Array methods through delegation: - # + # # * empty?() # * length() # * size() - # + # def initialize(headers, fields, header_row = false) @header_row = header_row - + # handle extra headers or fields @row = if headers.size > fields.size headers.zip(fields) @@ -235,7 +235,7 @@ class CSV fields.zip(headers).map { |pair| pair.reverse } end end - + # Internal data format used to compare equality. attr_reader :row protected :row @@ -244,35 +244,35 @@ class CSV extend Forwardable def_delegators :@row, :empty?, :length, :size - + # Returns +true+ if this is a header row. def header_row? @header_row end - + # Returns +true+ if this is a field row. def field_row? not header_row? end - + # Returns the headers of this row. def headers @row.map { |pair| pair.first } end - - # + + # # :call-seq: # field( header ) # field( header, offset ) # field( index ) - # + # # This method will fetch the field value by +header+ or +index+. If a field # is not found, +nil+ is returned. - # + # # When provided, +offset+ ensures that a header match occurrs on or later - # than the +offset+ index. You can use this to find duplicate headers, + # than the +offset+ index. You can use this to find duplicate headers, # without resorting to hard-coding exact indices. - # + # def field(header_or_index, minimum_index = 0) # locate the pair finder = header_or_index.is_a?(Integer) ? :[] : :assoc @@ -282,23 +282,23 @@ class CSV pair.nil? ? nil : pair.last end alias_method :[], :field - - # + + # # :call-seq: # []=( header, value ) # []=( header, offset, value ) # []=( index, value ) - # + # # Looks up the field by the semantics described in CSV::Row.field() and # assigns the +value+. - # + # # Assigning past the end of the row with an index will set all pairs between # to <tt>[nil, nil]</tt>. Assigning to an unused header appends the new # pair. - # + # def []=(*args) value = args.pop - + if args.first.is_a? Integer if @row[args.first].nil? # extending past the end with index @row[args.first] = [nil, value] @@ -315,20 +315,20 @@ class CSV end end end - - # + + # # :call-seq: # <<( field ) # <<( header_and_field_array ) # <<( header_and_field_hash ) - # + # # If a two-element Array is provided, it is assumed to be a header and field # and the pair is appended. A Hash works the same way with the key being # the header and the value being the field. Anything else is assumed to be # a lone field which is appended with a +nil+ header. - # + # # This method returns the row for chaining. - # + # def <<(arg) if arg.is_a?(Array) and arg.size == 2 # appending a header and name @row << arg @@ -337,33 +337,33 @@ class CSV else # append field value @row << [nil, arg] end - + self # for chaining end - - # + + # # A shortcut for appending multiple fields. Equivalent to: - # + # # args.each { |arg| csv_row << arg } - # + # # This method returns the row for chaining. - # + # def push(*args) args.each { |arg| self << arg } - + self # for chaining end - - # + + # # :call-seq: # delete( header ) # delete( header, offset ) # delete( index ) - # + # # Used to remove a pair from the row by +header+ or +index+. The pair is # located as described in CSV::Row.field(). The deleted pair is returned, # or +nil+ if a pair could not be found. - # + # def delete(header_or_index, minimum_index = 0) if header_or_index.is_a? Integer # by index @row.delete_at(header_or_index) @@ -371,28 +371,28 @@ class CSV @row.delete_at(index(header_or_index, minimum_index)) end end - - # + + # # The provided +block+ is passed a header and field for each pair in the row # and expected to return +true+ or +false+, depending on whether the pair # should be deleted. - # + # # This method returns the row for chaining. - # + # def delete_if(&block) @row.delete_if(&block) - + self # for chaining end - - # + + # # This method accepts any number of arguments which can be headers, indices, - # Ranges of either, or two-element Arrays containing a header and offset. + # Ranges of either, or two-element Arrays containing a header and offset. # Each argument will be replaced with a field lookup as described in # CSV::Row.field(). - # + # # If called with no arguments, all fields are returned. - # + # def fields(*headers_and_or_indices) if headers_and_or_indices.empty? # return all fields--no arguments @row.map { |pair| pair.last } @@ -413,80 +413,80 @@ class CSV end end alias_method :values_at, :fields - - # + + # # :call-seq: # index( header ) # index( header, offset ) - # + # # This method will return the index of a field with the provided +header+. # The +offset+ can be used to locate duplicate header names, as described in # CSV::Row.field(). - # + # def index(header, minimum_index = 0) # find the pair index = headers[minimum_index..-1].index(header) # return the index at the right offset, if we found one index.nil? ? nil : index + minimum_index end - + # Returns +true+ if +name+ is a header for this row, and +false+ otherwise. def header?(name) headers.include? name end alias_method :include?, :header? - - # + + # # Returns +true+ if +data+ matches a field in this row, and +false+ # otherwise. - # + # def field?(data) fields.include? data end include Enumerable - - # + + # # Yields each pair of the row as header and field tuples (much like # iterating over a Hash). - # + # # Support for Enumerable. - # + # # This method returns the row for chaining. - # + # def each(&block) @row.each(&block) - + self # for chaining end - - # - # Returns +true+ if this row contains the same headers and fields in the + + # + # Returns +true+ if this row contains the same headers and fields in the # same order as +other+. - # + # def ==(other) @row == other.row end - - # + + # # Collapses the row into a simple Hash. Be warning that this discards field # order and clobbers duplicate fields. - # + # def to_hash # flatten just one level of the internal Array Hash[*@row.inject(Array.new) { |ary, pair| ary.push(*pair) }] end - - # + + # # Returns the row as a CSV String. Headers are not used. Equivalent to: - # + # # csv_row.fields.to_csv( options ) - # + # def to_csv(options = Hash.new) fields.to_csv(options) end alias_method :to_s, :to_csv - + # A summary of fields, by header, in an ASCII compatible String. def inspect str = ["#<", self.class.to_s] @@ -505,35 +505,35 @@ class CSV end end end - - # + + # # A CSV::Table is a two-dimensional data structure for representing CSV - # documents. Tables allow you to work with the data by row or column, + # documents. Tables allow you to work with the data by row or column, # manipulate the data, and even convert the results back to CSV, if needed. - # + # # All tables returned by CSV will be constructed from this class, if header # row processing is activated. - # + # class Table - # + # # Construct a new CSV::Table from +array_of_rows+, which are expected # to be CSV::Row objects. All rows are assumed to have the same headers. - # + # # A CSV::Table object supports the following Array methods through # delegation: - # + # # * empty?() # * length() # * size() - # + # def initialize(array_of_rows) @table = array_of_rows @mode = :col_or_row end - + # The current access mode for indexing and iteration. attr_reader :mode - + # Internal data format used to compare equality. attr_reader :table protected :table @@ -542,88 +542,88 @@ class CSV extend Forwardable def_delegators :@table, :empty?, :length, :size - - # - # Returns a duplicate table object, in column mode. This is handy for - # chaining in a single call without changing the table mode, but be aware + + # + # Returns a duplicate table object, in column mode. This is handy for + # chaining in a single call without changing the table mode, but be aware # that this method can consume a fair amount of memory for bigger data sets. - # + # # This method returns the duplicate table for chaining. Don't chain # destructive methods (like []=()) this way though, since you are working # with a duplicate. - # + # def by_col self.class.new(@table.dup).by_col! end - - # + + # # Switches the mode of this table to column mode. All calls to indexing and # iteration methods will work with columns until the mode is changed again. - # + # # This method returns the table and is safe to chain. - # + # def by_col! @mode = :col - + self end - - # - # Returns a duplicate table object, in mixed mode. This is handy for - # chaining in a single call without changing the table mode, but be aware + + # + # Returns a duplicate table object, in mixed mode. This is handy for + # chaining in a single call without changing the table mode, but be aware # that this method can consume a fair amount of memory for bigger data sets. - # + # # This method returns the duplicate table for chaining. Don't chain # destructive methods (like []=()) this way though, since you are working # with a duplicate. - # + # def by_col_or_row self.class.new(@table.dup).by_col_or_row! end - - # + + # # Switches the mode of this table to mixed mode. All calls to indexing and # iteration methods will use the default intelligent indexing system until # the mode is changed again. In mixed mode an index is assumed to be a row # reference while anything else is assumed to be column access by headers. - # + # # This method returns the table and is safe to chain. - # + # def by_col_or_row! @mode = :col_or_row - + self end - - # + + # # Returns a duplicate table object, in row mode. This is handy for chaining # in a single call without changing the table mode, but be aware that this # method can consume a fair amount of memory for bigger data sets. - # + # # This method returns the duplicate table for chaining. Don't chain # destructive methods (like []=()) this way though, since you are working # with a duplicate. - # + # def by_row self.class.new(@table.dup).by_row! end - - # + + # # Switches the mode of this table to row mode. All calls to indexing and # iteration methods will work with rows until the mode is changed again. - # + # # This method returns the table and is safe to chain. - # + # def by_row! @mode = :row - + self end - - # + + # # Returns the headers for the first row of this table (assumed to match all # other rows). An empty Array is returned for empty tables. - # + # def headers if @table.empty? Array.new @@ -631,15 +631,15 @@ class CSV @table.first.headers end end - - # + + # # In the default mixed mode, this method returns rows for index access and # columns for header access. You can force the index association by first # calling by_col!() or by_row!(). - # + # # Columns are returned as an Array of values. Altering that Array has no # effect on the table. - # + # def [](index_or_header) if @mode == :row or # by index (@mode == :col_or_row and index_or_header.is_a? Integer) @@ -648,23 +648,23 @@ class CSV @table.map { |row| row[index_or_header] } end end - - # + + # # In the default mixed mode, this method assigns rows for index access and # columns for header access. You can force the index association by first # calling by_col!() or by_row!(). - # + # # Rows may be set to an Array of values (which will inherit the table's # headers()) or a CSV::Row. - # - # Columns may be set to a single value, which is copied to each row of the + # + # Columns may be set to a single value, which is copied to each row of the # column, or an Array of values. Arrays of values are assigned to rows top # to bottom in row major order. Excess values are ignored and if the Array # does not have a value for each row the extra rows will receive a +nil+. - # + # # Assigning to an existing column or row clobbers the data. Assigning to # new columns creates them at the right end of the table. - # + # def []=(index_or_header, value) if @mode == :row or # by index (@mode == :col_or_row and index_or_header.is_a? Integer) @@ -693,16 +693,16 @@ class CSV end end end - - # + + # # The mixed mode default is to treat a list of indices as row access, # returning the rows indicated. Anything else is considered columnar # access. For columnar access, the return set has an Array for each row # with the values indicated by the headers in each Array. You can force # column or row mode using by_col!() or by_row!(). - # + # # You cannot mix column and row access. - # + # def values_at(*indices_or_headers) if @mode == :row or # by indices ( @mode == :col_or_row and indices_or_headers.all? do |index| @@ -717,41 +717,41 @@ class CSV end end - # + # # Adds a new row to the bottom end of this table. You can provide an Array, # which will be converted to a CSV::Row (inheriting the table's headers()), # or a CSV::Row. - # + # # This method returns the table for chaining. - # + # def <<(row_or_array) if row_or_array.is_a? Array # append Array @table << Row.new(headers, row_or_array) else # append Row @table << row_or_array end - + self # for chaining end - - # + + # # A shortcut for appending multiple rows. Equivalent to: - # + # # rows.each { |row| self << row } - # + # # This method returns the table for chaining. - # + # def push(*rows) rows.each { |row| self << row } - + self # for chaining end - # + # # Removes and returns the indicated column or row. In the default mixed # mode indices refer to rows and everything else is assumed to be a column # header. Use by_col!() or by_row!() to force the lookup. - # + # def delete(index_or_header) if @mode == :row or # by index (@mode == :col_or_row and index_or_header.is_a? Integer) @@ -760,15 +760,15 @@ class CSV @table.map { |row| row.delete(index_or_header).last } end end - - # + + # # Removes any column or row for which the block returns +true+. In the # default mixed mode or row mode, iteration is the standard row major # walking of rows. In column mode, interation will +yield+ two element # tuples containing the column name and an Array of values for that column. - # + # # This method returns the table for chaining. - # + # def delete_if(&block) if @mode == :row or @mode == :col_or_row # by index @table.delete_if(&block) @@ -779,38 +779,38 @@ class CSV end to_delete.map { |header| delete(header) } end - + self # for chaining end - + include Enumerable - - # + + # # In the default mixed mode or row mode, iteration is the standard row major # walking of rows. In column mode, interation will +yield+ two element # tuples containing the column name and an Array of values for that column. - # + # # This method returns the table for chaining. - # + # def each(&block) if @mode == :col headers.each { |header| block[[header, self[header]]] } else @table.each(&block) end - + self # for chaining end - + # Returns +true+ if all rows of this table ==() +other+'s rows. def ==(other) @table == other.table end - - # + + # # Returns the table as an Array of Arrays. Headers will be the first row, # then all of the field rows will follow. - # + # def to_a @table.inject([headers]) do |array, row| if row.header_row? @@ -820,11 +820,11 @@ class CSV end end end - - # + + # # Returns the table as a complete CSV String. Headers will be listed first, # then all of the field rows. - # + # def to_csv(options = Hash.new) @table.inject([headers.to_csv(options)]) do |rows, row| if row.header_row? @@ -835,7 +835,7 @@ class CSV end.join end alias_method :to_s, :to_csv - + # Shows the mode and size of this table in a US-ASCII String. def inspect "#<#{self.class} mode:#{@mode} row_count:#{to_a.size}>".encode("US-ASCII") @@ -844,19 +844,19 @@ class CSV # The error thrown when the parser encounters illegal CSV formatting. class MalformedCSVError < RuntimeError; end - - # + + # # A FieldInfo Struct contains details about a field's position in the data # source it was read from. CSV will pass this Struct to some blocks that make # decisions based on field structure. See CSV.convert_fields() for an # example. - # + # # <b><tt>index</tt></b>:: The zero-based index of the field in its row. # <b><tt>line</tt></b>:: The line of the data source this row is from. # <b><tt>header</tt></b>:: The header for the column, when available. - # + # FieldInfo = Struct.new(:index, :line, :header) - + # A Regexp used to find and convert some common Date formats. DateMatcher = / \A(?: (\w+,?\s+)?\w+\s+\d{1,2},?\s+\d{2,4} | \d{4}-\d{2}-\d{2} )\z /x @@ -864,34 +864,34 @@ class CSV DateTimeMatcher = / \A(?: (\w+,?\s+)?\w+\s+\d{1,2}\s+\d{1,2}:\d{1,2}:\d{1,2},?\s+\d{2,4} | \d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2} )\z /x - + # The encoding used by all converters. ConverterEncoding = Encoding.find("UTF-8") - - # + + # # This Hash holds the built-in converters of CSV that can be accessed by name. # You can select Converters with CSV.convert() or through the +options+ Hash # passed to CSV::new(). - # + # # <b><tt>:integer</tt></b>:: Converts any field Integer() accepts. # <b><tt>:float</tt></b>:: Converts any field Float() accepts. - # <b><tt>:numeric</tt></b>:: A combination of <tt>:integer</tt> + # <b><tt>:numeric</tt></b>:: A combination of <tt>:integer</tt> # and <tt>:float</tt>. # <b><tt>:date</tt></b>:: Converts any field Date::parse() accepts. # <b><tt>:date_time</tt></b>:: Converts any field DateTime::parse() accepts. - # <b><tt>:all</tt></b>:: All built-in converters. A combination of + # <b><tt>:all</tt></b>:: All built-in converters. A combination of # <tt>:date_time</tt> and <tt>:numeric</tt>. - # + # # All built-in converters transcode field data to UTF-8 before attempting a # conversion. If your data cannot be transcoded to UTF-8 the conversion will # fail and the field will remain unchanged. - # + # # This Hash is intentionally left unfrozen and users should feel free to add # values to it that can be accessed by all CSV objects. - # + # # To add a combo field, the value should be an Array of names. Combo fields # can be nested with other combo fields. - # + # Converters = { integer: lambda { |f| Integer(f.encode(ConverterEncoding)) rescue f }, @@ -917,26 +917,26 @@ class CSV }, all: [:date_time, :numeric] } - # + # # This Hash holds the built-in header converters of CSV that can be accessed # by name. You can select HeaderConverters with CSV.header_convert() or # through the +options+ Hash passed to CSV::new(). - # + # # <b><tt>:downcase</tt></b>:: Calls downcase() on the header String. # <b><tt>:symbol</tt></b>:: The header String is downcased, spaces are # replaced with underscores, non-word characters # are dropped, and finally to_sym() is called. - # + # # All built-in header converters transcode header data to UTF-8 before # attempting a conversion. If your data cannot be transcoded to UTF-8 the # conversion will fail and the header will remain unchanged. - # + # # This Hash is intetionally left unfrozen and users should feel free to add # values to it that can be accessed by all CSV objects. - # + # # To add a combo field, the value should be an Array of names. Combo fields # can be nested with other combo fields. - # + # HeaderConverters = { downcase: lambda { |h| h.encode(ConverterEncoding).downcase }, symbol: lambda { |h| @@ -944,10 +944,10 @@ class CSV gsub(/\W+/, "").to_sym } } - - # + + # # The options used when no overrides are given by calling code. They are: - # + # # <b><tt>:col_sep</tt></b>:: <tt>","</tt> # <b><tt>:row_sep</tt></b>:: <tt>:auto</tt> # <b><tt>:quote_char</tt></b>:: <tt>'"'</tt> @@ -959,10 +959,10 @@ class CSV # <b><tt>:header_converters</tt></b>:: +nil+ # <b><tt>:skip_blanks</tt></b>:: +false+ # <b><tt>:force_quotes</tt></b>:: +false+ - # + # DEFAULT_OPTIONS = { col_sep: ",", row_sep: :auto, - quote_char: '"', + quote_char: '"', field_size_limit: nil, converters: nil, unconverted_fields: nil, @@ -971,21 +971,21 @@ class CSV header_converters: nil, skip_blanks: false, force_quotes: false }.freeze - - # + + # # This method will return a CSV instance, just like CSV::new(), but the # instance will be cached and returned for all future calls to this method for # the same +data+ object (tested by Object#object_id()) with the same # +options+. - # + # # If a block is given, the instance is passed to the block and the return # value becomes the return value of the block. - # + # def self.instance(data = $stdout, options = Hash.new) # create a _signature_ for this method call, data object and options sig = [data.object_id] + options.values_at(*DEFAULT_OPTIONS.keys.sort_by { |sym| sym.to_s }) - + # fetch or create the instance for this signature @@instances ||= Hash.new instance = (@@instances[sig] ||= new(data, options)) @@ -997,25 +997,25 @@ class CSV end end - # + # # This method allows you to serialize an Array of Ruby objects to a String or # File of CSV data. This is not as powerful as Marshal or YAML, but perhaps # useful for spreadsheet and database interaction. - # + # # Out of the box, this method is intended to work with simple data objects or # Structs. It will serialize a list of instance variables and/or # Struct.members(). - # + # # If you need need more complicated serialization, you can control the process # by adding methods to the class to be serialized. - # + # # A class method csv_meta() is responsible for returning the first row of the # document (as an Array). This row is considered to be a Hash of the form # key_1,value_1,key_2,value_2,... CSV::load() expects to find a class key # with a value of the stringified class name and CSV::dump() will create this, # if you do not define this method. This method is only called on the first # object of the Array. - # + # # The next method you can provide is an instance method called csv_headers(). # This method is expected to return the second line of the document (again as # an Array), which is to be used to give each column a header. By default, @@ -1023,20 +1023,20 @@ class CSV # @ character or call send() passing the header as the method name and # the field value as an argument. This method is only called on the first # object of the Array. - # + # # Finally, you can provide an instance method called csv_dump(), which will # be passed the headers. This should return an Array of fields that can be # serialized for this object. This method is called once for every object in # the Array. - # + # # The +io+ parameter can be used to serialize to a File, and +options+ can be # anything CSV::new() accepts. - # + # def self.dump(ary_of_objs, io = "", options = Hash.new) obj_template = ary_of_objs.first - + csv = new(io, options) - + # write meta information begin csv << obj_template.class.csv_meta @@ -1054,7 +1054,7 @@ class CSV end end csv << headers - + # serialize each object ary_of_objs.each do |obj| begin @@ -1069,39 +1069,39 @@ class CSV end end end - + if io.is_a? String csv.string else csv.close end end - - # + + # # This method is the reading counterpart to CSV::dump(). See that method for # a detailed description of the process. - # - # You can customize loading by adding a class method called csv_load() which + # + # You can customize loading by adding a class method called csv_load() which # will be passed a Hash of meta information, an Array of headers, and an Array # of fields for the object the method is expected to return. - # + # # Remember that all fields will be Strings after this load. If you need # something else, use +options+ to setup converters or provide a custom # csv_load() implementation. - # + # def self.load(io_or_str, options = Hash.new) csv = new(io_or_str, options) - + # load meta information meta = Hash[*csv.shift] cls = meta["class".encode(csv.encoding)].split("::".encode(csv.encoding)). inject(Object) do |c, const| c.const_get(const) end - + # load headers headers = csv.shift - + # unserialize each object stored in the file results = csv.inject(Array.new) do |all, row| begin @@ -1118,36 +1118,36 @@ class CSV end all << obj end - + csv.close unless io_or_str.is_a? String - + results end - - # + + # # :call-seq: # filter( options = Hash.new ) { |row| ... } # filter( input, options = Hash.new ) { |row| ... } # filter( input, output, options = Hash.new ) { |row| ... } - # + # # This method is a convenience for building Unix-like filters for CSV data. - # Each row is yielded to the provided block which can alter it as needed. + # Each row is yielded to the provided block which can alter it as needed. # After the block returns, the row is appended to +output+ altered or not. - # + # # The +input+ and +output+ arguments can be anything CSV::new() accepts - # (generally String or IO objects). If not given, they default to + # (generally String or IO objects). If not given, they default to # <tt>ARGF</tt> and <tt>$stdout</tt>. - # + # # The +options+ parameter is also filtered down to CSV::new() after some - # clever key parsing. Any key beginning with <tt>:in_</tt> or + # clever key parsing. Any key beginning with <tt>:in_</tt> or # <tt>:input_</tt> will have that leading identifier stripped and will only # be used in the +options+ Hash for the +input+ object. Keys starting with - # <tt>:out_</tt> or <tt>:output_</tt> affect only +output+. All other keys + # <tt>:out_</tt> or <tt>:output_</tt> affect only +output+. All other keys # are assigned to both objects. - # + # # The <tt>:output_row_sep</tt> +option+ defaults to # <tt>$INPUT_RECORD_SEPARATOR</tt> (<tt>$/</tt>). - # + # def self.filter(*args) # parse options for input, output, or both in_options, out_options = Hash.new, {row_sep: $INPUT_RECORD_SEPARATOR} @@ -1167,19 +1167,19 @@ class CSV # build input and output wrappers input = new(args.shift || ARGF, in_options) output = new(args.shift || $stdout, out_options) - + # read, yield, write input.each do |row| yield row output << row end end - - # + + # # This method is intended as the primary interface for reading CSV files. You # pass a +path+ and any +options+ you wish to set for the read. Each row of # file will be passed to the provided +block+ in turn. - # + # # The +options+ parameter can be anything CSV::new() understands. This method # also understands an additional <tt>:encoding</tt> parameter that you can use # to specify the Encoding of the data in the file to be read. You must provide @@ -1188,7 +1188,7 @@ class CSV # have the data transcoded as it is read. For example, # <tt>encoding: "UTF-32BE:UTF-8"</tt> would read UTF-32BE data from the file # but transcode it to UTF-8 before CSV parses it. - # + # def self.foreach(path, options = Hash.new, &block) encoding = options.delete(:encoding) mode = "rb" @@ -1198,24 +1198,24 @@ class CSV end end - # + # # :call-seq: # generate( str, options = Hash.new ) { |csv| ... } # generate( options = Hash.new ) { |csv| ... } - # - # This method wraps a String you provide, or an empty default String, in a + # + # This method wraps a String you provide, or an empty default String, in a # CSV object which is passed to the provided block. You can use the block to # append CSV rows to the String and when the block exits, the final String # will be returned. - # + # # Note that a passed String *is* modfied by this method. Call dup() before # passing if you need a new String. - # + # # The +options+ parameter can be anthing CSV::new() understands. This method # understands an additional <tt>:encoding</tt> parameter when not passed a # String to set the base Encoding for the output. CSV needs this hint if you # plan to output non-ASCII compatible data. - # + # def self.generate(*args) # add a default empty String, if none was given if args.first.is_a? String @@ -1233,19 +1233,19 @@ class CSV csv.string # return final String end - # - # This method is a shortcut for converting a single row (Array) into a CSV + # + # This method is a shortcut for converting a single row (Array) into a CSV # String. - # + # # The +options+ parameter can be anthing CSV::new() understands. This method - # understands an additional <tt>:encoding</tt> parameter to set the base + # understands an additional <tt>:encoding</tt> parameter to set the base # Encoding for the output. This method will try to guess your Encoding from # the first non-+nil+ field in +row+, if possible, but you may need to use # this parameter as a backup plan. - # + # # The <tt>:row_sep</tt> +option+ defaults to <tt>$INPUT_RECORD_SEPARATOR</tt> # (<tt>$/</tt>) when calling this method. - # + # def self.generate_line(row, options = Hash.new) options = {row_sep: $INPUT_RECORD_SEPARATOR}.merge(options) encoding = options.delete(:encoding) @@ -1257,27 +1257,27 @@ class CSV end (new(str, options) << row).string end - - # + + # # :call-seq: # open( filename, mode = "rb", options = Hash.new ) { |faster_csv| ... } # open( filename, options = Hash.new ) { |faster_csv| ... } # open( filename, mode = "rb", options = Hash.new ) # open( filename, options = Hash.new ) - # + # # This method opens an IO object, and wraps that with CSV. This is intended # as the primary interface for writing a CSV file. - # + # # You must pass a +filename+ and may optionally add a +mode+ for Ruby's # open(). You may also pass an optional Hash containing any +options+ # CSV::new() understands as the final argument. - # + # # This method works like Ruby's open() call, in that it will pass a CSV object # to a provided block and close it when the block terminates, or it will # return the CSV object when no block is provided. (*Note*: This is different # from the Ruby 1.8 CSV library which passed rows to the block. Use # CSV::foreach() for that behavior.) - # + # # You must provide a +mode+ with an embedded Encoding designator unless your # data is in Encoding::default_external(). CSV will check the Encoding of the # underlying IO object (set by the +mode+ you pass) to deterime how to parse @@ -1285,10 +1285,10 @@ class CSV # it is read just as you can with a normal call to IO::open(). For example, # <tt>"rb:UTF-32BE:UTF-8"</tt> would read UTF-32BE data from the file but # transcode it to UTF-8 before CSV parses it. - # + # # An opened CSV object will delegate to many IO methods for convenience. You # may call: - # + # # * binmode() # * binmode?() # * close() @@ -1320,7 +1320,7 @@ class CSV # * to_io() # * truncate() # * tty?() - # + # def self.open(*args) # find the +options+ Hash options = if args.last.is_a? Hash then args.pop else Hash.new end @@ -1328,7 +1328,7 @@ class CSV args << "rb" if args.size == 1 # wrap a File opened with the remaining +args+ csv = new(File.open(*args), options) - + # handle blocks like Ruby's open(), not like the CSV library if block_given? begin @@ -1340,19 +1340,19 @@ class CSV csv end end - - # + + # # :call-seq: # parse( str, options = Hash.new ) { |row| ... } # parse( str, options = Hash.new ) - # + # # This method can be used to easily parse CSV out of a String. You may either # provide a +block+ which will be called with each row of the String in turn, # or just use the returned Array of Arrays (when no +block+ is given). - # + # # You pass your +str+ to read from, and an optional +options+ Hash containing # anything CSV::new() understands. - # + # def self.parse(*args, &block) csv = new(*args) if block.nil? # slurp contents, if no block is given @@ -1365,20 +1365,20 @@ class CSV csv.each(&block) end end - - # - # This method is a shortcut for converting a single line of a CSV String into - # a into an Array. Note that if +line+ contains multiple rows, anything + + # + # This method is a shortcut for converting a single line of a CSV String into + # a into an Array. Note that if +line+ contains multiple rows, anything # beyond the first row is ignored. - # + # # The +options+ parameter can be anthing CSV::new() understands. - # + # def self.parse_line(line, options = Hash.new) new(line, options).shift end - - # - # Use to slurp a CSV file into an Array of Arrays. Pass the +path+ to the + + # + # Use to slurp a CSV file into an Array of Arrays. Pass the +path+ to the # file and any +options+ CSV::new() understands. This method also understands # an additional <tt>:encoding</tt> parameter that you can use to specify the # Encoding of the data in the file to be read. You must provide this unless @@ -1387,46 +1387,46 @@ class CSV # transcoded as it is read. For example, # <tt>encoding: "UTF-32BE:UTF-8"</tt> would read UTF-32BE data from the file # but transcode it to UTF-8 before CSV parses it. - # + # def self.read(path, options = Hash.new) encoding = options.delete(:encoding) mode = "rb" mode << ":#{encoding}" if encoding open(path, mode, options) { |csv| csv.read } end - + # Alias for CSV::read(). def self.readlines(*args) read(*args) end - - # + + # # A shortcut for: - # + # # CSV.read( path, { headers: true, # converters: :numeric, # header_converters: :symbol }.merge(options) ) - # + # def self.table(path, options = Hash.new) read( path, { headers: true, converters: :numeric, header_converters: :symbol }.merge(options) ) end - - # + + # # This constructor will wrap either a String or IO object passed in +data+ for # reading and/or writing. In addition to the CSV instance methods, several IO # methods are delegated. (See CSV::open() for a complete list.) If you pass # a String for +data+, you can later retrieve it (after writing to it, for # example) with CSV.string(). - # - # Note that a wrapped String will be positioned at at the beginning (for + # + # Note that a wrapped String will be positioned at at the beginning (for # reading). If you want it at the end (for writing), use CSV::generate(). # If you want any other positioning, pass a preset StringIO object instead. - # - # You may set any reading and/or writing preferences in the +options+ Hash. + # + # You may set any reading and/or writing preferences in the +options+ Hash. # Available options are: - # + # # <b><tt>:col_sep</tt></b>:: The String placed between each field. # This String will be transcoded into # the data's Encoding before parsing. @@ -1501,7 +1501,7 @@ class CSV # Array or String were not fields of the # document and thus will have an empty # Array attached. - # <b><tt>:headers</tt></b>:: If set to <tt>:first_row</tt> or + # <b><tt>:headers</tt></b>:: If set to <tt>:first_row</tt> or # +true+, the initial row of the CSV # file will be treated as a row of # headers. If set to an Array, the @@ -1538,16 +1538,16 @@ class CSV # skip over any rows with no content. # <b><tt>:force_quotes</tt></b>:: When set to a +true+ value, CSV will # quote all CSV fields it creates. - # + # # See CSV::DEFAULT_OPTIONS for the default settings. - # + # # Options cannot be overriden in the instance methods for performance reasons, # so be sure to set what you want here. - # + # def initialize(data, options = Hash.new) # build the options for this read/write options = DEFAULT_OPTIONS.merge(options) - + # create the IO object we will read from @io = if data.is_a? String then StringIO.new(data) else data end # honor the IO encoding if we can, otherwise default to ASCII-8BIT @@ -1557,110 +1557,110 @@ class CSV @io.string.encoding end @encoding ||= Encoding.default_internal || Encoding.default_external - # + # # prepare for building safe regular expressions in the target encoding, # if we can transcode the needed characters - # + # @re_esc = "\\".encode(@encoding) rescue "" @re_chars = %w[ \\ . [ ] - ^ $ ? * + { } ( ) | # \ \r \n \t \f \v ]. map { |s| s.encode(@encoding) rescue nil }.compact - + init_separators(options) init_parsers(options) init_converters(options) init_headers(options) - + unless options.empty? raise ArgumentError, "Unknown options: #{options.keys.join(', ')}." end - + # track our own lineno since IO gets confused about line-ends is CSV fields @lineno = 0 end - - # + + # # The encoded <tt>:col_sep</tt> used in parsing and writing. See CSV::new # for details. - # + # attr_reader :col_sep - # + # # The encoded <tt>:row_sep</tt> used in parsing and writing. See CSV::new # for details. - # + # attr_reader :row_sep - # + # # The encoded <tt>:quote_char</tt> used in parsing and writing. See CSV::new # for details. - # + # attr_reader :quote_char # The limit for field size, if any. See CSV::new for details. attr_reader :field_size_limit - # + # # Returns the current list of converters in effect. See CSV::new for details. # Built-in converters will be returned by name, while others will be returned # as is. - # + # def converters @converters.map do |converter| name = Converters.rassoc(converter) name ? name.first : converter end end - # + # # Returns +true+ if unconverted_fields() to parsed results. See CSV::new # for details. - # + # def unconverted_fields?() @unconverted_fields end - # + # # Returns +nil+ if headers will not be used, +true+ if they will but have not # yet been read, or the actual headers after they have been read. See # CSV::new for details. - # + # def headers @headers || true if @use_headers end - # + # # Returns +true+ if headers will be returned as a row of results. # See CSV::new for details. - # + # def return_headers?() @return_headers end # Returns +true+ if headers are written in output. See CSV::new for details. def write_headers?() @write_headers end - # + # # Returns the current list of converters in effect for headers. See CSV::new # for details. Built-in converters will be returned by name, while others # will be returned as is. - # + # def header_converters @header_converters.map do |converter| name = HeaderConverters.rassoc(converter) name ? name.first : converter end end - # + # # Returns +true+ blank lines are skipped by the parser. See CSV::new # for details. - # + # def skip_blanks?() @skip_blanks end # Returns +true+ if all output fields are quoted. See CSV::new for details. def force_quotes?() @force_quotes end - - # + + # # The Encoding CSV is parsing or writing in. This will be the Encoding you # receive parsed data in and/or the Encoding data will be written in. - # + # attr_reader :encoding - - # - # The line number of the last row read from this file. Fields with nested + + # + # The line number of the last row read from this file. Fields with nested # line-end characters will not affect this count. - # + # attr_reader :lineno - + ### IO and StringIO Delegation ### - + extend Forwardable def_delegators :@io, :binmode, :binmode?, :close, :close_read, :close_write, :closed?, :eof, :eof?, :external_encoding, :fcntl, @@ -1668,31 +1668,31 @@ class CSV :ioctl, :isatty, :path, :pid, :pos, :pos=, :reopen, :seek, :stat, :string, :sync, :sync=, :tell, :to_i, :to_io, :truncate, :tty? - + # Rewinds the underlying IO object and resets CSV's lineno() counter. def rewind @headers = nil @lineno = 0 - + @io.rewind end ### End Delegation ### - - # + + # # The primary write method for wrapped Strings and IOs, +row+ (an Array or # CSV::Row) is converted to CSV and appended to the data source. When a # CSV::Row is passed, only the row's fields() are appended to the output. - # + # # The data source must be open for writing. - # + # def <<(row) # make sure headers have been assigned if header_row? and [Array, String].include? @use_headers.class parse_headers # won't read data for Array or String self << @headers if @write_headers end - + # handle CSV::Row objects and Hashes row = case row when self.class::Row then row.fields @@ -1704,69 +1704,69 @@ class CSV @lineno += 1 @io << row.map(&@quote).join(@col_sep) + @row_sep # quote and separate - + self # for chaining end alias_method :add_row, :<< alias_method :puts, :<< - - # + + # # :call-seq: # convert( name ) # convert { |field| ... } # convert { |field, field_info| ... } - # + # # You can use this method to install a CSV::Converters built-in, or provide a # block that handles a custom conversion. - # + # # If you provide a block that takes one argument, it will be passed the field # and is expected to return the converted value or the field itself. If your - # block takes two arguments, it will also be passed a CSV::FieldInfo Struct, - # containing details about the field. Again, the block should return a + # block takes two arguments, it will also be passed a CSV::FieldInfo Struct, + # containing details about the field. Again, the block should return a # converted field or the field itself. - # + # def convert(name = nil, &converter) add_converter(:converters, self.class::Converters, name, &converter) end - # + # # :call-seq: # header_convert( name ) # header_convert { |field| ... } # header_convert { |field, field_info| ... } - # + # # Identical to CSV#convert(), but for header rows. - # + # # Note that this method must be called before header rows are read to have any # effect. - # + # def header_convert(name = nil, &converter) add_converter( :header_converters, self.class::HeaderConverters, name, &converter ) end - + include Enumerable - - # + + # # Yields each row of the data source in turn. - # + # # Support for Enumerable. - # + # # The data source must be open for reading. - # + # def each while row = shift yield row end end - - # + + # # Slurps the remaining rows and returns an Array of Arrays. - # + # # The data source must be open for reading. - # + # def read rows = to_a if @use_headers @@ -1776,25 +1776,25 @@ class CSV end end alias_method :readlines, :read - + # Returns +true+ if the next row read will be a header row. def header_row? @use_headers and @headers.nil? end - - # + + # # The primary read method for wrapped Strings and IOs, a single row is pulled # from the data source, parsed and returned as an Array of fields (if header # rows are not used) or a CSV::Row (when header rows are used). - # + # # The data source must be open for reading. - # + # def shift ######################################################################### ### This method is purposefully kept a bit long as simple conditional ### ### checks are faster than numerous (expensive) method calls. ### ######################################################################### - + # handle headers not based on document content if header_row? and @return_headers and [Array, String].include? @use_headers.class @@ -1804,25 +1804,25 @@ class CSV return parse_headers end end - + # begin with a blank line, so we can always add to it line = "" - # + # # it can take multiple calls to <tt>@io.gets()</tt> to get a full line, # because of \r and/or \n characters embedded in quoted fields - # + # loop do # add another read to the line (line += @io.gets(@row_sep)) rescue return nil # copy the line so we can chop it up in parsing parse = line.dup parse.sub!(@parsers[:line_end], "") - - # + + # # I believe a blank line should be an <tt>Array.new</tt>, not Ruby 1.8 # CSV's <tt>[nil]</tt> - # + # if parse.empty? @lineno += 1 if @skip_blanks @@ -1837,19 +1837,19 @@ class CSV end end - # - # shave leading empty fields if needed, because the main parser chokes + # + # shave leading empty fields if needed, because the main parser chokes # on these - # + # csv = if parse.sub!(@parsers[:leading_fields], "") [nil] * ($&.length / @col_sep.length) else Array.new end - # - # then parse the main fields with a hyper-tuned Regexp from + # + # then parse the main fields with a hyper-tuned Regexp from # Mastering Regular Expressions, Second Edition - # + # parse.gsub!(@parsers[:csv_row]) do csv << if $1.nil? # we found an unquoted field if $2.empty? # switch empty unquoted fields to +nil+... @@ -1903,11 +1903,11 @@ class CSV end alias_method :gets, :shift alias_method :readline, :shift - - # + + # # Returns a simplified description of the key FasterCSV attributes in an # ASCII compatible String. - # + # def inspect str = ["<#", self.class.to_s, " io_type:"] # show type of wrapped IO @@ -1942,19 +1942,19 @@ class CSV end.join end end - + private - - # + + # # Stores the indicated separators for later use. - # + # # If auto-discovery was requested for <tt>@row_sep</tt>, this method will read # ahead in the <tt>@io</tt> and try to find one. +ARGF+, +STDIN+, +STDOUT+, # +STDERR+ and any stream open for output only with a default # <tt>@row_sep</tt> of <tt>$INPUT_RECORD_SEPARATOR</tt> (<tt>$/</tt>). - # + # # This method also establishes the quoting rules used for CSV output. - # + # def init_separators(options) # store the selected separators @col_sep = options.delete(:col_sep).to_s.encode(@encoding) @@ -1964,11 +1964,11 @@ class CSV if @quote_char.length != 1 raise ArgumentError, ":quote_char has to be a single character String" end - - # + + # # automatically discover row separator when requested # (not fully encoding safe) - # + # if @row_sep == :auto if [ARGF, STDIN, STDOUT, STDERR].include?(@io) or (defined?(Zlib) and @io.class == Zlib::GzipWriter) @@ -1977,20 +1977,20 @@ class CSV begin saved_pos = @io.pos # remember where we were while @row_sep == :auto - # - # if we run out of data, it's probably a single line + # + # if we run out of data, it's probably a single line # (use a sensible default) - # + # if @io.eof? @row_sep = $INPUT_RECORD_SEPARATOR break end - + # read ahead a bit sample = read_to_char(1024) sample += read_to_char(1) if sample[-1..-1] == encode_str("\r") and not @io.eof? - + # try to find a standard separator if sample =~ encode_re("\r\n?|\n") @row_sep = $& @@ -2011,7 +2011,7 @@ class CSV end end @row_sep = @row_sep.to_s.encode(@encoding) - + # establish quoting rules @force_quotes = options.delete(:force_quotes) do_quote = lambda do |field| @@ -2039,13 +2039,13 @@ class CSV end end end - + # Pre-compiles parsers and stores them by name for access during reads. def init_parsers(options) # store the parser behaviors @skip_blanks = options.delete(:skip_blanks) @field_size_limit = options.delete(:field_size_limit) - + # prebuild Regexps for faster parsing esc_col_sep = escape_re(@col_sep) esc_row_sep = escape_re(@row_sep) @@ -2084,27 +2084,27 @@ class CSV return_newline: encode_str("\r\n") } end - - # + + # # Loads any converters requested during construction. - # + # # If +field_name+ is set <tt>:converters</tt> (the default) field converters # are set. When +field_name+ is <tt>:header_converters</tt> header converters # are added instead. - # - # The <tt>:unconverted_fields</tt> option is also actived for + # + # The <tt>:unconverted_fields</tt> option is also actived for # <tt>:converters</tt> calls, if requested. - # + # def init_converters(options, field_name = :converters) if field_name == :converters @unconverted_fields = options.delete(:unconverted_fields) end instance_variable_set("@#{field_name}", Array.new) - + # find the correct method to add the converters convert = method(field_name.to_s.sub(/ers\Z/, "")) - + # load converters unless options[field_name].nil? # allow a single converter not wrapped in an Array @@ -2120,10 +2120,10 @@ class CSV end end end - + options.delete(field_name) end - + # Stores header row settings and loads header converters, if needed. def init_headers(options) @use_headers = options.delete(:headers) @@ -2132,18 +2132,18 @@ class CSV # headers must be delayed until shift(), in case they need a row of content @headers = nil - + init_converters(options, :header_converters) end - - # + + # # The actual work method for adding converters, used by both CSV.convert() and # CSV.header_convert(). - # + # # This method requires the +var_name+ of the instance variable to place the # converters in, the +const+ Hash to lookup named converters in, and the # normal parameters of the CSV.convert() and CSV.header_convert() methods. - # + # def add_converter(var_name, const, name = nil, &converter) if name.nil? # custom converter instance_variable_get("@#{var_name}") << converter @@ -2159,18 +2159,18 @@ class CSV end end end - - # + + # # Processes +fields+ with <tt>@converters</tt>, or <tt>@header_converters</tt> # if +headers+ is passed as +true+, returning the converted field set. Any # converter that changes the field into something other than a String halts # the pipeline of conversion for that field. This is primarily an efficiency # shortcut. - # + # def convert_fields(fields, headers = false) # see if we are converting headers or fields converters = headers ? @header_converters : @converters - + fields.map.with_index do |field, index| converters.each do |converter| field = if converter.arity == 1 # straight field converter @@ -2184,17 +2184,17 @@ class CSV field # final state of each field, converted or original end end - - # + + # # This methods is used to turn a finished +row+ into a CSV::Row. Header rows # are also dealt with here, either by returning a CSV::Row with identical # headers and fields (save that the fields do not go through the converters) # or by reading past them to return a field row. Headers are also saved in # <tt>@headers</tt> for use in future rows. - # + # # When +nil+, +row+ is assumed to be a header row not based on an actual row # of the stream. - # + # def parse_headers(row = nil) if @headers.nil? # header row @headers = case @use_headers # save headers @@ -2209,11 +2209,11 @@ class CSV # first row is headers else row end - + # prepare converted and unconverted copies row = @headers if row.nil? @headers = convert_fields(@headers, true) - + if @return_headers # return headers return self.class::Row.new(@headers, row, true) elsif not [Array, String].include? @use_headers.class # skip to field row @@ -2223,12 +2223,12 @@ class CSV self.class::Row.new(@headers, convert_fields(row)) # field row end - - # + + # # Thiw methods injects an instance variable <tt>unconverted_fields</tt> into # +row+ and an accessor method for it called unconverted_fields(). The # variable is set to the contents of +fields+. - # + # def add_unconverted_fields(row, fields) class << row attr_reader :unconverted_fields @@ -2236,41 +2236,41 @@ class CSV row.instance_eval { @unconverted_fields = fields } row end - - # + + # # This method is an encoding safe version of Regexp::escape(). It will escape # any characters that would change the meaning of a regular expression in the # encoding of +str+. Regular expression characters that cannot be transcoded # to the target encoding will be skipped and no escaping will be performed if # a backslash cannot be transcoded. - # + # def escape_re(str) str.chars.map { |c| @re_chars.include?(c) ? @re_esc + c : c }.join end - - # + + # # Builds a regular expression in <tt>@encoding</tt>. All +chunks+ will be # transcoded to that encoding. - # + # def encode_re(*chunks) Regexp.new(encode_str(*chunks)) end - - # + + # # Builds a String in <tt>@encoding</tt>. All +chunks+ will be transcoded to # that encoding. - # + # def encode_str(*chunks) chunks.map { |chunk| chunk.encode(@encoding.name) }.join end - # + # # Reads at least +bytes+ from <tt>@io</tt>, but will read up 10 bytes ahead if # needed to ensure the data read is valid in the ecoding of that data. This # should ensure that it is safe to use regular expressions on the read data, # unless it is actually a broken encoding. The read data will be returned in # <tt>@encoding</tt>. - # + # def read_to_char(bytes) return "" if @io.eof? data = @io.read(bytes) diff --git a/lib/debug.rb b/lib/debug.rb index 7bb1450198..10236c352d 100644 --- a/lib/debug.rb +++ b/lib/debug.rb @@ -220,7 +220,7 @@ class Context def debug_command(file, line, id, binding) MUTEX.lock unless defined?($debugger_restart) and $debugger_restart - callcc{|c| $debugger_restart = c} + callcc{|c| $debugger_restart = c} end set_last_thread(Thread.current) frame_pos = 0 @@ -299,7 +299,7 @@ class Context stdout.print "Breakpoints:\n" break_points.each do |b| if b[0] and b[1] == 0 - stdout.printf " %d %s:%s\n", n, b[2], b[3] + stdout.printf " %d %s:%s\n", n, b[2], b[3] end n += 1 end @@ -711,7 +711,7 @@ EOHELP end @frames.shift - when 'raise' + when 'raise' excn_handle(file, line, id, binding) end @@ -878,7 +878,7 @@ class << DEBUGGER__ @stdout.print "Already stopped.\n" else thread_list(@thread_list[th]) - context(th).suspend + context(th).suspend end when /^resume\s+(\d+)/ diff --git a/lib/delegate.rb b/lib/delegate.rb index 025e901a89..5fc0cafb4b 100644 --- a/lib/delegate.rb +++ b/lib/delegate.rb @@ -37,16 +37,16 @@ # 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 @@ -57,7 +57,7 @@ # Elements: 4 # Non-Nil: 4 # Unique: 4 -# +# # Elements: 8 # Non-Nil: 7 # Unique: 6 @@ -72,19 +72,19 @@ # # 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 # @@ -97,15 +97,15 @@ # super # pass obj to Delegator constructor, required # @delegate_sd_obj = obj # store obj for future use # end -# +# # def __getobj__ # @delegate_sd_obj # return object we are delegating to, required # end -# +# # def __setobj__(obj) # @delegate_sd_obj = obj # change delegation object, a feature we're providing # end -# +# # # ... # end @@ -142,18 +142,18 @@ class Delegator end end - # - # Checks for a method provided by this the delegate object by fowarding the + # + # Checks for a method provided by this the delegate object by fowarding the # call through \_\_getobj\_\_. - # + # def respond_to?(m, include_private = false) return true if super return self.__getobj__.respond_to?(m, include_private) end - # + # # Returns true if two objects are considered same. - # + # def ==(obj) return true if obj.equal?(self) self.__getobj__ == obj diff --git a/lib/drb/drb.rb b/lib/drb/drb.rb index 13a89de07f..6a4e6021db 100644 --- a/lib/drb/drb.rb +++ b/lib/drb/drb.rb @@ -18,7 +18,7 @@ # # 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 +# 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*). # @@ -121,7 +121,7 @@ require 'drb/eq' # 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 @@ -135,7 +135,7 @@ require 'drb/eq' # 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 @@ -148,33 +148,33 @@ require 'drb/eq' # starting the server code first. # # ==== Server code -# +# # require 'drb/drb' -# +# # # The URI for the server to connect to -# URI="druby://localhost:8787" -# +# 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" # @@ -184,43 +184,43 @@ require 'drb/eq' # # 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 +# 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 +# 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 @@ -228,12 +228,12 @@ require 'drb/eq' # # 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 [email protected]_key? name # # make the filename safe, then declare it to be so @@ -242,34 +242,34 @@ require 'drb/eq' # 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 @@ -288,9 +288,9 @@ require 'drb/eq' # 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 +# 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 @@ -360,7 +360,7 @@ module DRb # # 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 + # drb remains valid only while that object instance remains alive # within the server runtime. # # For alternative mechanisms, see DRb::TimerIdConv in rdb/timeridconv.rb @@ -374,7 +374,7 @@ module DRb def to_obj(ref) ObjectSpace._id2ref(ref) end - + # Convert an object into a reference id. # # This implementation returns the object's __id__ in the local @@ -390,7 +390,7 @@ module DRb # 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. - module DRbUndumped + module DRbUndumped def _dump(dummy) # :nodoc: raise TypeError, 'can\'t dump' end @@ -424,7 +424,7 @@ module DRb def self._load(s) # :nodoc: Marshal::load(s) end - + def _dump(lv) # :nodoc: Marshal::dump(@unknown) end @@ -456,11 +456,11 @@ module DRb # +name+ attribute. The marshalled object is held in the +buf+ # attribute. class DRbUnknown - + # 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 + # 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. def initialize(err, buf) @@ -499,7 +499,7 @@ module DRb # 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 + # will be unmarshalled and returned. Otherwise, a new # but identical DRbUnknown object will be returned. def reload self.class._load(@buf) @@ -513,7 +513,7 @@ module DRb class DRbArray def initialize(ary) - @ary = ary.collect { |obj| + @ary = ary.collect { |obj| if obj.kind_of? DRbUndumped DRbObject.new(obj) else @@ -607,7 +607,7 @@ module DRb rescue raise(DRbConnError, $!.message, $!.backtrace) end - + def recv_request(stream) # :nodoc: ref = load(stream) ro = DRb.to_obj(ref) @@ -656,10 +656,10 @@ module DRb # 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'), + # 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 + # 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 @@ -675,14 +675,14 @@ module DRb # # The protocol instance returned by #open must have the following methods: # - # [send_request (ref, msg_id, arg, b)] + # [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 + # DRb.recv_reply, providing a stream that sits on top of the # current protocol. # [alive?] # Is this connection still alive? @@ -725,7 +725,7 @@ module DRb # 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. - def open(uri, config, first=true) + def open(uri, config, first=true) @protocol.each do |prot| begin return prot.open(uri, config) @@ -744,14 +744,14 @@ module DRb end module_function :open - # Open a server listening for connections at +uri+ with + # 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 + # 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. def open_server(uri, config, first=true) @protocol.each do |prot| @@ -773,7 +773,7 @@ module DRb # 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. + # URI, then a DRbBadURI error is raised. def uri_option(uri, config, first=true) @protocol.each do |prot| begin @@ -837,9 +837,9 @@ module DRb end def self.open_server_inaddr_any(host, port) - infos = Socket::getaddrinfo(host, nil, + infos = Socket::getaddrinfo(host, nil, Socket::AF_UNSPEC, - Socket::SOCK_STREAM, + Socket::SOCK_STREAM, 0, Socket::AI_PASSIVE) family = infos.collect { |af, *_| af }.uniq @@ -853,7 +853,7 @@ module DRb end end - # Open a server listening for connections at +uri+ using + # Open a server listening for connections at +uri+ using # configuration +config+. def self.open_server(uri, config) uri = 'druby://:0' unless uri @@ -899,7 +899,7 @@ module DRb def peeraddr @socket.peeraddr end - + # Get the socket. def stream; @socket; end @@ -907,7 +907,7 @@ module DRb def send_request(ref, msg_id, arg, b) @msg.send_request(stream, ref, msg_id, arg, b) end - + # On the server side, receive a request from the client. def recv_request @msg.recv_request(stream) @@ -937,14 +937,14 @@ module DRb @socket = nil end end - - # On the server side, for an instance returned by #open_server, + + # 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. def accept while true s = @socket.accept - break if (@acl ? @acl.allow_socket?(s) : true) + break if (@acl ? @acl.allow_socket?(s) : true) s.close end if @config[:tcp_original_host].to_s.size == 0 @@ -981,16 +981,16 @@ module DRb end attr :option def to_s; @option; end - + def ==(other) return false unless DRbURIOption === other @option == other.option end - + def hash @option.hash end - + alias eql? == end @@ -1007,7 +1007,7 @@ module DRb # created to act as a stub for the remote referenced object. 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]) @@ -1057,7 +1057,7 @@ module DRb end # Get the URI of the remote object. - def __drburi + def __drburi @uri end @@ -1085,7 +1085,7 @@ module DRb 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) + return obj.__send__(msg_id, *a, &b) end succ, result = self.class.with_friend(@uri) do @@ -1108,7 +1108,7 @@ module DRb 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 @@ -1120,7 +1120,7 @@ module DRb prefix = "(#{uri}) " bt = [] result.backtrace.each do |x| - break if /`__send__'$/ =~ x + break if /`__send__'$/ =~ x if /^\(druby:\/\// =~ x bt.push(x) else @@ -1271,14 +1271,14 @@ module DRb def self.verbose=(on) @@verbose = on end - + # Get the default value of the :verbose option. def self.verbose @@verbose end def self.make_config(hash={}) # :nodoc: - default_config = { + default_config = { :idconv => @@idconv, :verbose => @@verbose, :tcp_acl => @@acl, @@ -1368,7 +1368,7 @@ module DRb attr_reader :thread # The front object of the DRbServer. - # + # # This object receives remote method calls made on the server's # URI alone, with an object id. attr_reader :front @@ -1461,7 +1461,7 @@ module DRb def any_to_s(obj) obj.to_s + ":#{obj.class}" rescue - sprintf("#<%s:0x%lx>", obj.class, obj.__id__) + sprintf("#<%s:0x%lx>", obj.class, obj.__id__) end # Check that a method is callable via dRuby. @@ -1469,14 +1469,14 @@ module DRb # +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 + # 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. 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) desc = any_to_s(obj) raise NoMethodError, "private method `#{msg_id}' called for #{desc}" @@ -1488,7 +1488,7 @@ module DRb end end public :check_insecure_method - + class InvokeMethod # :nodoc: def initialize(drb_server, client) @drb_server = drb_server @@ -1510,7 +1510,7 @@ module DRb perform_with_block }.value else - @result = Thread.new { + @result = Thread.new { Thread.current['DRb'] = info $SAFE = @safe_level perform_without_block @@ -1525,7 +1525,7 @@ module DRb end @succ = true if @msg_id == :to_ary && @result.class == Array - @result = DRbArray.new(@result) + @result = DRbArray.new(@result) end return @succ, @result rescue StandardError, ScriptError, Interrupt @@ -1541,7 +1541,7 @@ module DRb @argv = argv @block = block end - + def check_insecure_method @drb_server.check_insecure_method(@obj, @msg_id) end @@ -1550,7 +1550,7 @@ module DRb init_with_client check_insecure_method end - + def perform_without_block if Proc === @obj && @msg_id == :__drb_yield if @argv.size == 1 @@ -1638,7 +1638,7 @@ module DRb # The primary local dRuby server. # - # This is the server created by the #start_service call. + # This is the server created by the #start_service call. attr_accessor :primary_server module_function :primary_server=, :primary_server @@ -1653,8 +1653,8 @@ module DRb # If the above rule fails to find a server, a DRbServerNotFound # error is raised. def current_server - drb = Thread.current['DRb'] - server = (drb && drb['server']) ? drb['server'] : @primary_server + drb = Thread.current['DRb'] + server = (drb && drb['server']) ? drb['server'] : @primary_server raise DRbServerNotFound unless server return server end @@ -1700,7 +1700,7 @@ module DRb DRbServer.make_config end module_function :config - + # Get the front object of the current server. # # This raises a DRbServerNotFound error if there is no current server. @@ -1771,7 +1771,7 @@ module DRb @server.delete(server.uri) end module_function :remove_server - + def fetch_server(uri) @server[uri] end diff --git a/lib/drb/extserv.rb b/lib/drb/extserv.rb index af52250518..5996626492 100644 --- a/lib/drb/extserv.rb +++ b/lib/drb/extserv.rb @@ -1,6 +1,6 @@ =begin external service - Copyright (c) 2000,2002 Masatoshi SEKI + Copyright (c) 2000,2002 Masatoshi SEKI =end require 'drb/drb' diff --git a/lib/drb/extservm.rb b/lib/drb/extservm.rb index 3b1819e834..5937cb0c50 100644 --- a/lib/drb/extservm.rb +++ b/lib/drb/extservm.rb @@ -1,6 +1,6 @@ =begin external service manager - Copyright (c) 2000 Masatoshi SEKI + Copyright (c) 2000 Masatoshi SEKI =end require 'drb/drb' @@ -21,7 +21,7 @@ module DRb def self.command=(cmd) @@command = cmd end - + def initialize super() @cond = new_cond @@ -51,7 +51,7 @@ module DRb end self end - + def unregist(name) synchronize do @servers.delete(name) diff --git a/lib/drb/invokemethod.rb b/lib/drb/invokemethod.rb index 7da8ace88d..220d0ad68d 100644 --- a/lib/drb/invokemethod.rb +++ b/lib/drb/invokemethod.rb @@ -9,7 +9,7 @@ module DRb end block_value = @block.call(*x) end - + def perform_with_block @obj.__send__(@msg_id, *@argv) do |*x| jump_error = nil diff --git a/lib/drb/ssl.rb b/lib/drb/ssl.rb index 58d6b7d1e0..08f97f4bc6 100644 --- a/lib/drb/ssl.rb +++ b/lib/drb/ssl.rb @@ -15,7 +15,7 @@ module DRb :SSLClientCA => nil, :SSLCACertificatePath => nil, :SSLCACertificateFile => nil, - :SSLVerifyMode => ::OpenSSL::SSL::VERIFY_NONE, + :SSLVerifyMode => ::OpenSSL::SSL::VERIFY_NONE, :SSLVerifyDepth => nil, :SSLVerifyCallback => nil, # custom verification :SSLCertificateStore => nil, @@ -31,7 +31,7 @@ module DRb @ssl_ctx = nil end - def [](key); + def [](key); @config[key] || DEFAULT[key] end @@ -41,14 +41,14 @@ module DRb ssl.connect ssl end - + def accept(tcp) ssl = OpenSSL::SSL::SSLSocket.new(tcp, @ssl_ctx) ssl.sync = true ssl.accept ssl end - + def setup_certificate if @cert && @pkey return @@ -77,7 +77,7 @@ module DRb 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"), @@ -89,7 +89,7 @@ module DRb cert.add_extension(ef.create_extension("nsComment", comment)) end cert.sign(rsa, OpenSSL::Digest::SHA1.new) - + @cert = cert @pkey = rsa end @@ -143,7 +143,7 @@ module DRb 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 @@ -159,7 +159,7 @@ module DRb @ssl = is_established ? soc : nil super(uri, soc.to_io, config) end - + def stream; @ssl; end def close @@ -169,12 +169,12 @@ module DRb end super end - + def accept begin while true soc = @socket.accept - break if (@acl ? @acl.allow_socket?(soc) : true) + break if (@acl ? @acl.allow_socket?(soc) : true) soc.close end ssl = @config.accept(soc) @@ -185,6 +185,6 @@ module DRb end end end - + DRbProtocol.add_protocol(DRbSSLSocket) end diff --git a/lib/drb/timeridconv.rb b/lib/drb/timeridconv.rb index bb2c48d528..6d8935b1ef 100644 --- a/lib/drb/timeridconv.rb +++ b/lib/drb/timeridconv.rb @@ -19,7 +19,7 @@ module DRb end def add(obj) - synchronize do + synchronize do key = obj.__id__ @curr[key] = obj return key @@ -27,7 +27,7 @@ module DRb end def fetch(key, dv=@sentinel) - synchronize do + synchronize do obj = peek(key) if obj == @sentinel return dv unless dv == @sentinel @@ -39,7 +39,7 @@ module DRb end def include?(key) - synchronize do + synchronize do obj = peek(key) return false if obj == @sentinel true @@ -47,7 +47,7 @@ module DRb end def peek(key) - synchronize do + synchronize do return @curr.fetch(key, @renew.fetch(key, @gc.fetch(key, @sentinel))) end end diff --git a/lib/drb/unix.rb b/lib/drb/unix.rb index 57feed8301..ebecc22901 100644 --- a/lib/drb/unix.rb +++ b/lib/drb/unix.rb @@ -8,7 +8,7 @@ module DRb class DRbUNIXSocket < DRbTCPSocket def self.parse_uri(uri) - if /^drbunix:(.*?)(\?(.*))?$/ =~ uri + if /^drbunix:(.*?)(\?(.*))?$/ =~ uri filename = $1 option = $3 [filename, option] @@ -59,7 +59,7 @@ module DRb @server_mode = server_mode @acl = nil end - + # import from tempfile.rb Max_try = 10 private diff --git a/lib/e2mmap.rb b/lib/e2mmap.rb index b8d1d44f38..ac2fb2dd49 100644 --- a/lib/e2mmap.rb +++ b/lib/e2mmap.rb @@ -56,7 +56,7 @@ module Exception2MessageMapper super cl.bind(self) unless cl < E2MM end - + def bind(cl) self.module_eval %[ def Raise(err = nil, *rest) @@ -88,7 +88,7 @@ module Exception2MessageMapper def def_e2message(c, m) E2MM.def_e2message(self, c, m) end - + # def_exception(n, m, s) # n: exception_name # m: message_form @@ -115,7 +115,7 @@ module Exception2MessageMapper E2MM.instance_eval{@MessageMap[[k, c]] = m} c end - + # E2MM.def_exception(k, n, m, s) # k: class to define exception under. # n: exception_name @@ -164,8 +164,8 @@ module Exception2MessageMapper alias message e2mm_message end - E2MM.def_exception(E2MM, - :ErrNotRegisteredException, + E2MM.def_exception(E2MM, + :ErrNotRegisteredException, "not registerd exception(%s)") end diff --git a/lib/erb.rb b/lib/erb.rb index 678f082b07..5e9feb9ba5 100644 --- a/lib/erb.rb +++ b/lib/erb.rb @@ -20,7 +20,7 @@ # purposes of generating document information details and/or flow control. # # A very simple example is this: -# +# # require 'erb' # # x = 42 @@ -86,39 +86,39 @@ # <tt>%q{...}</tt> to avoid trouble with the backslash. # # require "erb" -# +# # # Create template. # template = %q{ # From: James Edward Gray II <[email protected]> # 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 @@ -128,19 +128,19 @@ # From: James Edward Gray II <[email protected]> # 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 @@ -150,7 +150,7 @@ # variables in the Product object can be resolved. # # require "erb" -# +# # # Build template data class. # class Product # def initialize( code, name, desc, cost ) @@ -158,37 +158,37 @@ # @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> @@ -196,13 +196,13 @@ # Call for a price, today! # <% end %> # </p> -# +# # </body> # </html> # }.gsub(/^ /, '') -# +# # rhtml = ERB.new(template) -# +# # # Set up template data. # toy = Product.new( "TZ-1002", # "Rubysapien", @@ -213,7 +213,7 @@ # 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) # @@ -222,10 +222,10 @@ # <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> @@ -233,15 +233,15 @@ # <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: @@ -318,7 +318,7 @@ class ERB end end attr_accessor :stag - + def scan(&block) @stag = nil if @percent @@ -425,7 +425,7 @@ class ERB end end end - + Scanner.regist_scanner(SimpleScanner, nil, false) begin @@ -484,13 +484,13 @@ class ERB def push(cmd) @line << cmd end - + def cr @script << (@line.join('; ')) @line = [] @script << "\n" end - + def close return unless @line @compiler.post_cmd.each do |x| @@ -520,7 +520,7 @@ class ERB content = '' scanner = make_scanner(s) scanner.scan do |token| - next if token.nil? + next if token.nil? next if token == '' if scanner.stag.nil? case token @@ -632,19 +632,19 @@ end class ERB # # 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 <b>$SAFE</b> 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 @@ -653,20 +653,20 @@ class ERB # === 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 variables @@ -680,21 +680,21 @@ class ERB # 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. - # + # def initialize(str, safe_level=nil, trim_mode=nil, eoutvar='_erbout') @safe_level = safe_level compiler = ERB::Compiler.new(trim_mode) @@ -721,7 +721,7 @@ class ERB cmd = [] cmd.push "#{eoutvar} = ''" - + compiler.pre_cmd = cmd cmd = [] @@ -739,13 +739,13 @@ class ERB # 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. # def result(b=TOPLEVEL_BINDING) if @safe_level - proc { + proc { $SAFE = @safe_level eval(@src, b, (@filename || '(erb)'), 0) }.call @@ -813,14 +813,14 @@ class ERB public # # 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 > 0 & a < 10? # def html_escape(s) @@ -829,17 +829,17 @@ class ERB alias h html_escape module_function :h module_function :html_escape - + # # 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 # def url_encode(s) diff --git a/lib/fileutils.rb b/lib/fileutils.rb index 32408ee868..f2302703be 100644 --- a/lib/fileutils.rb +++ b/lib/fileutils.rb @@ -1,17 +1,17 @@ -# +# # = fileutils.rb -# +# # Copyright (c) 2000-2007 Minero Aoki -# +# # This program is free software. # You can distribute/modify this program under the same terms of ruby. -# +# # == module FileUtils -# +# # Namespace for several file utility methods for copying, moving, removing, etc. -# +# # === Module Functions -# +# # cd(dir, options) # cd(dir, options) {|dir| .... } # pwd() @@ -64,23 +64,23 @@ # 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 <tt>:verbose</tt> 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 <tt>:noop</tt> 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 <tt>:noop</tt> and # <tt>:verbose</tt> flags to methods in FileUtils. -# +# module FileUtils @@ -107,14 +107,14 @@ module FileUtils # # 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 - # + # def cd(dir, options = {}, &block) # :yield: dir fu_check_options options, OPT_TABLE['cd'] fu_output_message "cd #{dir}" if options[:verbose] @@ -131,13 +131,13 @@ module FileUtils # # 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' - # + # def uptodate?(new, old_list, options = nil) raise ArgumentError, 'uptodate? does not accept any option' if options @@ -154,14 +154,14 @@ module FileUtils # # 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 - # + # def mkdir(list, options = {}) fu_check_options options, OPT_TABLE['mkdir'] list = fu_list(list) @@ -178,12 +178,12 @@ module FileUtils # # 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 @@ -191,7 +191,7 @@ module FileUtils # * /usr/local/lib/ruby # # You can pass several directories at a time in a list. - # + # def mkdir_p(list, options = {}) fu_check_options options, OPT_TABLE['mkdir_p'] list = fu_list(list) @@ -247,14 +247,14 @@ module FileUtils # # 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 - # + # def rmdir(list, options = {}) fu_check_options options, OPT_TABLE['rmdir'] list = fu_list(list) @@ -286,19 +286,19 @@ module FileUtils # If +new+ already exists and it is a directory, creates a link +new/old+. # If +new+ already exists and it is not a directory, raises Errno::EEXIST. # But if :force option is set, overwrite +new+. - # + # # FileUtils.ln 'gcc', 'cc', :verbose => true # FileUtils.ln '/usr/bin/emacs21', '/usr/bin/emacs' - # + # # <b><tt>ln(list, destdir, options = {})</tt></b> - # + # # 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. - # + # def ln(src, dest, options = {}) fu_check_options options, OPT_TABLE['ln'] fu_output_message "ln#{options[:force] ? ' -f' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose] @@ -320,24 +320,24 @@ module FileUtils # Options: force noop verbose # # <b><tt>ln_s(old, new, options = {})</tt></b> - # + # # 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 - # + # # <b><tt>ln_s(list, destdir, options = {})</tt></b> - # + # # 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' - # + # def ln_s(src, dest, options = {}) fu_check_options options, OPT_TABLE['ln_s'] fu_output_message "ln -s#{options[:force] ? 'f' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose] @@ -357,10 +357,10 @@ module FileUtils # # Options: noop verbose - # + # # Same as # #ln_s(src, dest, :force) - # + # def ln_sf(src, dest, options = {}) fu_check_options options, OPT_TABLE['ln_sf'] options = options.dup @@ -383,7 +383,7 @@ module FileUtils # 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 - # + # def cp(src, dest, options = {}) fu_check_options options, OPT_TABLE['cp'] fu_output_message "cp#{options[:preserve] ? ' -p' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose] @@ -402,17 +402,17 @@ module FileUtils # # Options: preserve noop verbose dereference_root remove_destination - # + # # Copies +src+ to +dest+. If +src+ is a directory, this method copies # all its contents recursively. If +dest+ is a directory, copies # +src+ to +dest/src+. # # +src+ can be a list of files. - # + # # # Installing ruby library "mylib" under the site_ruby # FileUtils.rm_r site_ruby + '/mylib', :force # FileUtils.cp_r 'lib/', site_ruby + '/mylib' - # + # # # Examples of copying several files to target directory. # FileUtils.cp_r %w(mail.rb field.rb debug/), site_ruby + '/tmail' # FileUtils.cp_r Dir.glob('*.rb'), '/home/aamine/lib/ruby', :noop => true, :verbose => true @@ -422,7 +422,7 @@ module FileUtils # # use following code. # FileUtils.cp_r 'src/.', 'dest' # cp_r('src', 'dest') makes src/dest, # # but this doesn't. - # + # def cp_r(src, dest, options = {}) fu_check_options options, OPT_TABLE['cp_r'] fu_output_message "cp -r#{options[:preserve] ? 'p' : ''}#{options[:remove_destination] ? ' --remove-destination' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose] @@ -485,16 +485,16 @@ module FileUtils # # Options: force noop verbose - # + # # Moves file(s) +src+ to +dest+. If +file+ and +dest+ exist on the different # disk partition, the file is copied then the original file is removed. - # + # # 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 - # + # def mv(src, dest, options = {}) fu_check_options options, OPT_TABLE['mv'] fu_output_message "mv#{options[:force] ? ' -f' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose] @@ -539,14 +539,14 @@ module FileUtils # # 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 - # + # def rm(list, options = {}) fu_check_options options, OPT_TABLE['rm'] list = fu_list(list) @@ -567,7 +567,7 @@ module FileUtils # # Options: noop verbose - # + # # Equivalent to # # #rm(list, :force => true) @@ -588,11 +588,11 @@ module FileUtils # # 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 # :-) # @@ -606,7 +606,7 @@ module FileUtils # # NOTE: This method calls #remove_entry_secure if :secure option is set. # See also #remove_entry_secure. - # + # def rm_r(list, options = {}) fu_check_options options, OPT_TABLE['rm_r'] # options[:secure] = true unless options.key?(:secure) @@ -627,14 +627,14 @@ module FileUtils # # Options: noop verbose secure - # + # # Equivalent to # # #rm_r(list, :force => true) # # WARNING: This method causes local vulnerability. # Read the documentation of #rm_r first. - # + # def rm_rf(list, options = {}) fu_check_options options, OPT_TABLE['rm_rf'] options = options.dup @@ -788,7 +788,7 @@ module FileUtils # # 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 # @@ -828,14 +828,14 @@ module FileUtils # # Options: mode preserve noop verbose - # + # # If +src+ is not same as +dest+, copies it and changes the permission # mode to +mode+. If +dest+ is a directory, destination is +dest+/+src+. # This method removes destination before copy. - # + # # FileUtils.install 'ruby', '/usr/local/bin/ruby', :mode => 0755, :verbose => true # FileUtils.install 'lib.rb', '/usr/local/lib/ruby/site_ruby', :verbose => true - # + # def install(src, dest, options = {}) fu_check_options options, OPT_TABLE['install'] fu_output_message "install -c#{options[:preserve] && ' -p'}#{options[:mode] ? (' -m 0%o' % options[:mode]) : ''} #{[src,dest].flatten.join ' '}" if options[:verbose] @@ -856,14 +856,14 @@ module FileUtils # # 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 - # + # def chmod(mode, list, options = {}) fu_check_options options, OPT_TABLE['chmod'] list = fu_list(list) @@ -879,12 +879,12 @@ module FileUtils # # 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.#{$$}" - # + # def chmod_R(mode, list, options = {}) fu_check_options options, OPT_TABLE['chmod_R'] list = fu_list(list) @@ -908,16 +908,16 @@ module FileUtils # # 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 - # + # def chown(user, group, list, options = {}) fu_check_options options, OPT_TABLE['chown'] list = fu_list(list) @@ -937,16 +937,16 @@ module FileUtils # # 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 - # + # def chown_R(user, group, list, options = {}) fu_check_options options, OPT_TABLE['chown_R'] list = fu_list(list) @@ -1010,13 +1010,13 @@ module FileUtils # # 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' - # + # def touch(list, options = {}) fu_check_options options, OPT_TABLE['touch'] list = fu_list(list) @@ -1510,11 +1510,11 @@ module FileUtils METHODS = singleton_methods() - [:private_module_function, :commands, :options, :have_option?, :options_of, :collect_method] - # + # # This module has all methods of FileUtils module, but it outputs messages # before acting. This equates to passing the <tt>:verbose</tt> flag to # methods in FileUtils. - # + # module Verbose include FileUtils @fileutils_output = $stderr @@ -1535,11 +1535,11 @@ module FileUtils end end - # + # # This module has all methods of FileUtils module, but never changes # files/directories. This equates to passing the <tt>:noop</tt> flag # to methods in FileUtils. - # + # module NoWrite include FileUtils @fileutils_output = $stderr @@ -1560,12 +1560,12 @@ module FileUtils end end - # + # # This module has all methods of FileUtils module, but never changes # files/directories, with printing message before acting. # This equates to passing the <tt>:noop</tt> and <tt>:verbose</tt> flag # to methods in FileUtils. - # + # module DryRun include FileUtils @fileutils_output = $stderr diff --git a/lib/forwardable.rb b/lib/forwardable.rb index 59a760db45..39b35d9cee 100644 --- a/lib/forwardable.rb +++ b/lib/forwardable.rb @@ -1,5 +1,5 @@ # -# forwardable.rb - +# forwardable.rb - # $Release Version: 1.1$ # $Revision$ # by Keiju ISHITSUKA([email protected]) @@ -33,28 +33,28 @@ # # class Queue # extend Forwardable -# +# # def initialize # @q = [ ] # prepare delegate object # end -# +# # # setup preferred 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 @@ -90,9 +90,9 @@ # # If you want to use both Forwardable and SingleForwardable, you can # use methods def_instance_delegator and def_single_delegator, etc. -# +# # If the object isn't a Module and Class, You can too extend -# Forwardable module. +# Forwardable module. # printer = String.new # printer.extend Forwardable # prepare object for delegation # printer.def_delegator "STDOUT", "puts" # add delegation for STDOUT.puts() diff --git a/lib/getoptlong.rb b/lib/getoptlong.rb index 4cfb5fbd27..c5e60ec188 100644 --- a/lib/getoptlong.rb +++ b/lib/getoptlong.rb @@ -12,10 +12,10 @@ # found at http://www.sra.co.jp/people/m-kasahr/ruby/getoptlong/ # The GetoptLong class allows you to parse command line options similarly to -# the GNU getopt_long() C library call. Note, however, that GetoptLong is a +# the GNU getopt_long() C library call. Note, however, that GetoptLong is a # pure Ruby implementation. # -# GetoptLong allows for POSIX-style options like <tt>--file</tt> as well +# GetoptLong allows for POSIX-style options like <tt>--file</tt> as well # as single letter options like <tt>-f</tt> # # The empty option <tt>--</tt> (two minus symbols) is used to end option @@ -26,13 +26,13 @@ # # require 'getoptlong' # require 'rdoc/usage' -# +# # opts = GetoptLong.new( # [ '--help', '-h', GetoptLong::NO_ARGUMENT ], # [ '--repeat', '-n', GetoptLong::REQUIRED_ARGUMENT ], # [ '--name', GetoptLong::OPTIONAL_ARGUMENT ] # ) -# +# # dir = nil # name = nil # repetitions = 1 @@ -41,16 +41,16 @@ # when '--help' # puts <<-EOF # hello [OPTION] ... DIR -# +# # -h, --help: # show help -# +# # --repeat x, -n x: # repeat x times -# +# # --name [name]: # greet user by name, if name not supplied default is John -# +# # DIR: The directory in which to issue the greeting. # EOF # when '--repeat' @@ -63,12 +63,12 @@ # end # end # end -# +# # if ARGV.length != 1 # puts "Missing dir argument (try --help)" # exit 0 # end -# +# # dir = ARGV.shift # # Dir.chdir(dir) @@ -114,7 +114,7 @@ class GetoptLong # Set up option processing. # # The options to support are passed to new() as an array of arrays. - # Each sub-array contains any number of String option names which carry + # Each sub-array contains any number of String option names which carry # the same meaning, and one of the following flags: # # GetoptLong::NO_ARGUMENT :: Option does not take an argument. @@ -194,23 +194,23 @@ class GetoptLong # the processing of options as follows: # # <b>REQUIRE_ORDER</b> : - # + # # Options are required to occur before non-options. # # Processing of options ends as soon as a word is encountered that has not # been preceded by an appropriate option flag. # # For example, if -a and -b are options which do not take arguments, - # parsing command line arguments of '-a one -b two' would result in - # 'one', '-b', 'two' being left in ARGV, and only ('-a', '') being + # parsing command line arguments of '-a one -b two' would result in + # 'one', '-b', 'two' being left in ARGV, and only ('-a', '') being # processed as an option/arg pair. # # This is the default ordering, if the environment variable # POSIXLY_CORRECT is set. (This is for compatibility with GNU getopt_long.) # # <b>PERMUTE</b> : - # - # Options can occur anywhere in the command line parsed. This is the + # + # Options can occur anywhere in the command line parsed. This is the # default behavior. # # Every sequence of words which can be interpreted as an option (with or @@ -227,7 +227,7 @@ class GetoptLong # # <b>RETURN_IN_ORDER</b> : # - # All words on the command line are processed as options. Words not + # All words on the command line are processed as options. Words not # preceded by a short or long option flag are passed as arguments # with an option of '' (empty string). # @@ -273,7 +273,7 @@ class GetoptLong # The method is failed if option processing has already started. # if @status != STATUS_YET - raise RuntimeError, + raise RuntimeError, "invoke set_options, but option processing has already started" end @@ -320,7 +320,7 @@ class GetoptLong end # - # Register the option (`i') to the `@canonical_names' and + # Register the option (`i') to the `@canonical_names' and # `@canonical_names' Hashes. # if canonical_name == nil @@ -452,7 +452,7 @@ class GetoptLong return nil end argument = ARGV.shift - elsif @ordering == REQUIRE_ORDER + elsif @ordering == REQUIRE_ORDER if (ARGV[0] !~ /^-./) terminate return nil @@ -589,7 +589,7 @@ class GetoptLong # # The block is called repeatedly with two arguments: # The first is the option name. - # The second is the argument which followed it (if any). + # The second is the argument which followed it (if any). # Example: ('--opt', 'value') # # The option name is always converted to the first (preferred) diff --git a/lib/gserver.rb b/lib/gserver.rb index 592e8661fe..2ab6e42bce 100644 --- a/lib/gserver.rb +++ b/lib/gserver.rb @@ -13,7 +13,7 @@ require "thread" # # GServer implements a generic server, featuring thread pool management, -# simple logging, and multi-server management. See HttpServer in +# simple logging, and multi-server management. See HttpServer in # <tt>xmlrpc/httpserver.rb</tt> in the Ruby standard library for an example of # GServer in action. # @@ -34,7 +34,7 @@ require "thread" # # # # # A server that returns the time in seconds since 1970. -# # +# # # class TimeServer < GServer # def initialize(port=10001, *args) # super(port, *args) @@ -47,17 +47,17 @@ require "thread" # # Run the server with logging enabled (it's a separate thread). # server = TimeServer.new # server.audit = true # Turn logging on. -# server.start +# server.start # # # *** Now point your browser to http://localhost:10001 to see it working *** # -# # See if it's still running. +# # 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". diff --git a/lib/ipaddr.rb b/lib/ipaddr.rb index 26364cd9ce..21c8787f80 100644 --- a/lib/ipaddr.rb +++ b/lib/ipaddr.rb @@ -66,19 +66,19 @@ end # == 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> class IPAddr @@ -425,7 +425,7 @@ class IPAddr # Creates a new ipaddr object either from a human readable IP # address representation in string, or from a packed in_addr value # followed by an address family. - # + # # In the former case, the following are the valid formats that will # be recognized: "address", "address/prefixlen" and "address/mask", # where IPv6 address may be enclosed in square brackets (`[' and @@ -433,7 +433,7 @@ class IPAddr # IP address. Although the address family is determined # automatically from a specified string, you can specify one # explicitly by the optional second argument. - # + # # Otherwise an IP addess is generated from a packed in_addr value # and an address family. # diff --git a/lib/irb.rb b/lib/irb.rb index f5e662ac51..119e1a45d8 100644 --- a/lib/irb.rb +++ b/lib/irb.rb @@ -64,7 +64,7 @@ module IRB trap("SIGINT") do irb.signal_handle end - + catch(:IRB_EXIT) do irb.eval_input end @@ -84,7 +84,7 @@ module IRB end # - # irb interpreter main routine + # irb interpreter main routine # class Irb def initialize(workspace = nil, input_method = nil, output_method = nil) @@ -125,7 +125,7 @@ module IRB end end end - + @scanner.set_input(@context.io) do signal_status(:IN_INPUT) do if l = @context.io.gets @@ -158,7 +158,7 @@ module IRB print exc.class, ": ", exc, "\n" if exc.backtrace[0] =~ /irb(2)?(\/.*|-.*|\.rb)?:/ && exc.class.to_s !~ /^IRB/ && !(SyntaxError === exc) - irb_bug = true + irb_bug = true else irb_bug = false end @@ -174,7 +174,7 @@ module IRB else lasts.push "\tfrom "+m if lasts.size > @context.back_trace_limit - lasts.shift + lasts.shift levels += 1 end end @@ -279,13 +279,13 @@ module IRB when "l" ltype when "i" - if $1 + if $1 format("%" + $1 + "d", indent) else indent.to_s end when "n" - if $1 + if $1 format("%" + $1 + "d", line_no) else line_no.to_s diff --git a/lib/irb/cmd/chws.rb b/lib/irb/cmd/chws.rb index c2db7e5d91..e225b52585 100644 --- a/lib/irb/cmd/chws.rb +++ b/lib/irb/cmd/chws.rb @@ -1,12 +1,12 @@ # -# change-ws.rb - +# change-ws.rb - # $Release Version: 0.9.5$ # $Revision$ # by Keiju ISHITSUKA([email protected]) # # -- # -# +# # require "irb/cmd/nop.rb" diff --git a/lib/irb/cmd/fork.rb b/lib/irb/cmd/fork.rb index 6f4133c047..534f13f56a 100644 --- a/lib/irb/cmd/fork.rb +++ b/lib/irb/cmd/fork.rb @@ -1,12 +1,12 @@ # -# fork.rb - +# fork.rb - # $Release Version: 0.9.5 $ # $Revision$ # by Keiju ISHITSUKA([email protected]) # # -- # -# +# # @RCS_ID='-$Id$-' @@ -17,7 +17,7 @@ module IRB class Fork<Nop def execute(&block) pid = send ExtendCommand.irb_original_method_name("fork") - unless pid + unless pid class<<self alias_method :exit, ExtendCommand.irb_original_method_name('exit') end diff --git a/lib/irb/cmd/help.rb b/lib/irb/cmd/help.rb index e1f47e2c97..146acdfa81 100644 --- a/lib/irb/cmd/help.rb +++ b/lib/irb/cmd/help.rb @@ -5,7 +5,7 @@ # # -- # -# +# # require 'rdoc/ri/driver' diff --git a/lib/irb/cmd/load.rb b/lib/irb/cmd/load.rb index cda9a053fe..5988b7bbd1 100644 --- a/lib/irb/cmd/load.rb +++ b/lib/irb/cmd/load.rb @@ -1,12 +1,12 @@ # -# load.rb - +# load.rb - # $Release Version: 0.9.5$ # $Revision$ # by Keiju ISHITSUKA([email protected]) # # -- # -# +# # require "irb/cmd/nop.rb" @@ -25,7 +25,7 @@ module IRB class Require<Nop include IrbLoader - + def execute(file_name) # return ruby_require(file_name) unless IRB.conf[:USE_LOADER] @@ -44,7 +44,7 @@ module IRB when /\.(so|o|sl)$/ return ruby_require(file_name) end - + begin irb_load(f = file_name + ".rb") $".push f diff --git a/lib/irb/cmd/nop.rb b/lib/irb/cmd/nop.rb index 0b68098d4f..873c0f43f4 100644 --- a/lib/irb/cmd/nop.rb +++ b/lib/irb/cmd/nop.rb @@ -1,17 +1,17 @@ # -# nop.rb - +# nop.rb - # $Release Version: 0.9.5$ # $Revision$ # by Keiju ISHITSUKA([email protected]) # # -- # -# +# # module IRB module ExtendCommand class Nop - + @RCS_ID='-$Id$-' def self.execute(conf, *opts) diff --git a/lib/irb/cmd/pushws.rb b/lib/irb/cmd/pushws.rb index b5b41501af..a82939f39d 100644 --- a/lib/irb/cmd/pushws.rb +++ b/lib/irb/cmd/pushws.rb @@ -1,12 +1,12 @@ # -# change-ws.rb - +# change-ws.rb - # $Release Version: 0.9.5$ # $Revision$ # by Keiju ISHITSUKA([email protected]) # # -- # -# +# # require "irb/cmd/nop.rb" diff --git a/lib/irb/cmd/subirb.rb b/lib/irb/cmd/subirb.rb index 5eccf9f2c1..bf41ec50cc 100644 --- a/lib/irb/cmd/subirb.rb +++ b/lib/irb/cmd/subirb.rb @@ -1,13 +1,13 @@ #!/usr/local/bin/ruby # -# multi.rb - +# multi.rb - # $Release Version: 0.9.5$ # $Revision$ # by Keiju ISHITSUKA([email protected]) # # -- # -# +# # require "irb/cmd/nop.rb" diff --git a/lib/irb/completion.rb b/lib/irb/completion.rb index 26339f217d..a31bee0c76 100644 --- a/lib/irb/completion.rb +++ b/lib/irb/completion.rb @@ -1,5 +1,5 @@ # -# irb/completor.rb - +# irb/completor.rb - # $Release Version: 0.9$ # $Revision$ # by Keiju ISHITSUKA([email protected]) @@ -15,16 +15,16 @@ module IRB ReservedWords = [ "BEGIN", "END", - "alias", "and", - "begin", "break", + "alias", "and", + "begin", "break", "case", "class", "def", "defined", "do", "else", "elsif", "end", "ensure", - "false", "for", - "if", "in", - "module", + "false", "for", + "if", "in", + "module", "next", "nil", "not", - "or", + "or", "redo", "rescue", "retry", "return", "self", "super", "then", "true", @@ -32,10 +32,10 @@ module IRB "when", "while", "yield", ] - + CompletionProc = proc { |input| bind = IRB.conf[:MAIN_CONTEXT].workspace.binding - + # puts "input: #{input}" case input @@ -63,7 +63,7 @@ module IRB candidates = Proc.instance_methods.collect{|m| m.to_s} candidates |= Hash.instance_methods.collect{|m| m.to_s} select_message(receiver, message, candidates) - + when /^(:[^:.]*)$/ # Symbol if Symbol.respond_to?(:all_symbols) @@ -137,7 +137,7 @@ module IRB gv = eval("global_variables", bind).collect{|m| m.to_s} lv = eval("local_variables", bind).collect{|m| m.to_s} cv = eval("self.class.constants", bind).collect{|m| m.to_s} - + if (gv | lv | cv).include?(receiver) # foo.func and foo is local var. candidates = eval("#{receiver}.methods", bind).collect{|m| m.to_s} @@ -157,7 +157,7 @@ module IRB rescue Exception name = "" end - next if name != "IRB::Context" and + next if name != "IRB::Context" and /^(IRB|SLex|RubyLex|RubyToken)/ =~ name candidates.concat m.instance_methods(false).collect{|x| x.to_s} } @@ -177,7 +177,7 @@ module IRB else candidates = eval("methods | private_methods | local_variables | self.class.constants", bind).collect{|m| m.to_s} - + (candidates|ReservedWords).grep(/^#{Regexp.quote(input)}/) end } diff --git a/lib/irb/context.rb b/lib/irb/context.rb index e2ab05a341..a3f5e5a79c 100644 --- a/lib/irb/context.rb +++ b/lib/irb/context.rb @@ -6,7 +6,7 @@ # # -- # -# +# # require "irb/workspace" @@ -45,7 +45,7 @@ module IRB @ignore_eof = IRB.conf[:IGNORE_EOF] @back_trace_limit = IRB.conf[:BACK_TRACE_LIMIT] - + self.prompt_mode = IRB.conf[:PROMPT_MODE] if IRB.conf[:SINGLE_IRB] or !defined?(JobManager) @@ -90,7 +90,7 @@ module IRB @output_method = StdioOutputMethod.new end - @verbose = IRB.conf[:VERBOSE] + @verbose = IRB.conf[:VERBOSE] @echo = IRB.conf[:ECHO] if @echo.nil? @echo = true @@ -106,7 +106,7 @@ module IRB attr_accessor :workspace attr_reader :thread attr_accessor :io - + attr_accessor :irb attr_accessor :ap_name attr_accessor :rc @@ -141,7 +141,7 @@ module IRB def verbose? if @verbose.nil? - if defined?(ReadlineInputMethod) && @io.kind_of?(ReadlineInputMethod) + if defined?(ReadlineInputMethod) && @io.kind_of?(ReadlineInputMethod) false elsif !STDIN.tty? or @io.kind_of?(FileInputMethod) true @@ -179,7 +179,7 @@ module IRB @auto_indent_mode = IRB.conf[:AUTO_INDENT] end end - + def inspect? @inspect_mode.nil? or @inspect_mode end diff --git a/lib/irb/ext/change-ws.rb b/lib/irb/ext/change-ws.rb index 217d4a58ef..3ae1eab7a4 100644 --- a/lib/irb/ext/change-ws.rb +++ b/lib/irb/ext/change-ws.rb @@ -1,12 +1,12 @@ # -# irb/ext/cb.rb - +# irb/ext/cb.rb - # $Release Version: 0.9.5$ # $Revision$ # by Keiju ISHITSUKA([email protected]) # # -- # -# +# # module IRB @@ -22,12 +22,12 @@ module IRB def change_workspace(*_main) if _main.empty? - @workspace = home_workspace + @workspace = home_workspace return main end - + @workspace = WorkSpace.new(_main[0]) - + if !(class<<main;ancestors;end).include?(ExtendCommandBundle) main.extend ExtendCommandBundle end diff --git a/lib/irb/ext/history.rb b/lib/irb/ext/history.rb index a12700ce19..9142146c42 100644 --- a/lib/irb/ext/history.rb +++ b/lib/irb/ext/history.rb @@ -1,12 +1,12 @@ # -# history.rb - +# history.rb - # $Release Version: 0.9.5$ # $Revision$ # by Keiju ISHITSUKA([email protected]) # # -- # -# +# # module IRB @@ -56,7 +56,7 @@ module IRB end def size(size) - if size != 0 && size < @size + if size != 0 && size < @size @contents = @contents[@size - size .. @size] end @size = size @@ -78,7 +78,7 @@ module IRB @contents.push [no, val] @contents.shift if @size != 0 && @contents.size > @size end - + alias real_inspect inspect def inspect diff --git a/lib/irb/ext/loader.rb b/lib/irb/ext/loader.rb index 2d4400caef..cee8f51cc9 100644 --- a/lib/irb/ext/loader.rb +++ b/lib/irb/ext/loader.rb @@ -1,12 +1,12 @@ # -# loader.rb - +# loader.rb - # $Release Version: 0.9.5$ # $Revision$ # by Keiju ISHITSUKA([email protected]) # # -- # -# +# # @@ -44,7 +44,7 @@ module IRB irb.suspend_name(path, File.basename(path)) do irb.suspend_input_method(FileInputMethod.new(path)) do |back_io| - irb.signal_status(:IN_LOAD) do + irb.signal_status(:IN_LOAD) do if back_io.kind_of?(FileInputMethod) irb.eval_input else @@ -61,7 +61,7 @@ module IRB def load_file(path, priv = nil) irb.suspend_name(path, File.basename(path)) do - + if priv ws = WorkSpace.new(Module.new) else @@ -70,7 +70,7 @@ module IRB irb.suspend_workspace(ws) do irb.suspend_input_method(FileInputMethod.new(path)) do |back_io| - irb.signal_status(:IN_LOAD) do + irb.signal_status(:IN_LOAD) do # p irb.conf if back_io.kind_of?(FileInputMethod) irb.eval_input diff --git a/lib/irb/ext/math-mode.rb b/lib/irb/ext/math-mode.rb index 450a21eff7..370fab229d 100644 --- a/lib/irb/ext/math-mode.rb +++ b/lib/irb/ext/math-mode.rb @@ -1,12 +1,12 @@ # -# math-mode.rb - +# math-mode.rb - # $Release Version: 0.9.5$ # $Revision$ # by Keiju ISHITSUKA([email protected]) # # -- # -# +# # require "mathn" diff --git a/lib/irb/ext/multi-irb.rb b/lib/irb/ext/multi-irb.rb index d32d41ff95..5085a3f272 100644 --- a/lib/irb/ext/multi-irb.rb +++ b/lib/irb/ext/multi-irb.rb @@ -6,7 +6,7 @@ # # -- # -# +# # IRB.fail CantShiftToMultiIrbMode unless defined?(Thread) require "thread" @@ -66,7 +66,7 @@ module IRB IRB.fail IrbAlreadyDead unless th.alive? th.exit end - end + end def search(key) job = case key @@ -123,8 +123,8 @@ module IRB t_status = "exited" end ary.push format("#%d->%s on %s (%s: %s)", - i, - irb.context.irb_name, + i, + irb.context.irb_name, irb.context.main, th, t_status) @@ -143,14 +143,14 @@ module IRB IRB.JobManager.irb(Thread.current).context end - # invoke multi-irb + # invoke multi-irb def IRB.irb(file = nil, *main) workspace = WorkSpace.new(*main) parent_thread = Thread.current Thread.start do begin irb = Irb.new(workspace, file) - rescue + rescue print "Subirb can't start with context(self): ", workspace.main.inspect, "\n" print "return to main irb\n" Thread.pass diff --git a/lib/irb/ext/save-history.rb b/lib/irb/ext/save-history.rb index 88610fe9c9..4d53844d5f 100644 --- a/lib/irb/ext/save-history.rb +++ b/lib/irb/ext/save-history.rb @@ -1,13 +1,13 @@ #!/usr/local/bin/ruby # -# save-history.rb - +# save-history.rb - # $Release Version: 0.9.5$ # $Revision$ # by Keiju ISHITSUKA([email protected]) # # -- # -# +# # require "readline" diff --git a/lib/irb/ext/tracer.rb b/lib/irb/ext/tracer.rb index df954af20b..6728c46137 100644 --- a/lib/irb/ext/tracer.rb +++ b/lib/irb/ext/tracer.rb @@ -1,12 +1,12 @@ # -# irb/lib/tracer.rb - +# irb/lib/tracer.rb - # $Release Version: 0.9.5$ # $Revision$ # by Keiju ISHITSUKA([email protected]) # # -- # -# +# # require "tracer" @@ -43,7 +43,7 @@ module IRB alias __evaluate__ evaluate def evaluate(context, statements, file = nil, line = nil) if context.use_tracer? && file != nil && line != nil - Tracer.on + Tracer.on begin __evaluate__(context, statements, file, line) ensure @@ -57,4 +57,4 @@ module IRB IRB.initialize_tracer end - + diff --git a/lib/irb/ext/use-loader.rb b/lib/irb/ext/use-loader.rb index 3836275fcd..b643dd099e 100644 --- a/lib/irb/ext/use-loader.rb +++ b/lib/irb/ext/use-loader.rb @@ -1,12 +1,12 @@ # -# use-loader.rb - +# use-loader.rb - # $Release Version: 0.9.5$ # $Revision$ # by Keiju ISHITSUKA([email protected]) # # -- # -# +# # require "irb/cmd/load" @@ -30,7 +30,7 @@ module IRB class Context IRB.conf[:USE_LOADER] = false - + def use_loader IRB.conf[:USE_LOADER] end diff --git a/lib/irb/ext/workspaces.rb b/lib/irb/ext/workspaces.rb index f3ae8d1ae8..654b8118ea 100644 --- a/lib/irb/ext/workspaces.rb +++ b/lib/irb/ext/workspaces.rb @@ -1,12 +1,12 @@ # -# push-ws.rb - +# push-ws.rb - # $Release Version: 0.9.5$ # $Revision$ # by Keiju ISHITSUKA([email protected]) # # -- # -# +# # module IRB diff --git a/lib/irb/extend-command.rb b/lib/irb/extend-command.rb index 2816f35116..61a43e4a78 100644 --- a/lib/irb/extend-command.rb +++ b/lib/irb/extend-command.rb @@ -1,12 +1,12 @@ # -# irb/extend-command.rb - irb extend command +# irb/extend-command.rb - irb extend command # $Release Version: 0.9.5$ # $Revision$ # by Keiju ISHITSUKA([email protected]) # # -- # -# +# # module IRB # @@ -89,15 +89,15 @@ module IRB [:irb_load, :Load, "irb/cmd/load"], [:irb_require, :Require, "irb/cmd/load"], - [:irb_source, :Source, "irb/cmd/load", + [:irb_source, :Source, "irb/cmd/load", [:source, NO_OVERRIDE]], [:irb, :IrbCommand, "irb/cmd/subirb"], - [:irb_jobs, :Jobs, "irb/cmd/subirb", + [:irb_jobs, :Jobs, "irb/cmd/subirb", [:jobs, NO_OVERRIDE]], - [:irb_fg, :Foreground, "irb/cmd/subirb", + [:irb_fg, :Foreground, "irb/cmd/subirb", [:fg, NO_OVERRIDE]], - [:irb_kill, :Kill, "irb/cmd/subirb", + [:irb_kill, :Kill, "irb/cmd/subirb", [:kill, OVERRIDE_PRIVATE_ONLY]], [:irb_help, :Help, "irb/cmd/help", @@ -161,9 +161,9 @@ module IRB (override == NO_OVERRIDE) && !respond_to?(to, true) target = self (class<<self;self;end).instance_eval{ - if target.respond_to?(to, true) && + if target.respond_to?(to, true) && !target.respond_to?(EXCB.irb_original_method_name(to), true) - alias_method(EXCB.irb_original_method_name(to), to) + alias_method(EXCB.irb_original_method_name(to), to) end alias_method to, from } diff --git a/lib/irb/frame.rb b/lib/irb/frame.rb index 8a5d0696fb..8814b47a9d 100644 --- a/lib/irb/frame.rb +++ b/lib/irb/frame.rb @@ -1,12 +1,12 @@ # -# frame.rb - +# frame.rb - # $Release Version: 0.9$ # $Revision$ # by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd) # # -- # -# +# # require "e2mmap" diff --git a/lib/irb/help.rb b/lib/irb/help.rb index 2b064d5d6d..cae9c8a832 100644 --- a/lib/irb/help.rb +++ b/lib/irb/help.rb @@ -6,7 +6,7 @@ # # -- # -# +# # require 'irb/magic-file' diff --git a/lib/irb/init.rb b/lib/irb/init.rb index 62c862a1c3..8f88802f5d 100644 --- a/lib/irb/init.rb +++ b/lib/irb/init.rb @@ -6,7 +6,7 @@ # # -- # -# +# # module IRB @@ -20,7 +20,7 @@ module IRB IRB.load_modules unless @CONF[:PROMPT][@CONF[:PROMPT_MODE]] - IRB.fail(UndefinedPromptMode, @CONF[:PROMPT_MODE]) + IRB.fail(UndefinedPromptMode, @CONF[:PROMPT_MODE]) end end @@ -112,7 +112,7 @@ module IRB # @CONF[:LC_MESSAGES] = "en" @CONF[:LC_MESSAGES] = Locale.new - + @CONF[:DEBUG_LEVEL] = 1 end @@ -246,7 +246,7 @@ module IRB yield proc{|rc| rc == "rc" ? irbrc : irbrc+rc} end if home = ENV["HOME"] - yield proc{|rc| home+"/.irb#{rc}"} + yield proc{|rc| home+"/.irb#{rc}"} end home = Dir.pwd yield proc{|rc| home+"/.irb#{rc}"} diff --git a/lib/irb/input-method.rb b/lib/irb/input-method.rb index 0b22d9ca74..9c3d682c66 100644 --- a/lib/irb/input-method.rb +++ b/lib/irb/input-method.rb @@ -6,13 +6,13 @@ # # -- # -# +# # require 'irb/src_encoding' require 'irb/magic-file' module IRB - # + # # InputMethod # StdioInputMethod # FileInputMethod @@ -28,7 +28,7 @@ module IRB attr_reader :file_name attr_accessor :prompt - + def gets IRB.fail NotImplementedError, "gets" end @@ -38,7 +38,7 @@ module IRB false end end - + class StdioInputMethod < InputMethod def initialize super @@ -70,7 +70,7 @@ module IRB @stdin.external_encoding end end - + class FileInputMethod < InputMethod def initialize(file) super @@ -97,7 +97,7 @@ module IRB begin require "readline" class ReadlineInputMethod < InputMethod - include Readline + include Readline def initialize super diff --git a/lib/irb/lc/error.rb b/lib/irb/lc/error.rb index acfa22c2af..ed7d0361fe 100644 --- a/lib/irb/lc/error.rb +++ b/lib/irb/lc/error.rb @@ -1,12 +1,12 @@ # -# irb/lc/error.rb - +# irb/lc/error.rb - # $Release Version: 0.9.5$ # $Revision$ # by Keiju ISHITSUKA([email protected]) # # -- # -# +# # require "e2mmap" diff --git a/lib/irb/lc/ja/error.rb b/lib/irb/lc/ja/error.rb index dc0345e6df..c73b640637 100644 --- a/lib/irb/lc/ja/error.rb +++ b/lib/irb/lc/ja/error.rb @@ -1,12 +1,12 @@ # -*- coding: utf-8 -*- -# irb/lc/ja/error.rb - +# irb/lc/ja/error.rb - # $Release Version: 0.9.5$ # $Revision$ # by Keiju ISHITSUKA([email protected]) # # -- # -# +# # require "e2mmap" diff --git a/lib/irb/locale.rb b/lib/irb/locale.rb index d4e2a0244a..9c96d15525 100644 --- a/lib/irb/locale.rb +++ b/lib/irb/locale.rb @@ -6,7 +6,7 @@ # # -- # -# +# # module IRB class Locale @@ -30,7 +30,7 @@ module IRB def initialize(locale = nil) @lang = @territory = @encoding_name = @modifier = nil - @locale = locale || ENV["IRB_LANG"] || ENV["LC_MESSAGES"] || ENV["LC_ALL"] || ENV["LANG"] || "C" + @locale = locale || ENV["IRB_LANG"] || ENV["LC_MESSAGES"] || ENV["LC_ALL"] || ENV["LANG"] || "C" if m = LOCALE_NAME_RE.match(@locale) @lang, @territory, @encoding_name, @modifier = m[:language], m[:territory], m[:codeset], m[:modifier] @@ -50,7 +50,7 @@ module IRB def String(mes) mes = super(mes) if @encoding - mes.encode(@encoding) + mes.encode(@encoding) else mes end @@ -109,7 +109,7 @@ module IRB end alias toplevel_load load - + def load(file, priv=nil) dir = File.dirname(file) dir = "" if dir == "." @@ -125,7 +125,7 @@ module IRB return real_load(lc_path, priv) if lc_path end raise LoadError, "No such file to load -- #{file}" - end + end def real_load(path, priv) src = MagicFile.open(path){|f| f.read} diff --git a/lib/irb/notifier.rb b/lib/irb/notifier.rb index 51f10ff398..f76fc8040c 100644 --- a/lib/irb/notifier.rb +++ b/lib/irb/notifier.rb @@ -1,12 +1,12 @@ # -# notifier.rb - output methods used by irb +# notifier.rb - output methods used by irb # $Release Version: 0.9.5$ # $Revision$ # by Keiju ISHITSUKA([email protected]) # # -- # -# +# # require "e2mmap" @@ -15,16 +15,16 @@ require "irb/output-method" module IRB module Notifier extend Exception2MessageMapper - def_exception :ErrUndefinedNotifier, + def_exception :ErrUndefinedNotifier, "undefined notifier level: %d is specified" - def_exception :ErrUnrecognizedLevel, + def_exception :ErrUnrecognizedLevel, "unrecognized notifier level: %s is specified" def def_notifier(prefix = "", output_method = StdioOutputMethod.new) CompositeNotifier.new(prefix, output_method) end module_function :def_notifier - + class AbstructNotifier def initialize(prefix, base_notifier) @prefix = prefix @@ -112,7 +112,7 @@ module IRB def initialize(base, level, prefix) super(prefix, base) - + @level = level end @@ -121,7 +121,7 @@ module IRB def <=>(other) @level <=> other.level end - + def notify? @base_notifier.level >= self end diff --git a/lib/irb/output-method.rb b/lib/irb/output-method.rb index 301af7210e..bbfc072536 100644 --- a/lib/irb/output-method.rb +++ b/lib/irb/output-method.rb @@ -1,12 +1,12 @@ # -# output-method.rb - optput methods used by irb +# output-method.rb - optput methods used by irb # $Release Version: 0.9.5$ # $Revision$ # by Keiju ISHITSUKA([email protected]) # # -- # -# +# # require "e2mmap" @@ -39,7 +39,7 @@ module IRB # <minimum field width> (\*|\*[1-9][0-9]*\$|[1-9][0-9]*) # <precision>.(\*|\*[1-9][0-9]*\$|[1-9][0-9]*|)? # #<length modifier>(hh|h|l|ll|L|q|j|z|t) - # <conversion specifier>[diouxXeEfgGcsb%] + # <conversion specifier>[diouxXeEfgGcsb%] def parse_printf_format(format, opts) return format, opts if $1.size % 2 == 1 end diff --git a/lib/irb/ruby-lex.rb b/lib/irb/ruby-lex.rb index b21f0d34f8..13b101ffc8 100644 --- a/lib/irb/ruby-lex.rb +++ b/lib/irb/ruby-lex.rb @@ -6,7 +6,7 @@ # # -- # -# +# # require "e2mmap" @@ -20,12 +20,12 @@ class RubyLex def_exception(:AlreadyDefinedToken, "Already defined token(%s)") def_exception(:TkReading2TokenNoKey, "key nothing(key='%s')") def_exception(:TkSymbol2TokenNoKey, "key nothing(key='%s')") - def_exception(:TkReading2TokenDuplicateError, + def_exception(:TkReading2TokenDuplicateError, "key duplicate(token_n='%s', key='%s')") def_exception(:SyntaxError, "%s") def_exception(:TerminateLineInput, "Terminate Line Input") - + include RubyToken class << self @@ -53,7 +53,7 @@ class RubyLex @lex_state = EXPR_BEG @space_seen = false @here_header = false - + @continue = false @line = "" @@ -91,7 +91,7 @@ class RubyLex else @base_char_no += @readed.size end - + readed = @readed.join("") @readed = [] readed @@ -111,7 +111,7 @@ class RubyLex end @seek += 1 if c == "\n" - @line_no += 1 + @line_no += 1 @char_no = 0 else @char_no += 1 @@ -148,10 +148,10 @@ class RubyLex c2 = @here_readed.pop end c = c2 unless c - @rests.unshift c #c = + @rests.unshift c #c = @seek -= 1 if c == "\n" - @line_no -= 1 + @line_no -= 1 if idx = @readed.reverse.index("\n") @char_no = @readed.size - idx else @@ -216,14 +216,14 @@ class RubyLex @lex_state = EXPR_BEG @space_seen = false @here_header = false - + @continue = false prompt @line = "" @exp_line_no = @line_no end - + def each_top_level_statement initialize_input catch(:TERM_INPUT) do @@ -297,7 +297,7 @@ class RubyLex # Tracer.off tk end - + ENINDENT_CLAUSE = [ "case", "class", "def", "do", "for", "if", "module", "unless", "until", "while", "begin" #, "when" @@ -314,7 +314,7 @@ class RubyLex "W" => "]", "s" => ":" } - + PERCENT_PAREN = { "{" => "}", "[" => "]", @@ -354,7 +354,7 @@ class RubyLex end @OP.def_rule("=begin", - proc{|op, io| @prev_char_no == 0 && peek(0) =~ /\s/}) do + proc{|op, io| @prev_char_no == 0 && peek(0) =~ /\s/}) do |op, io| @ltype = "=" until getc == "\n"; end @@ -374,8 +374,8 @@ class RubyLex else @continue = false @lex_state = EXPR_BEG - until (@indent_stack.empty? || - [TkLPAREN, TkLBRACK, TkLBRACE, + until (@indent_stack.empty? || + [TkLPAREN, TkLBRACK, TkLBRACE, TkfLPAREN, TkfLBRACK, TkfLBRACE].include?(@indent_stack.last)) @indent_stack.pop end @@ -385,9 +385,9 @@ class RubyLex Token(TkNL) end - @OP.def_rules("*", "**", - "=", "==", "===", - "=~", "<=>", + @OP.def_rules("*", "**", + "=", "==", "===", + "=~", "<=>", "<", "<=", ">", ">=", ">>") do |op, io| @@ -455,7 +455,7 @@ class RubyLex @lex_state = EXPR_BEG; Token(TkQUESTION) else - if (ch == '\\') + if (ch == '\\') read_escape end @lex_state = EXPR_END @@ -469,8 +469,8 @@ class RubyLex @lex_state = EXPR_BEG Token(op) end - - @OP.def_rules("+=", "-=", "*=", "**=", + + @OP.def_rules("+=", "-=", "*=", "**=", "&=", "|=", "^=", "<<=", ">>=", "||=", "&&=") do |op, io| @lex_state = EXPR_BEG @@ -529,7 +529,7 @@ class RubyLex lex_int2 end - + def lex_int2 @OP.def_rules("]", "}", ")") do |op, io| @@ -572,7 +572,7 @@ class RubyLex Token(TkOPASGN, "/") #/) elsif @lex_state == EXPR_ARG and @space_seen and peek(0) !~ /\s/ identify_string(op) - else + else @lex_state = EXPR_BEG Token("/") #/) end @@ -588,7 +588,7 @@ class RubyLex # @lex_state = EXPR_BEG # Token(OP_ASGN, :^) # end - + @OP.def_rules(",") do |op, io| @lex_state = EXPR_BEG @@ -598,8 +598,8 @@ class RubyLex @OP.def_rules(";") do |op, io| @lex_state = EXPR_BEG - until (@indent_stack.empty? || - [TkLPAREN, TkLBRACK, TkLBRACE, + until (@indent_stack.empty? || + [TkLPAREN, TkLBRACK, TkLBRACE, TkfLPAREN, TkfLBRACK, TkfLBRACE].include?(@indent_stack.last)) @indent_stack.pop end @@ -617,7 +617,7 @@ class RubyLex @lex_state = EXPR_BEG Token("~") end - + @OP.def_rule("(") do |op, io| @indent += 1 @@ -718,7 +718,7 @@ class RubyLex end end - # @OP.def_rule("def", proc{|op, io| /\s/ =~ io.peek(0)}) do + # @OP.def_rule("def", proc{|op, io| /\s/ =~ io.peek(0)}) do # |op, io| # @indent += 1 # @lex_state = EXPR_FNAME @@ -739,13 +739,13 @@ class RubyLex printf "MATCH: end %s: %s\n", op, io.inspect if RubyLex.debug? t end - + p @OP if RubyLex.debug? end - + def identify_gvar @lex_state = EXPR_END - + case ch = getc when /[~_*$?!@\/\\;,=:<>".]/ #" Token(TkGVAR, "$" + ch) @@ -761,12 +761,12 @@ class RubyLex ungetc ungetc identify_identifier - else + else ungetc Token("$") end end - + def identify_identifier token = "" if peek(0) =~ /[$@]/ @@ -781,7 +781,7 @@ class RubyLex token.concat ch end ungetc - + if (ch == "!" || ch == "?") && token[0,1] =~ /\w/ && peek(0) != "=" token.concat getc end @@ -799,7 +799,7 @@ class RubyLex @lex_state = EXPR_END return Token(TkIVAR, token) end - + if @lex_state != EXPR_DOT print token, "\n" if RubyLex.debug? @@ -927,7 +927,7 @@ class RubyLex @lex_state = EXPR_END Token(Ltype2Token[lt]) end - + def identify_quotation ch = getc if lt = PERCENT_LTYPE[ch] @@ -968,10 +968,10 @@ class RubyLex match = /[0-7_]/ when /[89]/ RubyLex.fail SyntaxError, "Invalid octal digit" - else + else return Token(TkINTEGER) end - + len0 = true non_digit = false while ch = getc @@ -999,7 +999,7 @@ class RubyLex end return Token(TkINTEGER) end - + type = TkINTEGER allow_point = true allow_e = true @@ -1042,7 +1042,7 @@ class RubyLex end Token(type) end - + def identify_string(ltype, quoted = ltype) @ltype = ltype @quoted = quoted @@ -1063,7 +1063,7 @@ class RubyLex elsif ch == '\\' #' read_escape end - if PERCENT_PAREN.values.include?(@quoted) + if PERCENT_PAREN.values.include?(@quoted) if PERCENT_PAREN[ch] == @quoted nest += 1 elsif ch == @quoted @@ -1087,7 +1087,7 @@ class RubyLex @lex_state = EXPR_END end end - + def identify_comment @ltype = "#" @@ -1103,7 +1103,7 @@ class RubyLex end return Token(TkCOMMENT) end - + def read_escape case ch = getc when "\n", "\r", "\f" @@ -1120,7 +1120,7 @@ class RubyLex break end end - + when "x" 2.times do case ch = getc @@ -1149,7 +1149,7 @@ class RubyLex read_escape end else - # other characters + # other characters end end end diff --git a/lib/irb/ruby-token.rb b/lib/irb/ruby-token.rb index 30a94b043c..9eb3bc1739 100644 --- a/lib/irb/ruby-token.rb +++ b/lib/irb/ruby-token.rb @@ -1,12 +1,12 @@ # -# irb/ruby-token.rb - ruby tokens +# irb/ruby-token.rb - ruby tokens # $Release Version: 0.9.5$ # $Revision$ # by Keiju ISHITSUKA([email protected]) # # -- # -# +# # module RubyToken EXPR_BEG = :EXPR_BEG @@ -21,7 +21,7 @@ module RubyToken if !defined?(Symbol) Symbol = Integer end - + class Token def initialize(seek, line_no, char_no) @seek = seek @@ -84,7 +84,7 @@ module RubyToken if (tk = TkReading2Token[token]).nil? IRB.fail TkReading2TokenNoKey, token end - tk = Token(tk[0], value) + tk = Token(tk[0], value) if tk.kind_of?(TkOp) tk.name = token end @@ -93,8 +93,8 @@ module RubyToken if (tk = TkSymbol2Token[token]).nil? IRB.fail TkSymbol2TokenNoKey, token end - return Token(tk[0], value) - else + return Token(tk[0], value) + else if (token.ancestors & [TkId, TkVal, TkOPASGN, TkUnknownChar]).empty? token.new(@prev_seek, @prev_line_no, @prev_char_no) else @@ -194,7 +194,7 @@ module RubyToken [:TkASSOC, TkOp, "=>"], [:TkQUESTION, TkOp, "?"], #? [:TkCOLON, TkOp, ":"], #: - + [:TkfLPAREN], # func( # [:TkfLBRACK], # func[ # [:TkfLBRACE], # func{ # @@ -250,7 +250,7 @@ module RubyToken IRB.fail AlreadyDefinedToken, token_n end token_c = eval("class #{token_n} < #{super_token}; end; #{token_n}") - + if reading if TkReading2Token[reading] IRB.fail TkReading2TokenDuplicateError, token_n, reading diff --git a/lib/irb/slex.rb b/lib/irb/slex.rb index c8b40c6878..6b3d1f37e3 100644 --- a/lib/irb/slex.rb +++ b/lib/irb/slex.rb @@ -6,7 +6,7 @@ # # -- # -# +# # require "e2mmap" @@ -24,20 +24,20 @@ module IRB D_WARN = DOUT::def_notifier(1, "Warn: ") D_DEBUG = DOUT::def_notifier(2, "Debug: ") D_DETAIL = DOUT::def_notifier(4, "Detail: ") - + DOUT.level = Notifier::D_NOMSG def initialize @head = Node.new("") end - + def def_rule(token, preproc = nil, postproc = nil, &block) D_DETAIL.pp token postproc = block if block_given? node = create(token, preproc, postproc) end - + def def_rules(*tokens, &block) if block_given? p = block @@ -46,18 +46,18 @@ module IRB def_rule(token, nil, p) end end - + def preproc(token, proc) node = search(token) node.preproc=proc end - - #$BMW%A%'%C%/(B? + + #$BMW%A%'%C%/(B? def postproc(token) node = search(token, proc) node.postproc=proc end - + def search(token) @head.search(token.split(//)) end @@ -65,7 +65,7 @@ module IRB def create(token, preproc = nil, postproc = nil) @head.create_subnode(token.split(//), preproc, postproc) end - + def match(token) case token when Array @@ -78,14 +78,14 @@ module IRB D_DETAIL.exec_if{D_DEATIL.printf "match end: %s:%s\n", ret, token.inspect} ret end - + def inspect format("<SLex: @head = %s>", @head.inspect) end #---------------------------------------------------------------------- # - # class Node - + # class Node - # #---------------------------------------------------------------------- class Node @@ -99,7 +99,7 @@ module IRB attr_accessor :preproc attr_accessor :postproc - + def search(chrs, opt = nil) return self if chrs.empty? ch = chrs.shift @@ -114,7 +114,7 @@ module IRB end end end - + def create_subnode(chrs, preproc = nil, postproc = nil) if chrs.empty? if @postproc @@ -127,7 +127,7 @@ module IRB end return self end - + ch = chrs.shift if node = @Tree[ch] if chrs.empty? @@ -161,7 +161,7 @@ module IRB # chrs: String # character array # io must have getc()/ungetc(); and ungetc() must be - # able to be called arbitrary number of times. + # able to be called arbitrary number of times. # def match(chrs, op = "") D_DETAIL.print "match>: ", chrs, "op:", op, "\n" @@ -254,14 +254,14 @@ if $0 == __FILE__ print "1: ", tr.inspect, "\n" tr.def_rule("==") {print "==\n"} print "2: ", tr.inspect, "\n" - + print "case 1:\n" print tr.match("="), "\n" print "case 2:\n" print tr.match("=="), "\n" print "case 3:\n" print tr.match("=>"), "\n" - + when "2" tr = SLex.new print "0: ", tr.inspect, "\n" @@ -269,7 +269,7 @@ if $0 == __FILE__ print "1: ", tr.inspect, "\n" tr.def_rule("==", proc{false}) {print "==\n"} print "2: ", tr.inspect, "\n" - + print "case 1:\n" print tr.match("="), "\n" print "case 2:\n" diff --git a/lib/irb/version.rb b/lib/irb/version.rb index 32ecf940cf..a9ccc1ce95 100644 --- a/lib/irb/version.rb +++ b/lib/irb/version.rb @@ -6,7 +6,7 @@ # # -- # -# +# # module IRB diff --git a/lib/irb/workspace.rb b/lib/irb/workspace.rb index 7c95106c39..1b88914a84 100644 --- a/lib/irb/workspace.rb +++ b/lib/irb/workspace.rb @@ -1,12 +1,12 @@ # -# irb/workspace-binding.rb - +# irb/workspace-binding.rb - # $Release Version: 0.9.5$ # $Revision$ # by Keiju ISHITSUKA([email protected]) # # -- # -# +# # module IRB class WorkSpace @@ -21,7 +21,7 @@ module IRB case IRB.conf[:CONTEXT_MODE] when 0 # binding in proc on TOPLEVEL_BINDING @binding = eval("proc{binding}.call", - TOPLEVEL_BINDING, + TOPLEVEL_BINDING, __FILE__, __LINE__) when 1 # binding in loaded file @@ -37,7 +37,7 @@ EOF when 2 # binding in loaded file(thread use) unless defined? BINDING_QUEUE require "thread" - + IRB.const_set("BINDING_QUEUE", SizedQueue.new(1)) Thread.abort_on_exception = true Thread.start do @@ -49,7 +49,7 @@ EOF when 3 # binging in function on TOPLEVEL_BINDING(default) @binding = eval("def irb_binding; binding; end; irb_binding", - TOPLEVEL_BINDING, + TOPLEVEL_BINDING, __FILE__, __LINE__ - 3) end @@ -63,7 +63,7 @@ EOF when Module @binding = eval("IRB.conf[:__MAIN__].module_eval('binding', __FILE__, __LINE__)", @binding, __FILE__, __LINE__) else - begin + begin @binding = eval("IRB.conf[:__MAIN__].instance_eval('binding', __FILE__, __LINE__)", @binding, __FILE__, __LINE__) rescue TypeError IRB.fail CantChangeBinding, @main.inspect @@ -79,7 +79,7 @@ EOF def evaluate(context, statements, file = __FILE__, line = __LINE__) eval(statements, @binding, file, line) end - + # error message manipulator def filter_backtrace(bt) case IRB.conf[:CONTEXT_MODE] diff --git a/lib/irb/ws-for-case-2.rb b/lib/irb/ws-for-case-2.rb index 24c5fd5aa8..d7db90c96b 100644 --- a/lib/irb/ws-for-case-2.rb +++ b/lib/irb/ws-for-case-2.rb @@ -1,12 +1,12 @@ # -# irb/ws-for-case-2.rb - +# irb/ws-for-case-2.rb - # $Release Version: 0.9.5$ # $Revision$ # by Keiju ISHITSUKA([email protected]) # # -- # -# +# # while true diff --git a/lib/irb/xmp.rb b/lib/irb/xmp.rb index af87b48887..1a58026f45 100644 --- a/lib/irb/xmp.rb +++ b/lib/irb/xmp.rb @@ -6,7 +6,7 @@ # # -- # -# +# # require "irb" diff --git a/lib/mathn.rb b/lib/mathn.rb index 0241f578e9..57eac113c7 100644 --- a/lib/mathn.rb +++ b/lib/mathn.rb @@ -1,12 +1,12 @@ # -# mathn.rb - +# mathn.rb - # $Release Version: 0.5 $ # $Revision: 1.1.1.1.4.1 $ # by Keiju ISHITSUKA(SHL Japan Inc.) # # -- # -# +# # require "cmath.rb" @@ -66,14 +66,14 @@ class Rational 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 @@ -81,7 +81,7 @@ class Rational 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 @@ -89,12 +89,12 @@ class Rational 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 @@ -129,7 +129,7 @@ module Math # if !(x.kind_of?(Rational) and y.kind_of?(Rational)) # return a**Rational(1,2) # end - if a.imag >= 0 + if a.imag >= 0 Complex(x, y) else Complex(x, -y) @@ -142,7 +142,7 @@ module Math Complex(0,rsqrt(-a)) end end - + def rsqrt(a) if a.kind_of?(Float) sqrt!(a) @@ -156,7 +156,7 @@ module Math while (src >= max) and (src >>= 32) byte_a.unshift src & 0xffffffff end - + answer = 0 main = 0 side = 0 @@ -166,13 +166,13 @@ module Math if answer != 0 if main * 4 < side * side applo = main.div(side) - else + 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 diff --git a/lib/matrix.rb b/lib/matrix.rb index ec03c730fa..4bc000588b 100644 --- a/lib/matrix.rb +++ b/lib/matrix.rb @@ -1,6 +1,6 @@ #!/usr/local/bin/ruby #-- -# matrix.rb - +# matrix.rb - # $Release Version: 1.0$ # $Revision: 1.13 $ # Original Version from Smalltalk-80 version @@ -13,9 +13,9 @@ # An implementation of Matrix and Vector classes. # # Author:: Keiju ISHITSUKA -# Documentation:: Gavin Sinclair (sourced from <i>Ruby in a Nutshell</i> (Matsumoto, O'Reilly)) +# Documentation:: Gavin Sinclair (sourced from <i>Ruby in a Nutshell</i> (Matsumoto, O'Reilly)) # -# See classes Matrix and Vector for documentation. +# See classes Matrix and Vector for documentation. # require "e2mmap.rb" @@ -24,7 +24,7 @@ module ExceptionForMatrix # :nodoc: extend Exception2MessageMapper def_e2message(TypeError, "wrong argument type %s (expected %s)") def_e2message(ArgumentError, "Wrong # of arguments(%d for %d)") - + def_exception("ErrDimensionMismatch", "\#{self.name} dimension mismatch") def_exception("ErrNotRegular", "Not Regular Matrix") def_exception("ErrOperationNotDefined", "This operation(%s) can\\'t defined") @@ -59,7 +59,7 @@ end # * <tt> Matrix.row_vector(row) </tt> # * <tt> Matrix.column_vector(column) </tt> # -# To access Matrix elements/columns/rows/submatrices/properties: +# To access Matrix elements/columns/rows/submatrices/properties: # * <tt> [](i, j) </tt> # * <tt> #row_size </tt> # * <tt> #column_size </tt> @@ -104,13 +104,13 @@ end # class Matrix @RCS_ID='-$Id: matrix.rb,v 1.13 2001/12/09 14:22:23 keiju Exp keiju $-' - + # extend Exception2MessageMapper include ExceptionForMatrix - + # instance creations private_class_method :new - + # # Creates a matrix where each argument is a row. # Matrix[ [25, 93], [-1, 66] ] @@ -120,7 +120,7 @@ class Matrix def Matrix.[](*rows) new(:init_rows, rows, false) end - + # # 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 @@ -131,7 +131,7 @@ class Matrix def Matrix.rows(rows, copy = true) new(:init_rows, rows, copy) end - + # # Creates a matrix using +columns+ as an array of column vectors. # Matrix.columns([[25, 93], [-1, 66]]) @@ -147,7 +147,7 @@ class Matrix } Matrix.rows(rows, false) end - + # # Creates a matrix where the diagonal elements are composed of +values+. # Matrix.diagonal(9, 5, -3) @@ -164,7 +164,7 @@ class Matrix } rows(rows, false) end - + # # Creates an +n+ by +n+ diagonal matrix where each diagonal element is # +value+. @@ -185,11 +185,11 @@ class Matrix def Matrix.identity(n) Matrix.scalar(n, 1) end - class << Matrix + class << Matrix alias unit identity alias I identity end - + # # Creates an +n+ by +n+ zero matrix. # Matrix.zero(2) @@ -199,7 +199,7 @@ class Matrix def Matrix.zero(n) Matrix.scalar(n, 0) end - + # # Creates a single-row matrix where the values of that row are as given in # +row+. @@ -216,7 +216,7 @@ class Matrix Matrix.rows([[row]], false) end end - + # # Creates a single-column matrix where the values of that column are as given # in +column+. @@ -243,7 +243,7 @@ class Matrix def initialize(init_method, *argv) self.send(init_method, *argv) end - + def init_rows(rows, copy) if copy @rows = rows.collect{|row| row.dup} @@ -253,7 +253,7 @@ class Matrix self end private :init_rows - + # # Returns element (+i+,+j+) of the matrix. That is: row +i+, column +j+. # @@ -276,7 +276,7 @@ class Matrix def row_size @rows.size end - + # # 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 @@ -318,7 +318,7 @@ class Matrix Vector.elements(col, false) end end - + # # Returns a matrix that is the result of iteration of the given block over all # elements of the matrix. @@ -331,7 +331,7 @@ class Matrix Matrix.rows(rows, false) end alias map collect - + # # Returns a section of the matrix. The parameters are either: # * start_row, nrows, start_col, ncols; OR @@ -358,13 +358,13 @@ class Matrix 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 - + #-- # TESTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #++ @@ -375,7 +375,7 @@ class Matrix def regular? square? and rank == column_size end - + # # Returns +true+ is this is a singular (i.e. non-regular) matrix. # @@ -390,7 +390,7 @@ class Matrix def square? column_size == row_size end - + #-- # OBJECT METHODS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #++ @@ -400,27 +400,27 @@ class Matrix # def ==(other) return false unless Matrix === other - + other.compare_by_row_vectors(@rows) end def eql?(other) return false unless Matrix === other - + other.compare_by_row_vectors(@rows, :eql?) end - + # # Not really intended for general consumption. # def compare_by_row_vectors(rows, comparison = :==) return false unless @rows.size == rows.size - + 0.upto(@rows.size - 1) do |i| return false unless @rows[i].send(comparison, rows[i]) end true end - + # # Returns a clone of the matrix, so that the contents of each do not reference # identical objects. @@ -428,7 +428,7 @@ class Matrix def clone Matrix.rows(@rows) end - + # # Returns a hash-code for the matrix. # @@ -441,11 +441,11 @@ class Matrix end return value end - + #-- # ARITHMETIC -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #++ - + # # Matrix multiplication. # Matrix[[2,4], [6,8]] * Matrix.identity(2) @@ -467,7 +467,7 @@ class Matrix 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 @@ -483,7 +483,7 @@ class Matrix return x * y end end - + # # Matrix addition. # Matrix.scalar(2,5) + Matrix[[1,0], [-4,7]] @@ -501,9 +501,9 @@ class Matrix 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] @@ -529,9 +529,9 @@ class Matrix 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] @@ -539,7 +539,7 @@ class Matrix } Matrix.rows(rows, false) end - + # # Matrix division (multiplication by the inverse). # Matrix[[7,6], [3,9]] / Matrix[[2,9], [3,1]] @@ -581,7 +581,7 @@ class Matrix def inverse_from(src) size = row_size - 1 a = src.to_a - + for k in 0..size i = k akk = a[k][k].abs @@ -598,12 +598,12 @@ class Matrix @rows[i], @rows[k] = @rows[k], @rows[i] end akk = a[k][k] - + for i in 0 .. size next if i == k q = a[i][k].quo(akk) a[i][k] = 0 - + for j in (k + 1).. size a[i][j] -= a[k][j] * q end @@ -611,7 +611,7 @@ class Matrix @rows[i][j] -= @rows[k][j] * q end end - + for j in (k + 1).. size a[k][j] = a[k][j].quo(akk) end @@ -622,7 +622,7 @@ class Matrix self end #alias reciprocal inverse - + # # Matrix exponentiation. Defined for integer powers only. Equivalent to # multiplying the matrix by itself N times. @@ -656,11 +656,11 @@ class Matrix Matrix.Raise ErrOperationNotDefined, "**" end end - + #-- # MATRIX FUNCTIONS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #++ - + # # Returns the determinant of the matrix. If the matrix is not square, the # result is 0. This method's algorism is Gaussian elimination method @@ -673,10 +673,10 @@ class Matrix # def determinant return 0 unless square? - + size = row_size - 1 a = to_a - + det = 1 k = 0 loop do @@ -706,20 +706,20 @@ class Matrix # # Returns the determinant of the matrix. If the matrix is not square, the - # result is 0. This method's algorism is Gaussian elimination method. + # result is 0. This method's algorism is Gaussian elimination method. # This method uses Euclidean algorism. If all elements are integer, # really exact value. But, if an element is a float, can't return - # exact value. + # exact value. # # Matrix[[7,6], [3,9]].determinant # => 63 # def determinant_e return 0 unless square? - + size = row_size - 1 a = to_a - + det = 1 k = 0 loop do @@ -821,7 +821,7 @@ class Matrix # # Returns the rank of the matrix. This method uses Euclidean # algorism. If all elements are integer, really exact value. But, if - # an element is a float, can't return exact value. + # an element is a float, can't return exact value. # # Matrix[[7,6], [3,9]].rank # => 2 @@ -866,7 +866,7 @@ class Matrix tr end alias tr trace - + # # Returns the transpose of the matrix. # Matrix[[1,2], [3,4], [5,6]] @@ -881,11 +881,11 @@ class Matrix Matrix.columns(@rows) end alias t transpose - + #-- # CONVERTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #++ - + # # FIXME: describe #coerce. # @@ -907,7 +907,7 @@ class Matrix } rows end - + # # Returns an array of the column vectors of the matrix. See Vector. # @@ -917,30 +917,30 @@ class Matrix } columns end - + # # Returns an array of arrays that describe the rows of the matrix. # def to_a @rows.collect{|row| row.collect{|e| e}} end - + def elements_to_f collect{|e| e.to_f} end - + def elements_to_i collect{|e| e.to_i} end - + def elements_to_r collect{|e| e.to_r} end - + #-- # PRINTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #++ - + # # Overrides Object#to_s # @@ -949,23 +949,23 @@ class Matrix "[" + row.collect{|e| e.to_s}.join(", ") + "]" }.join(", ")+"]" end - + # # Overrides Object#inspect # def inspect "Matrix"[email protected] end - + # Private CLASS - + class Scalar < Numeric # :nodoc: include ExceptionForMatrix - + def initialize(value) @value = value end - + # ARITHMETIC def +(other) case other @@ -980,7 +980,7 @@ class Matrix x + y end end - + def -(other) case other when Numeric @@ -994,7 +994,7 @@ class Matrix x - y end end - + def *(other) case other when Numeric @@ -1006,7 +1006,7 @@ class Matrix x * y end end - + def / (other) case other when Numeric @@ -1020,7 +1020,7 @@ class Matrix x.quo(y) end end - + def ** (other) case other when Numeric @@ -1079,9 +1079,9 @@ end # class Vector include ExceptionForMatrix - + #INSTANCE CREATION - + private_class_method :new # @@ -1091,7 +1091,7 @@ class Vector def Vector.[](*array) new(:init_elements, array, copy = false) end - + # # Creates a vector from an Array. The optional second argument specifies # whether the array itself or a copy is used internally. @@ -1099,14 +1099,14 @@ class Vector def Vector.elements(array, copy = true) new(:init_elements, array, copy) end - + # # For internal use. # def initialize(method, array, copy) self.send(method, array, copy) end - + # # For internal use. # @@ -1117,9 +1117,9 @@ class Vector @elements = array end end - + # ACCESSING - + # # Returns element number +i+ (starting at zero) of the vector. # @@ -1135,14 +1135,14 @@ class Vector alias set_element []= alias set_component []= private :[]=, :set_element, :set_component - + # # Returns the number of elements in the vector. # def size @elements.size end - + #-- # ENUMERATIONS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #++ @@ -1156,7 +1156,7 @@ class Vector yield @elements[i], v[i] end end - + # # Collects (as in Enumerable#collect) over the elements of this vector and +v+ # in conjunction. @@ -1177,40 +1177,40 @@ class Vector # def ==(other) return false unless Vector === other - + other.compare_by(@elements) end def eql?(other) return false unless Vector === other - + other.compare_by(@elements, :eql?) end - + # # For internal use. # def compare_by(elements, comparison = :==) @elements.send(comparison, elements) end - + # # Return a copy of the vector. # def clone Vector.elements(@elements) end - + # # Return a hash-code for the vector. # def hash @elements.hash end - + #-- # ARITHMETIC -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #++ - + # # Multiplies the vector by +x+, where +x+ is a number or another vector. # @@ -1264,25 +1264,25 @@ class Vector s - x end end - + #-- # VECTOR FUNCTIONS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #++ - + # # Returns the inner product of this vector with the other. # Vector[4,7].inner_product Vector[10,1] => 47 # def inner_product(v) Vector.Raise ErrDimensionMismatch if size != v.size - + p = 0 each2(v) {|v1, v2| p += v1 * v2 } p end - + # # Like Array#collect. # @@ -1293,7 +1293,7 @@ class Vector Vector.elements(els, false) end alias map collect - + # # Like Vector#collect2, but returns a Vector instead of an Array. # @@ -1303,7 +1303,7 @@ class Vector } Vector.elements(els, false) end - + # # Returns the modulus (Pythagorean distance) of the vector. # Vector[5,8,2].r => 9.643650761 @@ -1315,7 +1315,7 @@ class Vector end return Math.sqrt(v) end - + #-- # CONVERTING #++ @@ -1326,26 +1326,26 @@ class Vector def covector Matrix.row_vector(self) end - + # # Returns the elements of the vector in an array. # def to_a @elements.dup end - + def elements_to_f collect{|e| e.to_f} end - + def elements_to_i collect{|e| e.to_i} end - + def elements_to_r collect{|e| e.to_r} end - + # # FIXME: describe Vector#coerce. # @@ -1357,18 +1357,18 @@ class Vector raise TypeError, "#{self.class} can't be coerced into #{other.class}" end end - + #-- # PRINTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #++ - + # # Overrides Object#to_s # def to_s "Vector[" + @elements.join(", ") + "]" end - + # # Overrides Object#inspect # diff --git a/lib/mkmf.rb b/lib/mkmf.rb index 1afce2ae65..4d0a0dfa93 100644 --- a/lib/mkmf.rb +++ b/lib/mkmf.rb @@ -264,7 +264,7 @@ module Logging @log = nil end end - + def self::postpone tmplog = "mkmftmp#{@postpone += 1}.log" open do @@ -858,7 +858,7 @@ end # HAVE_STRUCT_FOO_BAR preprocessor macro would be passed to the compiler. # # HAVE_ST_BAR is also defined for backward compatibility. -# +# def have_struct_member(type, member, headers = nil, &b) checking_for checking_message("#{type}.#{member}", headers) do if try_compile(<<"SRC", &b) @@ -1167,7 +1167,7 @@ end # 'extconf.h'. # # For example: -# +# # # extconf.rb # require 'mkmf' # have_func('realpath') @@ -1262,7 +1262,7 @@ def pkg_config(pkg) if pkgconfig = with_config("#{pkg}-config") and find_executable0(pkgconfig) # iff package specific config command is given get = proc {|opt| `#{pkgconfig} --#{opt}`.chomp} - elsif ($PKGCONFIG ||= + elsif ($PKGCONFIG ||= (pkgconfig = with_config("pkg-config", ("pkg-config" unless CROSS_COMPILING))) && find_executable0(pkgconfig) && pkgconfig) and system("#{$PKGCONFIG} --exists #{pkg}") diff --git a/lib/monitor.rb b/lib/monitor.rb index 31234819b8..00d85fae52 100644 --- a/lib/monitor.rb +++ b/lib/monitor.rb @@ -12,11 +12,11 @@ You can freely distribute/modify this library. This is a simple example. require 'monitor.rb' - + buf = [] buf.extend(MonitorMixin) empty_cond = buf.new_cond - + # consumer Thread.start do loop do @@ -26,7 +26,7 @@ This is a simple example. end end end - + # producer while line = ARGF.gets buf.synchronize do @@ -49,11 +49,11 @@ require 'thread' # +include+. For example: # # require 'monitor' -# +# # buf = [] # buf.extend(MonitorMixin) # empty_cond = buf.new_cond -# +# # # consumer # Thread.start do # loop do @@ -63,7 +63,7 @@ require 'thread' # end # end # end -# +# # # producer # while line = ARGF.gets # buf.synchronize do @@ -71,7 +71,7 @@ require 'thread' # 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 @@ -86,7 +86,7 @@ module MonitorMixin # class ConditionVariable class Timeout < Exception; end - + def wait(timeout = nil) if timeout raise NotImplementedError, "timeout is not implemented yet" @@ -100,33 +100,33 @@ module MonitorMixin @monitor.send(:mon_enter_for_cond, count) end end - + def wait_while while yield wait end end - + def wait_until until yield wait end end - + def signal @monitor.send(:mon_check_owner) @cond.signal end - + def broadcast @monitor.send(:mon_check_owner) @cond.broadcast end - + def count_waiters raise NotImplementedError end - + private def initialize(monitor) @@ -134,12 +134,12 @@ module MonitorMixin @cond = ::ConditionVariable.new end end - + def self.extend_object(obj) super(obj) obj.send(:mon_initialize) end - + # # Attempts to enter exclusive section. Returns +false+ if lock fails. # @@ -166,7 +166,7 @@ module MonitorMixin end @mon_count += 1 end - + # # Leaves exclusive section. # @@ -193,7 +193,7 @@ module MonitorMixin end end alias synchronize mon_synchronize - + # # FIXME: This isn't documented in Nutshell. # diff --git a/lib/mutex_m.rb b/lib/mutex_m.rb index f46f866fa5..21d828523e 100644 --- a/lib/mutex_m.rb +++ b/lib/mutex_m.rb @@ -1,5 +1,5 @@ # -# mutex_m.rb - +# mutex_m.rb - # $Release Version: 3.0$ # $Revision: 1.7 $ # Original from mutex.rb @@ -34,13 +34,13 @@ module Mutex_m alias try_lock mu_try_lock alias synchronize mu_synchronize } - end + end def Mutex_m.append_features(cl) super define_aliases(cl) unless cl.instance_of?(Module) end - + def Mutex_m.extend_object(obj) super obj.mu_extended @@ -56,30 +56,30 @@ module Mutex_m end mu_initialize end - - # locking + + # locking def mu_synchronize(&block) @_mutex.synchronize(&block) end - + def mu_locked? @_mutex.locked? end - + def mu_try_lock @_mutex.try_lock end - + def mu_lock @_mutex.lock end - + def mu_unlock @_mutex.unlock end - + private - + def mu_initialize @_mutex = Mutex.new end diff --git a/lib/net/ftp.rb b/lib/net/ftp.rb index 06cc3eafa2..40227b69d8 100644 --- a/lib/net/ftp.rb +++ b/lib/net/ftp.rb @@ -1,11 +1,11 @@ -# +# # = net/ftp.rb - FTP Client Library -# +# # Written by Shugo Maeda <[email protected]>. # # 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. # @@ -22,8 +22,8 @@ module Net # :stopdoc: class FTPError < StandardError; end class FTPReplyError < FTPError; end - class FTPTempError < FTPError; end - class FTPPermError < FTPError; end + class FTPTempError < FTPError; end + class FTPPermError < FTPError; end class FTPProtoError < FTPError; end # :startdoc: @@ -34,11 +34,11 @@ module Net # 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') @@ -71,13 +71,13 @@ module Net # class FTP include MonitorMixin - + # :stopdoc: FTP_PORT = 21 CRLF = "\r\n" DEFAULT_BLOCKSIZE = 4096 # :startdoc: - + # When +true+, transfers are performed in binary mode. Default: +true+. attr_reader :binary @@ -101,7 +101,7 @@ module Net # The server's last response. attr_reader :last_response - + # # A synonym for <tt>FTP.new</tt>, but with a mandatory host parameter. # @@ -120,7 +120,7 @@ module Net new(host, user, passwd, acct) end end - + # # 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, @@ -178,7 +178,7 @@ module Net end end private :open_socket - + # # Establishes an FTP connection to host, optionally overriding the default # port. If the environment variable +SOCKS_SERVER+ is set, sets up the @@ -215,7 +215,7 @@ module Net end end private :sanitize - + def putline(line) if @debug_mode print "put: ", sanitize(line), "\n" @@ -224,7 +224,7 @@ module Net @sock.write(line) end private :putline - + def getline line = @sock.readline # if get EOF, raise EOFError line.sub!(/(\r\n|\n|\r)\z/n, "") @@ -234,7 +234,7 @@ module Net return line end private :getline - + def getmultiline line = getline buff = line @@ -248,7 +248,7 @@ module Net return buff << "\n" end private :getmultiline - + def getresp @last_response = getmultiline @last_response_code = @last_response[0, 3] @@ -264,7 +264,7 @@ module Net end end private :getresp - + def voidresp resp = getresp if resp[0] != ?2 @@ -272,7 +272,7 @@ module Net end end private :voidresp - + # # Sends a command and returns the response. # @@ -282,7 +282,7 @@ module Net return getresp end end - + # # Sends a command and expect a response beginning with '2'. # @@ -292,7 +292,7 @@ module Net voidresp end end - + def sendport(host, port) af = (@sock.peeraddr)[0] if af == "AF_INET" @@ -305,7 +305,7 @@ module Net voidcmd(cmd) end private :sendport - + def makeport sock = TCPServer.open(@sock.addr[3], 0) port = sock.addr[1] @@ -314,7 +314,7 @@ module Net return sock end private :makeport - + def makepasv if @sock.peeraddr[0] == "AF_INET" host, port = parse227(sendcmd("PASV")) @@ -325,13 +325,13 @@ module Net return host, port end private :makepasv - + def transfercmd(cmd, rest_offset = nil) if @passive host, port = makepasv conn = open_socket(host, port) if @resume and rest_offset - resp = sendcmd("REST " + rest_offset.to_s) + resp = sendcmd("REST " + rest_offset.to_s) if resp[0] != ?3 raise FTPReplyError, resp end @@ -345,7 +345,7 @@ module Net else sock = makeport if @resume and rest_offset - resp = sendcmd("REST " + rest_offset.to_s) + resp = sendcmd("REST " + rest_offset.to_s) if resp[0] != ?3 raise FTPReplyError, resp end @@ -362,7 +362,7 @@ module Net return conn end private :transfercmd - + def getaddress thishost = Socket.gethostname if not thishost.index(".") @@ -378,7 +378,7 @@ module Net return realuser + "@" + thishost end private :getaddress - + # # Logs in to the remote host. The session must have been previously # connected. If +user+ is the string "anonymous" and the +password+ is @@ -391,7 +391,7 @@ module Net if user == "anonymous" and passwd == nil passwd = getaddress end - + resp = "" synchronize do resp = sendcmd('USER ' + user) @@ -410,7 +410,7 @@ module Net @welcome = resp self.binary = true end - + # # Puts the connection into binary (image) mode, issues the given command, # and fetches the data returned, passing it to the associated block in @@ -431,7 +431,7 @@ module Net end end end - + # # 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 @@ -457,7 +457,7 @@ module Net end end end - + # # 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 @@ -489,7 +489,7 @@ module Net getresp raise end - + # # Puts the connection into ASCII (text) mode, issues the given server-side # command (such as "STOR myfile"), and sends the contents of the file @@ -554,7 +554,7 @@ module Net f.close if localfile end end - + # # Retrieves +remotefile+ in ASCII (text) mode, storing the result in # +localfile+. @@ -593,7 +593,7 @@ module Net gettextfile(remotefile, localfile, &block) end end - + # # Transfers +localfile+ to the server in binary mode, storing the result in # +remotefile+. If a block is supplied, calls it, passing in the transmitted @@ -618,7 +618,7 @@ module Net f.close end end - + # # Transfers +localfile+ to the server in ASCII (text) mode, storing the result # in +remotefile+. If callback or an associated block is supplied, calls it, @@ -653,7 +653,7 @@ module Net cmd = "ACCT " + account voidcmd(cmd) end - + # # Returns an array of filenames in the remote directory. # @@ -668,7 +668,7 @@ module Net end return files end - + # # 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. @@ -690,7 +690,7 @@ module Net end alias ls list alias dir list - + # # Renames a file on the server. # @@ -701,7 +701,7 @@ module Net end voidcmd("RNTO " + toname) end - + # # Deletes a file on the server. # @@ -715,7 +715,7 @@ module Net raise FTPReplyError, resp end end - + # # Changes the (remote) directory. # @@ -733,22 +733,22 @@ module Net cmd = "CWD " + dirname voidcmd(cmd) end - + # # Returns the size of the given (remote) filename. # def size(filename) with_binary(true) do resp = sendcmd("SIZE " + filename) - if resp[0, 3] != "213" + if resp[0, 3] != "213" raise FTPReplyError, resp end return resp[3..-1].strip.to_i end end - + MDTM_REGEXP = /^(\d\d\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/ # :nodoc: - + # # 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. @@ -758,7 +758,7 @@ module Net ary = str.scan(MDTM_REGEXP)[0].collect {|i| i.to_i} return local ? Time.local(*ary) : Time.gm(*ary) end - + # # Creates a remote directory. # @@ -766,14 +766,14 @@ module Net resp = sendcmd("MKD " + dirname) return parse257(resp) end - + # # Removes a remote directory. # def rmdir(dirname) voidcmd("RMD " + dirname) end - + # # Returns the current remote directory. # @@ -782,7 +782,7 @@ module Net return parse257(resp) end alias getdir pwd - + # # Returns system information. # @@ -793,7 +793,7 @@ module Net end return resp[4 .. -1] end - + # # Aborts the previous command (ABOR command). # @@ -807,7 +807,7 @@ module Net end return resp end - + # # Returns the status (STAT command). # @@ -817,7 +817,7 @@ module Net @sock.send(line, Socket::MSG_OOB) return getresp end - + # # Issues the MDTM command. TODO: more info. # @@ -827,7 +827,7 @@ module Net return resp[3 .. -1].strip end end - + # # Issues the HELP command. # @@ -838,7 +838,7 @@ module Net end sendcmd(cmd) end - + # # Exits the FTP session. # @@ -860,7 +860,7 @@ module Net cmd = "SITE " + arg voidcmd(cmd) end - + # # Closes the connection. Further operations are impossible until you open # a new connection with #connect. @@ -868,14 +868,14 @@ module Net def close @sock.close if @sock and not @sock.closed? end - + # # Returns +true+ iff the connection is closed. # def closed? @sock == nil or @sock.closed? end - + def parse227(resp) if resp[0, 3] != "227" raise FTPReplyError, resp @@ -894,7 +894,7 @@ module Net return host, port end private :parse227 - + def parse228(resp) if resp[0, 3] != "228" raise FTPReplyError, resp @@ -922,11 +922,11 @@ module Net end host = v6[0, 8].join(":") port = (numbers[19].to_i << 8) + numbers[20].to_i - end + end return host, port end private :parse228 - + def parse229(resp) if resp[0, 3] != "229" raise FTPReplyError, resp @@ -945,7 +945,7 @@ module Net return host, port end private :parse229 - + def parse257(resp) if resp[0, 3] != "257" raise FTPReplyError, resp diff --git a/lib/net/http.rb b/lib/net/http.rb index e3716b1bde..d95615f5c8 100644 --- a/lib/net/http.rb +++ b/lib/net/http.rb @@ -4,26 +4,26 @@ # Copyright (c) 1999-2007 Yukihiro Matsumoto # Copyright (c) 1999-2007 Minero Aoki # Copyright (c) 2001 GOTOU Yuuzou -# +# # Written and maintained by Minero Aoki <[email protected]>. # HTTPS support added by GOTOU Yuuzou <[email protected]>. # # 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. -# +# See Net::HTTP for an overview and examples. +# # NOTE: You can find Japanese version of this document here: # http://www.ruby-lang.org/ja/man/html/net_http.html -# +# #-- # $Id$ -#++ +#++ require 'net/protocol' require 'uri' @@ -36,29 +36,29 @@ module Net #:nodoc: # :startdoc: # == 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 to [RFC2616] # (http://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' # @@ -69,7 +69,7 @@ module Net #:nodoc: # puts res.body # # Example #4: More generic GET+print - # + # # require 'net/http' # # url = URI.parse('http://www.example.com/index.html') @@ -78,9 +78,9 @@ module Net #:nodoc: # http.request(req) # } # puts res.body - # + # # === Posting Form Data - # + # # require 'net/http' # require 'uri' # @@ -112,15 +112,15 @@ module Net #:nodoc: # res = Net::HTTP.post_form(URI.parse('http://www.example.com/search.cgi'), # {'q' => ['ruby', 'perl'], 'max' => '50'}) # puts res.body - # + # # === 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 # : @@ -128,20 +128,20 @@ module Net #:nodoc: # # 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']) @@ -154,16 +154,16 @@ module Net #:nodoc: # # 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. + # # 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 @@ -172,25 +172,25 @@ module Net #:nodoc: # 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. @@ -263,22 +263,22 @@ module Net #:nodoc: # 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. # class HTTP < Protocol @@ -338,7 +338,7 @@ module Net #:nodoc: # # Get body from target and output it to +$stdout+. The # target can either be specified as (+uri+), or as - # (+host+, +path+, +port+ = 80); so: + # (+host+, +path+, +port+ = 80); so: # # Net::HTTP.get_print URI.parse('http://www.example.com/index.html') # @@ -358,7 +358,7 @@ module Net #:nodoc: # 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: @@ -372,7 +372,7 @@ module Net #:nodoc: # 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 # @@ -442,9 +442,9 @@ module Net #:nodoc: BufferedIO end - # 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 + # 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 @@ -548,7 +548,7 @@ module Net #:nodoc: end # 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. @@ -655,9 +655,9 @@ module Net #:nodoc: # 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) # : @@ -665,7 +665,7 @@ module Net #:nodoc: # # connecting proxy.foo.org:8080 # : # } - # + # def HTTP.Proxy(p_addr, p_port = nil, p_user = nil, p_pass = nil) return self unless p_addr delta = ProxyDelta @@ -765,14 +765,14 @@ module Net #:nodoc: # and it defaults to an empty hash. # If +initheader+ doesn't have the key 'accept-encoding', then # a value of "gzip;q=1.0,deflate;q=0.6,identity;q=0.3" is used, - # so that gzip compression is used in preference to deflate - # compression, which is used in preference to no compression. + # so that gzip compression is used in preference to deflate + # compression, which is used in preference to no compression. # Ruby doesn't have libraries to support the compress (Lempel-Ziv) # compression, so that is not supported. The intent of this is # to reduce bandwidth by default. If this routine sets up # compression, then it does the decompression also, removing # the header as well to prevent confusion. Otherwise - # it leaves the body as it found it. + # it leaves the body as it found it. # # In version 1.1 (ruby 1.6), this method returns a pair of objects, # a Net::HTTPResponse object and the entity body string. @@ -787,7 +787,7 @@ module Net #:nodoc: # +dest+ argument is obsolete. # It still works but you must not use it. # - # In version 1.1, this method might raise an exception for + # 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". # @@ -798,7 +798,7 @@ module Net #:nodoc: # # # 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| @@ -827,7 +827,7 @@ module Net #:nodoc: r.delete("content-encoding") when "identity" ; # nothing needed - else + else ; # Don't do anything dramatic, unless we need to later end else @@ -845,21 +845,21 @@ module Net #:nodoc: # 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 + # + # 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'] # - def head(path, initheader = nil) + def head(path, initheader = nil) res = request(Head.new(path, initheader)) res.value unless @newimpl res @@ -867,11 +867,11 @@ module Net #:nodoc: # 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 @@ -879,18 +879,18 @@ module Net #:nodoc: # # +dest+ argument is obsolete. # It still works but you must not use it. - # - # In version 1.1, this method might raise an exception for + # + # 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| @@ -983,21 +983,21 @@ module Net #:nodoc: # 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'] @@ -1014,9 +1014,9 @@ module Net #:nodoc: # as an HTTPResponse object. # # Returns the response. - # + # # This method never raises Net::* exceptions. - # + # # response = http.request_head('/index.html') # p response['content-type'] # @@ -1026,21 +1026,21 @@ module Net #:nodoc: # 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 @@ -1068,7 +1068,7 @@ module Net #:nodoc: # 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') @@ -1082,14 +1082,14 @@ module Net #:nodoc: # 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. # def request(req, body = nil, &block) # :yield: +response+ @@ -1421,7 +1421,7 @@ module Net #:nodoc: raise HTTPHeaderSyntaxError, 'wrong Content-Length format' len.to_i end - + def content_length=(len) unless len @header.delete 'content-length' @@ -1431,7 +1431,7 @@ module Net #:nodoc: end # Returns "true" if the "transfer-encoding" header is present and - # set to "chunked". This is an HTTP/1.1 feature, allowing the + # 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. def chunked? @@ -1472,7 +1472,7 @@ module Net #:nodoc: return nil unless @header['content-type'] self['Content-Type'].split(';').first.to_s.split('/')[0].to_s.strip end - + # Returns a content type string such as "html". # This method returns nil if Content-Type: header field does not exist # or sub-type is not given (e.g. "Content-Type: text"). @@ -1515,7 +1515,7 @@ module Net #:nodoc: # http.form_data = {"q" => "ruby", "lang" => "en"} # http.form_data = {"q" => ["ruby", "perl"], "lang" => "en"} # http.set_form_data({"q" => "ruby", "lang" => "en"}, ';') - # + # def set_form_data(params, sep = '&') self.body = params.map {|k, v| encode_kvpair(k, v) }.flatten.join(sep) self.content_type = 'application/x-www-form-urlencoded' @@ -1691,14 +1691,14 @@ module Net #:nodoc: buf << "\r\n" sock.write buf end - + end - # + # # HTTP request class. This class wraps request header and entity path. # You *must* use its subclass, Net::HTTP::Get, Post, Head. - # + # class HTTPRequest < HTTPGenericRequest # Creates HTTP request object. @@ -1838,17 +1838,17 @@ module Net #:nodoc: # 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 + # 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 + # 100 HTTPContinue # 101 HTTPSwitchProtocol - # + # # 2xx HTTPSuccess # 200 HTTPOK # 201 HTTPCreated @@ -1857,7 +1857,7 @@ module Net #:nodoc: # 204 HTTPNoContent # 205 HTTPResetContent # 206 HTTPPartialContent - # + # # 3xx HTTPRedirection # 300 HTTPMultipleChoice # 301 HTTPMovedPermanently @@ -1866,7 +1866,7 @@ module Net #:nodoc: # 304 HTTPNotModified # 305 HTTPUseProxy # 307 HTTPTemporaryRedirect - # + # # 4xx HTTPClientError # 400 HTTPBadRequest # 401 HTTPUnauthorized @@ -1886,7 +1886,7 @@ module Net #:nodoc: # 415 HTTPUnsupportedMediaType # 416 HTTPRequestedRangeNotSatisfiable # 417 HTTPExpectationFailed - # + # # 5xx HTTPServerError # 500 HTTPInternalServerError # 501 HTTPNotImplemented @@ -1894,7 +1894,7 @@ module Net #:nodoc: # 503 HTTPServiceUnavailable # 504 HTTPGatewayTimeOut # 505 HTTPVersionNotSupported - # + # # xxx HTTPUnknownResponse # class HTTPResponse @@ -2160,7 +2160,7 @@ module Net #:nodoc: # next is to fix bug in RDoc, where the private inside class << self # spills out. - public + public include HTTPHeader @@ -2193,7 +2193,7 @@ module Net #:nodoc: # To allow Net::HTTP 1.1 style assignment # e.g. # response, body = Net::HTTP.get(....) - # + # 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 diff --git a/lib/net/https.rb b/lib/net/https.rb index 051e712dc4..636ae1be4d 100644 --- a/lib/net/https.rb +++ b/lib/net/https.rb @@ -17,7 +17,7 @@ == Version $Id$ - + 2001-11-06: Contiributed to Ruby/OpenSSL project. 2004-03-06: Some code is merged in to net/http. diff --git a/lib/net/imap.rb b/lib/net/imap.rb index 3364561508..161e7ac32a 100644 --- a/lib/net/imap.rb +++ b/lib/net/imap.rb @@ -9,7 +9,7 @@ # Documentation: Shugo Maeda, with RDoc conversion and overview by William # Webber. # -# See Net::IMAP for documentation. +# See Net::IMAP for documentation. # @@ -45,12 +45,12 @@ module Net # 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. + # related commands implicitly operate. # # Messages have two sorts of identifiers: message sequence - # numbers, and UIDs. + # numbers, and UIDs. # - # Message sequence numbers number messages within a mail box + # 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 @@ -58,7 +58,7 @@ module Net # 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 + # 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 @@ -91,11 +91,11 @@ module Net # 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") @@ -103,7 +103,7 @@ module Net # 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 @@ -113,9 +113,9 @@ module Net # # 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. + # the selected mailbox does not exists; etc. # - # BAD:: the request from the client does not follow the server's + # 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 @@ -147,8 +147,8 @@ module Net # # 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. + # between UTF-8 and UTF-16), and Net::IMAP::ResponseParseError is + # thrown if a server response is non-parseable. # # # == References @@ -274,10 +274,10 @@ module Net # 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, + # the server. See Net::IMAP::LoginAuthenticator, # Net::IMAP::CramMD5Authenticator, and Net::IMAP::DigestMD5Authenticator # for examples. - # + # # # If +auth_type+ refers to an existing authenticator, it will be # replaced by the new one. @@ -314,7 +314,7 @@ module Net # # 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 + # it is up to the user of the class to ensure that # a certain capability is supported by a server before # using it. def capability @@ -355,7 +355,7 @@ module Net # the authentication mechanism to be used. Currently Net::IMAP # supports authentication mechanisms: # - # LOGIN:: login using cleartext user and password. + # 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 @@ -403,7 +403,7 @@ module Net end # Sends a SELECT command to select a +mailbox+ so that messages - # in the +mailbox+ can be accessed. + # 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], @@ -454,7 +454,7 @@ module Net # Sends a RENAME command to change the name of the +mailbox+ to # +newname+. # - # A Net::IMAP::NoResponseError is raised if a mailbox with the + # 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+. @@ -501,8 +501,8 @@ module Net # 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=[:Noselect], delim="/", name="foo/">, \\ + # #<Net::IMAP::MailboxList attr=[:Noinferiors, :Marked], delim="/", name="foo/bar">, \\ # #<Net::IMAP::MailboxList attr=[:Noinferiors], delim="/", name="foo/baz">] def list(refname, mailbox) synchronize do @@ -555,7 +555,7 @@ module Net # then that user will be stripped of any rights to that mailbox. # The IMAP ACL commands are described in [RFC-2086]. def setacl(mailbox, user, rights) - if rights.nil? + if rights.nil? send_command("SETACL", mailbox, user, "") else send_command("SETACL", mailbox, user, rights) @@ -574,7 +574,7 @@ module Net # 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 + # "subscribed". +refname+ and +mailbox+ are interpreted as # for #list(). # The return value is an array of +Net::IMAP::MailboxList+. def lsub(refname, mailbox) @@ -597,7 +597,7 @@ module Net # p imap.status("inbox", ["MESSAGES", "RECENT"]) # #=> {"RECENT"=>0, "MESSAGES"=>44} # - # A Net::IMAP::NoResponseError is raised if status values + # A Net::IMAP::NoResponseError is raised if status values # for +mailbox+ cannot be returned, for instance because it # does not exist. def status(mailbox, attr) @@ -608,9 +608,9 @@ module Net end # Sends a APPEND command to append the +message+ to the end of - # the +mailbox+. The optional +flags+ argument is an array 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 + # +date_time+ argument specifies the creation time to assign to the # new message; it defaults to the current time. # For example: # @@ -618,7 +618,7 @@ module Net # Subject: hello # From: [email protected] # To: [email protected] - # + # # hello world # EOF # @@ -637,7 +637,7 @@ module Net # Sends a CHECK command to request a checkpoint of the currently # selected mailbox. This performs implementation-specific - # housekeeping, for instance, reconciling the mailbox's + # housekeeping, for instance, reconciling the mailbox's # in-memory and on-disk state. def check send_command("CHECK") @@ -661,8 +661,8 @@ module Net # 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 + # 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. # @@ -686,7 +686,7 @@ module Net # # OR <search-key> <search-key>:: "or" two search keys together. # - # ON <date>:: messages with an internal date exactly equal to <date>, + # 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>. @@ -694,7 +694,7 @@ module Net # 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"]) @@ -717,8 +717,8 @@ module Net # 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=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"}>] @@ -741,9 +741,9 @@ module Net end # 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 + # 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. @@ -751,8 +751,8 @@ module Net # 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=6, attr={"FLAGS"=>[:Seen, :Deleted]}>, \\ + # #<Net::IMAP::FetchData seqno=7, attr={"FLAGS"=>[:Seen, :Deleted]}>, \\ # #<Net::IMAP::FetchData seqno=8, attr={"FLAGS"=>[:Seen, :Deleted]}>] def store(set, attr, flags) return store_internal("STORE", set, attr, flags) @@ -794,9 +794,9 @@ module Net return sort_internal("UID SORT", sort_keys, search_keys, charset) end - # Adds a response handler. For example, to detect when + # 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), + # indicates new messages being added to the mail box), # you could add the following handler after selecting the # mailbox. # @@ -832,7 +832,7 @@ module Net return thread_internal("THREAD", algorithm, search_keys, charset) end - # As for #thread(), but returns unique identifiers instead of + # As for #thread(), but returns unique identifiers instead of # message sequence numbers. def uid_thread(algorithm, search_keys, charset) return thread_internal("UID THREAD", algorithm, search_keys, charset) @@ -897,7 +897,7 @@ module Net # 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. - # if options[:ssl] is a hash, it's passed to + # if options[:ssl] is a hash, it's passed to # OpenSSL::SSL::SSLContext#set_params as parameters. # # The most common errors are: @@ -908,7 +908,7 @@ module Net # 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 + # Net::IMAP::ByeResponseError:: we connected to the host, but they # immediately said goodbye to us. def initialize(host, port_or_options = {}, usessl = false, certs = nil, verify = true) @@ -1092,7 +1092,7 @@ module Net @tagno += 1 return format("%s%04d", @tag_prefix, @tagno) end - + def put_string(str) @sock.print(str) if @@debug @@ -1160,7 +1160,7 @@ module Net put_string(str) end end - + def send_quoted_string(str) put_string('"' + str.gsub(/["\\]/n, "\\\\\\&") + '"') end @@ -1313,7 +1313,7 @@ module Net context = SSLContext.new context.set_params(params) if defined?(VerifyCallbackProc) - context.verify_callback = VerifyCallbackProc + context.verify_callback = VerifyCallbackProc end @sock = SSLSocket.new(@sock, context) @sock.sync_close = true @@ -1448,109 +1448,109 @@ module Net end # 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. ContinuationRequest = Struct.new(: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. UntaggedResponse = Struct.new(: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. # TaggedResponse = Struct.new(:tag, :name, :data, :raw_data) - + # 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. - # + # ResponseText = Struct.new(:code, :text) - # + # # 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. # ResponseCode = Struct.new(:name, :data) # 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. # MailboxList = Struct.new(:attr, :delim, :name) @@ -1559,78 +1559,78 @@ module Net # 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. # MailboxQuota = Struct.new(:mailbox, :usage, :quota) # 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. # MailboxQuotaRoot = Struct.new(:mailbox, :quotaroots) # 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. # MailboxACLItem = Struct.new(:user, :rights) # 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. - # + # StatusData = Struct.new(:mailbox, :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>>] @@ -1657,67 +1657,67 @@ module Net # Equivalent to BODY[TEXT]. # [UID] # A number expressing the unique identifier of the message. - # + # FetchData = Struct.new(:seqno, :attr) # 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. - # + # Envelope = Struct.new(:date, :subject, :from, :sender, :reply_to, :to, :cc, :bcc, :in_reply_to, :message_id) - # + # # 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. # Address = Struct.new(:name, :route, :mailbox, :host) - # + # # 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. - # + # ContentDisposition = Struct.new(:dsp_type, :param) - # Net::IMAP::ThreadMember represents a thread-node returned + # Net::IMAP::ThreadMember represents a thread-node returned # by Net::IMAP#thread # # ==== Fields: @@ -1730,37 +1730,37 @@ module Net ThreadMember = Struct.new(:seqno, :children) # 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. - # + # class BodyTypeBasic < Struct.new(:media_type, :subtype, :param, :content_id, :description, :encoding, :size, @@ -1771,7 +1771,7 @@ module Net end # Obsolete: use +subtype+ instead. Calling this will - # generate a warning message to +stderr+, then return + # generate a warning message to +stderr+, then return # the value of +subtype+. def media_subtype $stderr.printf("warning: media_subtype is obsolete.\n") @@ -1781,13 +1781,13 @@ module Net end # 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. - # + # class BodyTypeText < Struct.new(:media_type, :subtype, :param, :content_id, :description, :encoding, :size, @@ -1799,7 +1799,7 @@ module Net end # Obsolete: use +subtype+ instead. Calling this will - # generate a warning message to +stderr+, then return + # generate a warning message to +stderr+, then return # the value of +subtype+. def media_subtype $stderr.printf("warning: media_subtype is obsolete.\n") @@ -1809,13 +1809,13 @@ module Net end # 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. # class BodyTypeMessage < Struct.new(:media_type, :subtype, @@ -1829,7 +1829,7 @@ module Net end # Obsolete: use +subtype+ instead. Calling this will - # generate a warning message to +stderr+, then return + # generate a warning message to +stderr+, then return # the value of +subtype+. def media_subtype $stderr.printf("warning: media_subtype is obsolete.\n") @@ -1838,29 +1838,29 @@ module Net end end - # Net::IMAP::BodyTypeMultipart represents multipart body structures + # 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. - # + # class BodyTypeMultipart < Struct.new(:media_type, :subtype, :parts, :param, :disposition, :language, @@ -1870,7 +1870,7 @@ module Net end # Obsolete: use +subtype+ instead. Calling this will - # generate a warning message to +stderr+, then return + # generate a warning message to +stderr+, then return # the value of +subtype+. def media_subtype $stderr.printf("warning: media_subtype is obsolete.\n") @@ -2671,35 +2671,35 @@ module Net def thread_branch(token) rootmember = nil lastmember = nil - + while true shift_token # ignore first T_LPAR token = lookahead - + case token.symbol when T_NUMBER # new member newmember = ThreadMember.new(number, []) if rootmember.nil? rootmember = newmember - else + else lastmember.children << newmember - end + end lastmember = newmember - when T_SPACE - # do nothing + when T_SPACE + # do nothing when T_LPAR if rootmember.nil? # dummy member lastmember = rootmember = ThreadMember.new(nil, []) - end - + end + lastmember.children << thread_branch(token) when T_RPAR - break - end + break + end end - + return rootmember end @@ -3176,7 +3176,7 @@ module Net @user = user @password = password end - end + end add_authenticator "PLAIN", PlainAuthenticator # Authenticator for the "CRAM-MD5" authentication type. See @@ -3341,7 +3341,7 @@ module Net class BadResponseError < ResponseError end - # Error raised upon a "BYE" response from the server, indicating + # 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 ByeResponseError < ResponseError @@ -3426,7 +3426,7 @@ EOF usage exit(1) end - + imap = Net::IMAP.new($host, :port => $port, :ssl => $ssl) begin password = get_password diff --git a/lib/net/pop.rb b/lib/net/pop.rb index accac72905..6a45e3b5f0 100644 --- a/lib/net/pop.rb +++ b/lib/net/pop.rb @@ -3,20 +3,20 @@ # Copyright (c) 1999-2007 Yukihiro Matsumoto. # # Copyright (c) 1999-2007 Minero Aoki. -# +# # Written & maintained by Minero Aoki <[email protected]>. # # 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. -# +# # NOTE: You can find Japanese version of this document at: # http://www.ruby-lang.org/ja/man/html/net_pop.html -# +# # $Id$ -# +# # See Net::POP3 for documentation. # @@ -45,25 +45,25 @@ module Net # = Net::POP3 # # == What is This Library? - # - # This library provides functionality for retrieving + # + # This library provides functionality for retrieving # email via POP3, the Post Office Protocol version 3. For details # of POP3, see [RFC1939] (http://www.ietf.org/rfc/rfc1939.txt). - # + # # == Examples - # - # === Retrieving Messages - # - # This example retrieves messages from the server and deletes them + # + # === 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? @@ -80,19 +80,19 @@ module Net # 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? @@ -109,11 +109,11 @@ module Net # 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? @@ -128,11 +128,11 @@ module Net # 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| @@ -141,14 +141,14 @@ module Net # 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| @@ -159,41 +159,41 @@ module Net # 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. - # + # class POP3 < Protocol Revision = %q$Revision$.split[1] @@ -210,7 +210,7 @@ module Net def POP3.default_pop3_port 110 end - + # The default port for POP3S connections, port 995 def POP3.default_pop3s_port 995 @@ -375,7 +375,7 @@ module Net # Session management # - # Creates a new POP3 object and open the connection. Equivalent to + # Creates a new POP3 object and open the connection. Equivalent to # # Net::POP3.new(address, port, isapop).start(account, password) # @@ -396,7 +396,7 @@ module Net isapop = false, &block) # :yield: pop new(address, port, isapop).start(account, password, &block) end - + # Creates a new POP3 object. # # +address+ is the hostname or ip address of your POP3 server. @@ -412,7 +412,7 @@ module Net @ssl_params = POP3.ssl_params @port = port @apop = isapop - + @command = nil @socket = nil @started = false @@ -434,7 +434,7 @@ module Net def use_ssl? return !@ssl_params.nil? end - + # call-seq: # Net::POP#enable_ssl(params = {}) # @@ -451,7 +451,7 @@ module Net @port = port || @port end end - + def disable_ssl @ssl_params = nil end @@ -635,7 +635,7 @@ module Net # Yields each message to the passed-in block in turn. # Equivalent to: - # + # # pop3.mails.each do |popmail| # .... # end @@ -742,7 +742,7 @@ module Net # # 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 + # 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. # @@ -753,7 +753,7 @@ module Net # n = 1 # pop.mails.each do |popmail| # File.open("inbox/#{n}", 'w') do |f| - # f.write popmail.pop + # f.write popmail.pop # end # popmail.delete # n += 1 @@ -792,7 +792,7 @@ module Net alias all pop #:nodoc: obsolete alias mail pop #:nodoc: obsolete - # Fetches the message header and +lines+ lines of body. + # Fetches the message header and +lines+ lines of body. # # The optional +dest+ argument is obsolete. # @@ -804,7 +804,7 @@ module Net dest end - # Fetches the message header. + # Fetches the message header. # # The optional +dest+ argument is obsolete. # @@ -933,7 +933,7 @@ module Net @socket.each_message_chunk(&block) } end - + def dele(num) check_response(critical { get_response('DELE %d', num) }) end diff --git a/lib/net/protocol.rb b/lib/net/protocol.rb index e26c849338..e2423f2986 100644 --- a/lib/net/protocol.rb +++ b/lib/net/protocol.rb @@ -121,7 +121,7 @@ module Net # :nodoc: return rbuf_consume(@rbuf.size) end end - + def readline readuntil("\n").chop end @@ -228,7 +228,7 @@ module Net # :nodoc: LOG_on() LOG "read message (#{read_bytes} bytes)" end - + # *library private* (cannot handle 'break') def each_list_item while (str = readuntil("\r\n")) != ".\r\n" diff --git a/lib/net/smtp.rb b/lib/net/smtp.rb index b58e73029b..a84b7ba154 100644 --- a/lib/net/smtp.rb +++ b/lib/net/smtp.rb @@ -1,23 +1,23 @@ # = net/smtp.rb -# +# # Copyright (c) 1999-2007 Yukihiro Matsumoto. # # Copyright (c) 1999-2007 Minero Aoki. -# +# # Written & maintained by Minero Aoki <[email protected]>. # # 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. -# +# # NOTE: You can find Japanese version of this document at: # http://www.ruby-lang.org/ja/man/html/net_smtp.html -# +# # $Id$ # -# See Net::SMTP for documentation. -# +# See Net::SMTP for documentation. +# require 'net/protocol' require 'digest/md5' @@ -69,103 +69,103 @@ module Net # = 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] (http://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. # (http://www.ruby-lang.org/en/raa.html) - # + # # FYI: the official documentation on internet mail is: [RFC2822] (http://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 + # 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 <[email protected]> # To: Destination Address <[email protected]> # Subject: test message # Date: Sat, 23 Jun 2001 16:26:43 +0900 # Message-Id: <[email protected]> - # + # # This is a test message. # END_OF_MESSAGE - # + # # require 'net/smtp' # Net::SMTP.start('your.smtp.server', 25) do |smtp| # smtp.send_message msgstr, # '[email protected]', # end - # + # # === Closing the Session - # - # You MUST close the SMTP session after sending messages, by calling + # + # 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 + # 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) @@ -196,7 +196,7 @@ module Net def SMTP.default_ssl_context OpenSSL::SSL::SSLContext.new end - + # # Creates a new Net::SMTP object. # @@ -223,7 +223,7 @@ module Net @starttls = false @ssl_context = nil end - + # Provide human-readable stringification of class state. def inspect "#<#{self.class} #{@address}:#{@port} started=#{@started}>" @@ -235,7 +235,7 @@ module Net end # - # Set whether to use ESMTP or not. This should be done before + # 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 @@ -310,7 +310,7 @@ module Net end alias enable_ssl enable_tls - + # Disables SMTP/TLS for this object. Must be called before the # connection is established to have any effect. def disable_tls @@ -336,7 +336,7 @@ module Net def starttls_auto? @starttls == :auto end - + # Enables SMTP/TLS (STARTTLS) for this object. # +context+ is a OpenSSL::SSL::SSLContext object. def enable_starttls(context = SMTP.default_ssl_context) @@ -413,7 +413,7 @@ module Net # 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 @@ -437,7 +437,7 @@ module Net # +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'. + # server (see overview comments); it defaults to 'localhost'. # # The remaining arguments are used for SMTP authentication, if required # or desired. +user+ is the account name; +secret+ is your password @@ -476,33 +476,33 @@ module Net # +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 + # 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. + # 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 + # 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' + # require 'net/smtp' # smtp = Net::SMTP.new('smtp.mail.server', 25) # smtp.start(helo_domain, account, password, authtype) do |smtp| # smtp.send_message msgstr, '[email protected]', ['[email protected]'] - # end + # 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. + # started. # # === Errors # @@ -548,7 +548,7 @@ module Net check_auth_method(authtype || DEFAULT_AUTH_TYPE) check_auth_args user, secret end - s = timeout(@open_timeout) { TCPSocket.open(@address, @port) } + s = timeout(@open_timeout) { TCPSocket.open(@address, @port) } logging "Connection opened: #{@address}:#{@port}" @socket = new_internet_message_io(tls? ? tlsconnect(s) : s) check_response critical { recv_response() } @@ -621,7 +621,7 @@ module Net # # 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 + # binary message with this method. +msgstr+ should include both # the message headers and body. # # +from_addr+ is a String representing the source mail address. @@ -852,7 +852,7 @@ module Net # From: [email protected] # To: [email protected] # Subject: I found a bug - # + # # Check vm.c:58879. # EndMessage # diff --git a/lib/net/telnet.rb b/lib/net/telnet.rb index 67fd656c63..98285a944b 100644 --- a/lib/net/telnet.rb +++ b/lib/net/telnet.rb @@ -1,7 +1,7 @@ # = net/telnet.rb - Simple Telnet Client Library -# +# # Author:: Wakou Aoyama <[email protected]> -# Documentation:: William Webber and Wakou Aoyama +# Documentation:: William Webber and Wakou Aoyama # # This file holds the class Net::Telnet, which provides client-side # telnet functionality. @@ -13,7 +13,7 @@ require "socket" require "delegate" require "timeout" require "English" - + module Net # @@ -50,11 +50,11 @@ module Net # 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; + # 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 + # #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, @@ -63,21 +63,21 @@ module Net # 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, @@ -97,73 +97,73 @@ module Net # :stopdoc: IAC = 255.chr # "\377" # "\xff" # interpret as command - DONT = 254.chr # "\376" # "\xfe" # you are not to use option - DO = 253.chr # "\375" # "\xfd" # please, you use option - WONT = 252.chr # "\374" # "\xfc" # I won't use option - WILL = 251.chr # "\373" # "\xfb" # I will use option - SB = 250.chr # "\372" # "\xfa" # interpret as subnegotiation - GA = 249.chr # "\371" # "\xf9" # you may reverse the line - EL = 248.chr # "\370" # "\xf8" # erase the current line - EC = 247.chr # "\367" # "\xf7" # erase the current character - AYT = 246.chr # "\366" # "\xf6" # are you there - AO = 245.chr # "\365" # "\xf5" # abort output--but let prog finish - IP = 244.chr # "\364" # "\xf4" # interrupt process--permanently - BREAK = 243.chr # "\363" # "\xf3" # break - DM = 242.chr # "\362" # "\xf2" # data mark--for connect. cleaning - NOP = 241.chr # "\361" # "\xf1" # nop - SE = 240.chr # "\360" # "\xf0" # end sub negotiation - EOR = 239.chr # "\357" # "\xef" # end of record (transparent mode) - ABORT = 238.chr # "\356" # "\xee" # Abort process - SUSP = 237.chr # "\355" # "\xed" # Suspend process - EOF = 236.chr # "\354" # "\xec" # End of file - SYNCH = 242.chr # "\362" # "\xf2" # for telfunc calls - - OPT_BINARY = 0.chr # "\000" # "\x00" # Binary Transmission - OPT_ECHO = 1.chr # "\001" # "\x01" # Echo - OPT_RCP = 2.chr # "\002" # "\x02" # Reconnection - OPT_SGA = 3.chr # "\003" # "\x03" # Suppress Go Ahead - OPT_NAMS = 4.chr # "\004" # "\x04" # Approx Message Size Negotiation - OPT_STATUS = 5.chr # "\005" # "\x05" # Status - OPT_TM = 6.chr # "\006" # "\x06" # Timing Mark - OPT_RCTE = 7.chr # "\a" # "\x07" # Remote Controlled Trans and Echo - OPT_NAOL = 8.chr # "\010" # "\x08" # Output Line Width - OPT_NAOP = 9.chr # "\t" # "\x09" # Output Page Size - OPT_NAOCRD = 10.chr # "\n" # "\x0a" # Output Carriage-Return Disposition - OPT_NAOHTS = 11.chr # "\v" # "\x0b" # Output Horizontal Tab Stops - OPT_NAOHTD = 12.chr # "\f" # "\x0c" # Output Horizontal Tab Disposition - OPT_NAOFFD = 13.chr # "\r" # "\x0d" # Output Formfeed Disposition - OPT_NAOVTS = 14.chr # "\016" # "\x0e" # Output Vertical Tabstops - OPT_NAOVTD = 15.chr # "\017" # "\x0f" # Output Vertical Tab Disposition - OPT_NAOLFD = 16.chr # "\020" # "\x10" # Output Linefeed Disposition - OPT_XASCII = 17.chr # "\021" # "\x11" # Extended ASCII - OPT_LOGOUT = 18.chr # "\022" # "\x12" # Logout - OPT_BM = 19.chr # "\023" # "\x13" # Byte Macro - OPT_DET = 20.chr # "\024" # "\x14" # Data Entry Terminal - OPT_SUPDUP = 21.chr # "\025" # "\x15" # SUPDUP - OPT_SUPDUPOUTPUT = 22.chr # "\026" # "\x16" # SUPDUP Output - OPT_SNDLOC = 23.chr # "\027" # "\x17" # Send Location - OPT_TTYPE = 24.chr # "\030" # "\x18" # Terminal Type - OPT_EOR = 25.chr # "\031" # "\x19" # End of Record - OPT_TUID = 26.chr # "\032" # "\x1a" # TACACS User Identification - OPT_OUTMRK = 27.chr # "\e" # "\x1b" # Output Marking - OPT_TTYLOC = 28.chr # "\034" # "\x1c" # Terminal Location Number - OPT_3270REGIME = 29.chr # "\035" # "\x1d" # Telnet 3270 Regime - OPT_X3PAD = 30.chr # "\036" # "\x1e" # X.3 PAD - OPT_NAWS = 31.chr # "\037" # "\x1f" # Negotiate About Window Size - OPT_TSPEED = 32.chr # " " # "\x20" # Terminal Speed - OPT_LFLOW = 33.chr # "!" # "\x21" # Remote Flow Control - OPT_LINEMODE = 34.chr # "\"" # "\x22" # Linemode - OPT_XDISPLOC = 35.chr # "#" # "\x23" # X Display Location - OPT_OLD_ENVIRON = 36.chr # "$" # "\x24" # Environment Option - OPT_AUTHENTICATION = 37.chr # "%" # "\x25" # Authentication Option - OPT_ENCRYPT = 38.chr # "&" # "\x26" # Encryption Option - OPT_NEW_ENVIRON = 39.chr # "'" # "\x27" # New Environment Option - OPT_EXOPL = 255.chr # "\377" # "\xff" # Extended-Options-List - - NULL = "\000" - CR = "\015" - LF = "\012" - EOL = CR + LF + DONT = 254.chr # "\376" # "\xfe" # you are not to use option + DO = 253.chr # "\375" # "\xfd" # please, you use option + WONT = 252.chr # "\374" # "\xfc" # I won't use option + WILL = 251.chr # "\373" # "\xfb" # I will use option + SB = 250.chr # "\372" # "\xfa" # interpret as subnegotiation + GA = 249.chr # "\371" # "\xf9" # you may reverse the line + EL = 248.chr # "\370" # "\xf8" # erase the current line + EC = 247.chr # "\367" # "\xf7" # erase the current character + AYT = 246.chr # "\366" # "\xf6" # are you there + AO = 245.chr # "\365" # "\xf5" # abort output--but let prog finish + IP = 244.chr # "\364" # "\xf4" # interrupt process--permanently + BREAK = 243.chr # "\363" # "\xf3" # break + DM = 242.chr # "\362" # "\xf2" # data mark--for connect. cleaning + NOP = 241.chr # "\361" # "\xf1" # nop + SE = 240.chr # "\360" # "\xf0" # end sub negotiation + EOR = 239.chr # "\357" # "\xef" # end of record (transparent mode) + ABORT = 238.chr # "\356" # "\xee" # Abort process + SUSP = 237.chr # "\355" # "\xed" # Suspend process + EOF = 236.chr # "\354" # "\xec" # End of file + SYNCH = 242.chr # "\362" # "\xf2" # for telfunc calls + + OPT_BINARY = 0.chr # "\000" # "\x00" # Binary Transmission + OPT_ECHO = 1.chr # "\001" # "\x01" # Echo + OPT_RCP = 2.chr # "\002" # "\x02" # Reconnection + OPT_SGA = 3.chr # "\003" # "\x03" # Suppress Go Ahead + OPT_NAMS = 4.chr # "\004" # "\x04" # Approx Message Size Negotiation + OPT_STATUS = 5.chr # "\005" # "\x05" # Status + OPT_TM = 6.chr # "\006" # "\x06" # Timing Mark + OPT_RCTE = 7.chr # "\a" # "\x07" # Remote Controlled Trans and Echo + OPT_NAOL = 8.chr # "\010" # "\x08" # Output Line Width + OPT_NAOP = 9.chr # "\t" # "\x09" # Output Page Size + OPT_NAOCRD = 10.chr # "\n" # "\x0a" # Output Carriage-Return Disposition + OPT_NAOHTS = 11.chr # "\v" # "\x0b" # Output Horizontal Tab Stops + OPT_NAOHTD = 12.chr # "\f" # "\x0c" # Output Horizontal Tab Disposition + OPT_NAOFFD = 13.chr # "\r" # "\x0d" # Output Formfeed Disposition + OPT_NAOVTS = 14.chr # "\016" # "\x0e" # Output Vertical Tabstops + OPT_NAOVTD = 15.chr # "\017" # "\x0f" # Output Vertical Tab Disposition + OPT_NAOLFD = 16.chr # "\020" # "\x10" # Output Linefeed Disposition + OPT_XASCII = 17.chr # "\021" # "\x11" # Extended ASCII + OPT_LOGOUT = 18.chr # "\022" # "\x12" # Logout + OPT_BM = 19.chr # "\023" # "\x13" # Byte Macro + OPT_DET = 20.chr # "\024" # "\x14" # Data Entry Terminal + OPT_SUPDUP = 21.chr # "\025" # "\x15" # SUPDUP + OPT_SUPDUPOUTPUT = 22.chr # "\026" # "\x16" # SUPDUP Output + OPT_SNDLOC = 23.chr # "\027" # "\x17" # Send Location + OPT_TTYPE = 24.chr # "\030" # "\x18" # Terminal Type + OPT_EOR = 25.chr # "\031" # "\x19" # End of Record + OPT_TUID = 26.chr # "\032" # "\x1a" # TACACS User Identification + OPT_OUTMRK = 27.chr # "\e" # "\x1b" # Output Marking + OPT_TTYLOC = 28.chr # "\034" # "\x1c" # Terminal Location Number + OPT_3270REGIME = 29.chr # "\035" # "\x1d" # Telnet 3270 Regime + OPT_X3PAD = 30.chr # "\036" # "\x1e" # X.3 PAD + OPT_NAWS = 31.chr # "\037" # "\x1f" # Negotiate About Window Size + OPT_TSPEED = 32.chr # " " # "\x20" # Terminal Speed + OPT_LFLOW = 33.chr # "!" # "\x21" # Remote Flow Control + OPT_LINEMODE = 34.chr # "\"" # "\x22" # Linemode + OPT_XDISPLOC = 35.chr # "#" # "\x23" # X Display Location + OPT_OLD_ENVIRON = 36.chr # "$" # "\x24" # Environment Option + OPT_AUTHENTICATION = 37.chr # "%" # "\x25" # Authentication Option + OPT_ENCRYPT = 38.chr # "&" # "\x26" # Encryption Option + OPT_NEW_ENVIRON = 39.chr # "'" # "\x27" # New Environment Option + OPT_EXOPL = 255.chr # "\377" # "\xff" # Extended-Options-List + + NULL = "\000" + CR = "\015" + LF = "\012" + EOL = CR + LF REVISION = '$Id$' # :startdoc: @@ -174,13 +174,13 @@ module Net # 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 @@ -198,16 +198,16 @@ module Net # # The options have the following meanings: # - # Host:: the hostname or IP address of the host to connect to, as a String. + # 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. + # 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 + # 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 @@ -217,13 +217,13 @@ module Net # 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. + # 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 + # preceded by '#', sent traffic preceded by '>', and # received traffic preceded by '<'. By default, not dump log # is kept. # @@ -233,7 +233,7 @@ module Net # ready to receive a new command. By default, this regular # expression is /[$%#>] \z/n. # - # Telnetmode:: a boolean value, true by default. In telnet mode, + # 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() @@ -255,11 +255,11 @@ module Net # 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 + # 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 + # 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 @@ -267,12 +267,12 @@ module Net # # 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 + # 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. # - def initialize(options) # :yield: mesg + def initialize(options) # :yield: mesg @options = options @options["Host"] = "localhost" unless @options.has_key?("Host") @options["Port"] = 23 unless @options.has_key?("Port") @@ -280,7 +280,7 @@ module Net @options["Timeout"] = 10 unless @options.has_key?("Timeout") @options["Waittime"] = 0 unless @options.has_key?("Waittime") unless @options.has_key?("Binmode") - @options["Binmode"] = false + @options["Binmode"] = false else unless (true == @options["Binmode"] or false == @options["Binmode"]) raise ArgumentError, "Binmode option must be true or false" @@ -288,7 +288,7 @@ module Net end unless @options.has_key?("Telnetmode") - @options["Telnetmode"] = true + @options["Telnetmode"] = true else unless (true == @options["Telnetmode"] or false == @options["Telnetmode"]) raise ArgumentError, "Telnetmode option must be true or false" @@ -374,7 +374,7 @@ module Net # 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. - attr :sock + attr :sock # Set telnet command interpretation on (+mode+ == true) or off # (+mode+ == false), or return the current value (+mode+ not @@ -408,7 +408,7 @@ module Net def binmode(mode = nil) case mode when nil - @options["Binmode"] + @options["Binmode"] when true, false @options["Binmode"] = mode else @@ -428,7 +428,7 @@ module Net # Preprocess received data from the host. # # Performs newline conversion and detects telnet command sequences. - # Called automatically by #waitfor(). You should only use this + # 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. def preprocess(string) @@ -494,9 +494,9 @@ module Net # 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 + # 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 + # 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. # @@ -510,7 +510,7 @@ module Net # 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, + # 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 @@ -527,7 +527,7 @@ module Net # EOFError will be raised. Otherwise, defaults to the old # behaviour that the function will return whatever data # has been received already, or nil if nothing was received. - # + # def waitfor(options) # :yield: recvdata time_out = @options["Timeout"] waittime = @options["Waittime"] @@ -622,7 +622,7 @@ module Net # 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 + # newlines may be converted and telnet command sequences escaped # depending upon the values of telnetmode, binmode, and telnet options # set by the host. def print(string) @@ -657,7 +657,7 @@ module Net # 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 + # 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. # @@ -702,7 +702,7 @@ module Net # # The username and password can either be provided as two string # arguments in that order, or as a hash with keys "Name" and - # "Password". + # "Password". # # This method looks for the strings "login" and "Password" from the # host to determine when to send the username and password. If the diff --git a/lib/observer.rb b/lib/observer.rb index 472a154395..ee3f01b793 100644 --- a/lib/observer.rb +++ b/lib/observer.rb @@ -7,7 +7,7 @@ # # 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. +# when its state changes. # # == Mechanism # @@ -39,14 +39,14 @@ # 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 @@ -67,14 +67,14 @@ # 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 @@ -82,7 +82,7 @@ # end # end # end -# +# # class WarnHigh < Warner # def update(time, price) # callback for observer # if price > @limit diff --git a/lib/optparse.rb b/lib/optparse.rb index 19793f8d4d..ea1eaae52d 100644 --- a/lib/optparse.rb +++ b/lib/optparse.rb @@ -1,15 +1,15 @@ # # optparse.rb - command-line option analysis with the OptionParser class. -# +# # Author:: Nobu Nakada # Documentation:: Nobu Nakada and Gavin Sinclair. # -# See OptionParser for documentation. +# See OptionParser for documentation. # -# == Developer Documentation (not for RDoc output) -# +# == Developer Documentation (not for RDoc output) +# # === Class tree # # - OptionParser:: front end @@ -51,7 +51,7 @@ # 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 @@ -88,12 +88,12 @@ # 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. # # @@ -106,19 +106,19 @@ # 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", @@ -127,28 +127,28 @@ # 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. @@ -157,41 +157,41 @@ # " (#{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 # @@ -276,7 +276,7 @@ class OptionParser # Individual switch class. Not important to the user. # # Defined within Switch are several Switch-derived classes: NoArgument, - # RequiredArgument, etc. + # RequiredArgument, etc. # class Switch attr_reader :pattern, :conv, :short, :long, :arg, :desc, :block @@ -511,13 +511,13 @@ class OptionParser class List # Map from acceptable argument types to pattern and converter pairs. attr_reader :atype - + # Map from short style option switches to actual switch objects. attr_reader :short - + # Map from long style option switches to actual switch objects. attr_reader :long - + # List of all switches and summary string. attr_reader :list @@ -574,7 +574,7 @@ class OptionParser # # Inserts +switch+ at the head of the list, and associates short, long # and negated long options. Arguments are: - # + # # +switch+:: OptionParser::Switch instance to be inserted. # +short_opts+:: List of short style options. # +long_opts+:: List of long style options. @@ -590,7 +590,7 @@ class OptionParser # # Appends +switch+ at the tail of the list, and associates short, long # and negated long options. Arguments are: - # + # # +switch+:: OptionParser::Switch instance to be inserted. # +short_opts+:: List of short style options. # +long_opts+:: List of long style options. @@ -756,7 +756,7 @@ class OptionParser # Initializes a new instance and evaluates the optional block in context # of the instance. Arguments +args+ are passed to #new, see there for # description of parameters. - # + # # This method is *deprecated*, its behavior corresponds to the older #new # method. # @@ -1049,7 +1049,7 @@ class OptionParser # There is also a special form which matches character range (not full # set of regular expression): # "-[a-z]MANDATORY" - # "-[a-z][OPTIONAL]" + # "-[a-z][OPTIONAL]" # "-[a-z]" # # [Argument style and description:] @@ -1061,7 +1061,7 @@ class OptionParser # [Description:] # Description string for the option. # "Run verbosely" - # + # # [Handler:] # Handler for the parsed argument value. Either give a block or pass a # Proc or Method as an argument. diff --git a/lib/ostruct.rb b/lib/ostruct.rb index 0ac6852433..aea0c8e124 100644 --- a/lib/ostruct.rb +++ b/lib/ostruct.rb @@ -12,13 +12,13 @@ # OpenStruct allows you to create data objects and set arbitrary attributes. # For example: # -# require 'ostruct' +# require 'ostruct' # # record = OpenStruct.new # record.name = "John Smith" # record.age = 70 # record.pension = 300 -# +# # puts record.name # -> "John Smith" # puts record.address # -> nil # @@ -41,7 +41,7 @@ class OpenStruct # # p data # -> <OpenStruct country="Australia" population=20000000> # - # By default, the resulting OpenStruct object will have no attributes. + # By default, the resulting OpenStruct object will have no attributes. # def initialize(hash=nil) @table = {} @@ -53,7 +53,7 @@ class OpenStruct end end - # Duplicate an OpenStruct object members. + # Duplicate an OpenStruct object members. def initialize_copy(orig) super @table = @table.dup diff --git a/lib/prime.rb b/lib/prime.rb index ce71d5e00f..ec3f8fa8cb 100644 --- a/lib/prime.rb +++ b/lib/prime.rb @@ -21,9 +21,9 @@ class Integer def Integer.from_prime_division(pd) Prime.int_from_prime_division(pd) end - + # Returns the factorization of +self+. - # + # # See Prime#prime_division for more details. def prime_division(generator = Prime::Generator23.new) Prime.prime_division(self, generator) @@ -34,7 +34,7 @@ class Integer Prime.prime?(self) end - # Iterates the given block over all prime numbers. + # Iterates the given block over all prime numbers. # # See +Prime+#each for more details. def Integer.each_prime(ubound, &block) # :yields: prime @@ -51,11 +51,11 @@ end # end # # == Retrieving the instance -# +Prime+.new is obsolete. Now +Prime+ has the default instance and you can +# +Prime+.new is obsolete. Now +Prime+ has the default instance and you can # access it as +Prime+.instance. # # For convenience, each instance method of +Prime+.instance can be accessed -# as a class method of +Prime+. +# as a class method of +Prime+. # # e.g. # Prime.instance.prime?(2) #=> true @@ -64,19 +64,19 @@ end # == Generators # A "generator" provides an implementation of enumerating pseudo-prime # numbers and it remembers the position of enumeration and upper bound. -# Futhermore, it is a external iterator of prime enumeration which is +# Futhermore, it is a external iterator of prime enumeration which is # compatible to an Enumerator. # # +Prime+::+PseudoPrimeGenerator+ is the base class for generators. # There are few implementations of generator. # # [+Prime+::+EratosthenesGenerator+] -# Uses eratosthenes's sieve. +# Uses eratosthenes's sieve. # [+Prime+::+TrialDivisionGenerator+] # Uses the trial division method. # [+Prime+::+Generator23+] # Generates all positive integers which is not divided by 2 nor 3. -# This sequence is very bad as a pseudo-prime sequence. But this +# This sequence is very bad as a pseudo-prime sequence. But this # is faster and uses much less memory than other generators. So, # it is suitable for factorizing an integer which is not large but # has many prime factors. e.g. for Prime#prime? . @@ -106,23 +106,23 @@ class Prime # # == Parameters # +ubound+:: - # Optional. An arbitrary positive number. + # Optional. An arbitrary positive number. # The upper bound of enumeration. The method enumerates - # prime numbers infinitely if +ubound+ is nil. + # prime numbers infinitely if +ubound+ is nil. # +generator+:: # Optional. An implementation of pseudo-prime generator. # # == Return value # An evaluated value of the given block at the last time. # Or an enumerator which is compatible to an +Enumerator+ - # if no block given. + # if no block given. # # == Description # Calls +block+ once for each prime numer, passing the prime as # a parameter. # # +ubound+:: - # Upper bound of prime numbers. The iterator stops after + # Upper bound of prime numbers. The iterator stops after # yields all prime numbers p <= +ubound+. # # == Note @@ -156,9 +156,9 @@ class Prime # Re-composes a prime factorization and returns the product. # # == Parameters - # +pd+:: Array of pairs of integers. The each internal + # +pd+:: Array of pairs of integers. The each internal # pair consists of a prime number -- a prime factor -- - # and a natural number -- an exponent. + # and a natural number -- an exponent. # # == Example # For [[p_1, e_1], [p_2, e_2], ...., [p_n, e_n]], it returns @@ -176,7 +176,7 @@ class Prime # == Parameters # +value+:: An arbitrary integer. # +generator+:: Optional. A pseudo-prime generator. - # +generator+.succ must return the next + # +generator+.succ must return the next # pseudo-prime number in the ascendent # order. It must generate all prime numbers, # but may generate non prime numbers. @@ -185,7 +185,7 @@ class Prime # +ZeroDivisionError+:: when +value+ is zero. # # == Example - # For an arbitrary integer + # For an arbitrary integer # n = p_1**e_1 * p_2**e_2 * .... * p_n**e_n, # prime_division(n) returns # [[p_1, e_1], [p_2, e_2], ...., [p_n, e_n]]. @@ -231,9 +231,9 @@ class Prime end # returns the next pseudo-prime number, and move the internal - # position forward. + # position forward. # - # +PseudoPrimeGenerator+#succ raises +NotImplementedError+. + # +PseudoPrimeGenerator+#succ raises +NotImplementedError+. def succ raise NotImplementedError, "need to define `succ'" end @@ -278,7 +278,7 @@ class Prime end end end - + # An implementation of +PseudoPrimeGenerator+. # # Uses +EratosthenesSieve+. @@ -286,7 +286,7 @@ class Prime def initialize @last_prime = nil end - + def succ @last_prime = @last_prime ? EratosthenesSieve.instance.next_to(@last_prime) : 2 end @@ -296,13 +296,13 @@ class Prime alias next succ end - # An implementation of +PseudoPrimeGenerator+ which uses + # An implementation of +PseudoPrimeGenerator+ which uses # a prime table generated by trial division. class TrialDivisionGenerator<PseudoPrimeGenerator def initialize @index = -1 end - + def succ TrialDivision.instance[@index += 1] end @@ -315,15 +315,15 @@ class Prime # Generates all integer which are greater than 2 and # are not divided by 2 nor 3. # - # This is a pseudo-prime generator, suitable on - # checking primality of a integer by brute force + # This is a pseudo-prime generator, suitable on + # checking primality of a integer by brute force # method. class Generator23<PseudoPrimeGenerator def initialize @prime = 1 @step = nil end - + def succ loop do if (@step) @@ -358,7 +358,7 @@ class Prime # There must be no primes between @primes[-1] and @next_to_check. @primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101] - # @next_to_check % 6 must be 1. + # @next_to_check % 6 must be 1. @next_to_check = 103 # @primes[-1] - @primes[-1] % 6 + 7 @ulticheck_index = 3 # @primes.index(@primes.reverse.find {|n| # n < Math.sqrt(@@next_to_check) }) @@ -372,7 +372,7 @@ class Prime alias primes cache alias primes_so_far cache - # Returns the +index+th prime number. + # Returns the +index+th prime number. # # +index+ is a 0-based index. def [](index) @@ -390,7 +390,7 @@ class Prime @primes.push @next_to_check if @primes[2..@ulticheck_index].find {|prime| @next_to_check % prime == 0 }.nil? @next_to_check += 4 @primes.push @next_to_check if @primes[2..@ulticheck_index].find {|prime| @next_to_check % prime == 0 }.nil? - @next_to_check += 2 + @next_to_check += 2 end return @primes[index] end diff --git a/lib/pstore.rb b/lib/pstore.rb index fdc518eaec..7b7080338e 100644 --- a/lib/pstore.rb +++ b/lib/pstore.rb @@ -15,49 +15,49 @@ require "thread" # # PStore implements a file based persistence 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 +# 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 updated 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 +# +# 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 @@ -68,9 +68,9 @@ require "thread" # # 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| @@ -102,7 +102,7 @@ class PStore # The error type thrown by all PStore methods. class Error < StandardError end - + # Whether PStore should do its best to prevent file corruptions, even when under # unlikely-to-occur error conditions such as out-of-space conditions and other # unusual OS filesystem errors. Setting this flag comes at the price in the form @@ -112,13 +112,13 @@ class PStore # all POSIX platforms: Linux, MacOS X, FreeBSD, etc). The default value is false. attr_accessor :ultra_safe - # - # To construct a PStore object, pass in the _file_ path where you would like + # + # To construct a PStore object, pass in the _file_ path where you would like # the data to be stored. # # PStore objects are always reentrant. But if _thread_safe_ is set to true, # then it will become thread-safe at the cost of a minor performance hit. - # + # def initialize(file, thread_safe = false) dir = File::dirname(file) unless File::directory? dir @@ -142,10 +142,10 @@ class PStore def in_transaction raise PStore::Error, "not in transaction" unless @transaction end - # + # # Raises PStore::Error if the calling code is not in a PStore#transaction or # if the code is in a read-only PStore#transaction. - # + # def in_transaction_wr() in_transaction() raise PStore::Error, "in read-only transaction" if @rdonly @@ -153,9 +153,9 @@ class PStore private :in_transaction, :in_transaction_wr # - # Retrieves a value from the PStore file data, by _name_. The hierarchy of + # 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. # @@ -164,12 +164,12 @@ class PStore @table[name] end # - # 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 + # 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. # @@ -188,11 +188,11 @@ class PStore # 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... @@ -200,7 +200,7 @@ class PStore # 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. # @@ -210,7 +210,7 @@ class PStore end # # 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. # @@ -221,7 +221,7 @@ class PStore # # 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. # @@ -231,7 +231,7 @@ class PStore end # # 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. # @@ -247,22 +247,22 @@ class PStore # # 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. # @@ -274,21 +274,21 @@ class PStore # # 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. # @@ -300,19 +300,19 @@ class 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 + # 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 + # 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 + # 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. # def transaction(read_only = false, &block) # :yields: pstore @@ -326,11 +326,11 @@ class PStore if file begin @table, checksum, original_data_size = load_data(file, read_only) - + catch(:pstore_abort_transaction) do value = yield(self) end - + if !@abort && !read_only save_data(checksum, original_data_size, file) end @@ -349,19 +349,19 @@ class PStore ensure @transaction = false end - + private # Constant for relieving Ruby's garbage collector. EMPTY_STRING = "" EMPTY_MARSHAL_DATA = Marshal.dump({}) EMPTY_MARSHAL_CHECKSUM = Digest::MD5.digest(EMPTY_MARSHAL_DATA) - + class DummyMutex def synchronize yield end end - + # # Open the specified filename (either in read-only mode or in # read-write mode) and lock it for reading or writing. @@ -391,7 +391,7 @@ class PStore return file end end - + # Load the given PStore file. # If +read_only+ is true, the unmarshalled Hash will be returned. # If +read_only+ is false, a 3-tuple will be returned: the unmarshalled @@ -427,7 +427,7 @@ class PStore [table, checksum, size] end end - + def on_windows? is_windows = RUBY_PLATFORM =~ /mswin/ || RUBY_PLATFORM =~ /mingw/ || @@ -438,7 +438,7 @@ class PStore end is_windows end - + # Check whether Marshal.dump supports the 'canonical' option. This option # makes sure that Marshal.dump always dumps data structures in the same order. # This is important because otherwise, the checksums that we generate may differ. @@ -454,7 +454,7 @@ class PStore end result end - + def save_data(original_checksum, original_file_size, file) # We only want to save the new data if the size or checksum has changed. # This results in less filesystem calls, which is good for performance. @@ -464,7 +464,7 @@ class PStore new_data = dump(@table) end new_checksum = Digest::MD5.digest(new_data) - + if new_data.size != original_file_size || new_checksum != original_checksum if @ultra_safe && !on_windows? # Windows doesn't support atomic file renames. @@ -473,10 +473,10 @@ class PStore save_data_with_fast_strategy(new_data, file) end end - + new_data.replace(EMPTY_STRING) end - + def save_data_with_atomic_file_rename_strategy(data, file) temp_filename = "#{@filename}.tmp.#{Process.pid}.#{rand 1000000}" temp_file = File.new(temp_filename, WR_ACCESS) @@ -492,7 +492,7 @@ class PStore temp_file.close end end - + def save_data_with_fast_strategy(data, file) file.rewind file.truncate(0) diff --git a/lib/racc/parser.rb b/lib/racc/parser.rb index e87a250e56..fc9b390d59 100644 --- a/lib/racc/parser.rb +++ b/lib/racc/parser.rb @@ -388,7 +388,7 @@ module Racc toks.each {|t| out.print ' ', racc_token2str(t) } end out.puts " --> #{racc_token2str(sim)}" - + racc_print_stacks tstack, vstack @racc_debug_out.puts end diff --git a/lib/rake.rb b/lib/rake.rb index d46c49d526..337dc3dacf 100755 --- a/lib/rake.rb +++ b/lib/rake.rb @@ -115,7 +115,7 @@ class String File.join(partial_dirs) end protected :pathmap_partial - + # Preform the pathmap replacement operations on the given path. The # patterns take the form 'pat1,rep1;pat2,rep2...'. def pathmap_replace(patterns, &block) @@ -362,9 +362,9 @@ module Rake def inspect to_s end - + protected - + def lookup(name) if @hash.has_key?(name) @hash[name] @@ -1734,7 +1734,7 @@ module Rake [task_name, arg_names, []] end private :resolve_args_without_dependencies - + # Resolve task arguments for a task or rule when there are # dependencies declared. # @@ -1765,7 +1765,7 @@ module Rake [task_name, arg_names, deps] end private :resolve_args_with_dependencies - + # If a rule can be found that matches the task name, enhance the # task with the prerequisites and actions from the rule. Set the # source attribute of the task appropriately for the rule. Return @@ -2108,7 +2108,7 @@ module Rake 80 end - # Calculate the dynamic width of the + # Calculate the dynamic width of the def dynamic_width @dynamic_width ||= (dynamic_width_stty.nonzero? || dynamic_width_tput) end @@ -2124,7 +2124,7 @@ module Rake def unix? RUBY_PLATFORM =~ /(aix|darwin|linux|(net|free|open)bsd|cygwin|solaris|irix|hpux)/i end - + def windows? Win32.windows? end @@ -2184,7 +2184,7 @@ module Rake ], ['--execute-continue', '-E CODE', "Execute some Ruby code, then continue with normal task processing.", - lambda { |value| eval(value) } + lambda { |value| eval(value) } ], ['--libdir', '-I LIBDIR', "Include LIBDIR in the search path for required modules.", lambda { |value| $:.push(value) } @@ -2196,9 +2196,9 @@ module Rake lambda { |value| verbose(false) } ], ['--rakefile', '-f [FILE]', "Use FILE as the rakefile.", - lambda { |value| + lambda { |value| value ||= '' - @rakefiles.clear + @rakefiles.clear @rakefiles << value } ], @@ -2272,12 +2272,12 @@ module Rake opts.banner = "rake [-f rakefile] {options} targets..." opts.separator "" opts.separator "Options are ..." - + opts.on_tail("-h", "--help", "-H", "Display this help message.") do puts opts exit end - + standard_rake_options.each { |args| opts.on(*args) } parsed_argv = opts.parse(ARGV) @@ -2365,7 +2365,7 @@ module Rake end end end - + # The standard directory containing system wide rake files. if Win32.windows? def standard_system_dir #:nodoc: diff --git a/lib/rake/clean.rb b/lib/rake/clean.rb index 4ee2c5ac95..fd751dceb2 100644 --- a/lib/rake/clean.rb +++ b/lib/rake/clean.rb @@ -16,8 +16,8 @@ require 'rake' CLEAN = Rake::FileList["**/*~", "**/*.bak", "**/core"] -CLEAN.clear_exclude.exclude { |fn| - fn.pathmap("%f") == 'core' && File.directory?(fn) +CLEAN.clear_exclude.exclude { |fn| + fn.pathmap("%f") == 'core' && File.directory?(fn) } desc "Remove any temporary products." diff --git a/lib/rake/gempackagetask.rb b/lib/rake/gempackagetask.rb index 1e4632a26b..00b0157547 100644 --- a/lib/rake/gempackagetask.rb +++ b/lib/rake/gempackagetask.rb @@ -35,10 +35,10 @@ module Rake # s.files = PKG_FILES # s.description = <<EOF # Rake is a Make-like program implemented in Ruby. Tasks - # and dependencies are specified in standard Ruby syntax. + # and dependencies are specified in standard Ruby syntax. # EOF # end - # + # # Rake::GemPackageTask.new(spec) do |pkg| # pkg.need_zip = true # pkg.need_tar = true @@ -84,7 +84,7 @@ module Rake } end end - + def gem_file if @gem_spec.platform == Gem::Platform::RUBY "#{package_name}.gem" @@ -92,6 +92,6 @@ module Rake "#{package_name}-#{@gem_spec.platform}.gem" end end - + end end diff --git a/lib/rake/packagetask.rb b/lib/rake/packagetask.rb index 6158eaf3f6..f05f7cd49e 100644 --- a/lib/rake/packagetask.rb +++ b/lib/rake/packagetask.rb @@ -25,13 +25,13 @@ module Rake # of date. # # [<b>"<em>package_dir</em>/<em>name</em>-<em>version</em>.tgz"</b>] - # Create a gzipped tar package (if <em>need_tar</em> is true). + # Create a gzipped tar package (if <em>need_tar</em> is true). # # [<b>"<em>package_dir</em>/<em>name</em>-<em>version</em>.tar.gz"</b>] - # Create a gzipped tar package (if <em>need_tar_gz</em> is true). + # Create a gzipped tar package (if <em>need_tar_gz</em> is true). # # [<b>"<em>package_dir</em>/<em>name</em>-<em>version</em>.tar.bz2"</b>] - # Create a bzip2'd tar package (if <em>need_tar_bz2</em> is true). + # Create a bzip2'd tar package (if <em>need_tar_bz2</em> is true). # # [<b>"<em>package_dir</em>/<em>name</em>-<em>version</em>.zip"</b>] # Create a zip package archive (if <em>need_zip</em> is true). @@ -74,7 +74,7 @@ module Rake # Zip command for zipped archives. The default is 'zip'. attr_accessor :zip_command - # Create a Package Task with the given name and version. + # Create a Package Task with the given name and version. def initialize(name=nil, version=nil) init(name, version) yield self if block_given? @@ -102,11 +102,11 @@ module Rake desc "Build all the packages" task :package - + desc "Force a rebuild of the package files" task :repackage => [:clobber_package, :package] - - desc "Remove package products" + + desc "Remove package products" task :clobber_package do rm_r package_dir rescue nil end @@ -128,7 +128,7 @@ module Rake end end end - + if need_zip task :package => ["#{package_dir}/#{zip_file}"] file "#{package_dir}/#{zip_file}" => [package_dir_path] + package_files do @@ -160,7 +160,7 @@ module Rake def package_name @version ? "#{@name}-#{@version}" : @name end - + def package_dir_path "#{package_dir}/#{package_name}" end diff --git a/lib/rake/rdoctask.rb b/lib/rake/rdoctask.rb index 6cfbda1d6a..6c751a7cba 100644 --- a/lib/rake/rdoctask.rb +++ b/lib/rake/rdoctask.rb @@ -11,7 +11,7 @@ module Rake # The RDocTask will create the following targets: # # [<b><em>rdoc</em></b>] - # Main task for this RDOC task. + # Main task for this RDOC task. # # [<b>:clobber_<em>rdoc</em></b>] # Delete all the rdoc files. This target is automatically @@ -80,7 +80,7 @@ module Rake yield self if block_given? define end - + # Create the tasks defined by this task lib. def define if name.to_s != "rdoc" @@ -89,17 +89,17 @@ module Rake desc "Build the #{name} HTML Files" task name - + desc "Force a rebuild of the RDOC files" task "re#{name}" => ["clobber_#{name}", name] - - desc "Remove rdoc products" + + desc "Remove rdoc products" task "clobber_#{name}" do rm_r rdoc_dir rescue nil end - + task :clobber => ["clobber_#{name}"] - + directory @rdoc_dir task name => [rdoc_target] file rdoc_target => @rdoc_files + [Rake.application.rakefile] do diff --git a/lib/rake/testtask.rb b/lib/rake/testtask.rb index 79154e422b..f1e4f0b15d 100644 --- a/lib/rake/testtask.rb +++ b/lib/rake/testtask.rb @@ -10,7 +10,7 @@ module Rake # Create a task that runs a set of tests. # # Example: - # + # # Rake::TestTask.new do |t| # t.libs << "test" # t.test_files = FileList['test/test*.rb'] @@ -63,7 +63,7 @@ module Rake # * :rake -- Rake provided test loading script (default). # * :testrb -- Ruby provided test loading script. # * :direct -- Load tests using command line loader. - # + # attr_accessor :loader # Array of commandline options to pass to ruby when running test loader. diff --git a/lib/rbconfig/datadir.rb b/lib/rbconfig/datadir.rb index 5b8f07754a..040adc09a9 100644 --- a/lib/rbconfig/datadir.rb +++ b/lib/rbconfig/datadir.rb @@ -10,7 +10,7 @@ module Config # Only define datadir if it doesn't already exist. unless Config.respond_to?(:datadir) - + # Return the path to the data directory associated with the given # package name. Normally this is just # "#{Config::CONFIG['datadir']}/#{package_name}", but may be diff --git a/lib/rdoc.rb b/lib/rdoc.rb index f4fc3867cf..043d3420be 100644 --- a/lib/rdoc.rb +++ b/lib/rdoc.rb @@ -69,7 +69,7 @@ $DEBUG_RDOC = nil # always will override those in +RDOCOPT+. # # Run -# +# # % rdoc --help # # for full details on rdoc's options. @@ -96,7 +96,7 @@ $DEBUG_RDOC = nil # # =begin rdoc # Documentation to be processed by RDoc. -# +# # ... # =end # @@ -112,7 +112,7 @@ $DEBUG_RDOC = nil # # FIXME: fails if the birthday falls on February 29th # #++ # # The DOB is returned as a Time object. -# +# # def get_dob(person) # # ... # end @@ -138,7 +138,7 @@ $DEBUG_RDOC = nil # # def fred # :yields: index, position # # ... -# +# # yield line, address # # which will get documented as @@ -251,12 +251,12 @@ $DEBUG_RDOC = nil # module also will 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 MyModule # :nodoc: # class Input # end # end -# +# # module OtherModule # :nodoc: all # class Output # end @@ -290,7 +290,7 @@ $DEBUG_RDOC = nil # comment block may have one or more lines before the :section: directive. # These will be removed, and any identical lines at the end of the block are # also removed. This allows you to add visual cues such as: -# +# # # ---------------------------------------- # # :section: My Section # # This is the section that I wrote. diff --git a/lib/rdoc/code_objects.rb b/lib/rdoc/code_objects.rb index 0916b03398..3fdd86314d 100644 --- a/lib/rdoc/code_objects.rb +++ b/lib/rdoc/code_objects.rb @@ -340,7 +340,7 @@ module RDoc meth.add_alias(new_meth) add_method(new_meth) end - + def add_alias(an_alias) meth = find_instance_method_named(an_alias.old_name) @@ -453,7 +453,7 @@ module RDoc @method_list.each {|m| yield m} end - def each_attribute + def each_attribute @attributes.each {|a| yield a} end @@ -658,7 +658,7 @@ module RDoc def self.find_class_named(name) @@all_classes.each_value do |c| - res = c.find_class_named(name) + res = c.find_class_named(name) return res if res end nil @@ -767,7 +767,7 @@ module RDoc raise NoMethodError, "#{full_name} is a module" if module? if @superclass.nil? or @superclass == 'Object' then - @superclass = superclass + @superclass = superclass end end diff --git a/lib/rdoc/diagram.rb b/lib/rdoc/diagram.rb index 4aa2ec5656..d308d36dee 100644 --- a/lib/rdoc/diagram.rb +++ b/lib/rdoc/diagram.rb @@ -313,7 +313,7 @@ module RDoc def wrap_in_image_map(src, dot) res = "" dot_map = `dot -Tismap #{src}` - + if(!dot_map.empty?) res << %{<map id="map" name="map">\n} dot_map.split($/).each do |area| diff --git a/lib/rdoc/generator.rb b/lib/rdoc/generator.rb index d695e661d1..86196b4cf6 100644 --- a/lib/rdoc/generator.rb +++ b/lib/rdoc/generator.rb @@ -137,7 +137,7 @@ module RDoc::Generator end RDoc::TopLevel.all_classes_and_modules.each do |cls| - build_class_list(classes, options, cls, files[0], + build_class_list(classes, options, cls, files[0], RDoc::Generator::CLASS_DIR) end diff --git a/lib/rdoc/generator/chm/chm.rb b/lib/rdoc/generator/chm/chm.rb index cceeca5dfc..c362318d91 100644 --- a/lib/rdoc/generator/chm/chm.rb +++ b/lib/rdoc/generator/chm/chm.rb @@ -6,7 +6,7 @@ module RDoc::Generator::CHM::CHM HTML = RDoc::Generator::HTML::HTML INDEX = HTML::INDEX - + STYLE = HTML::STYLE CLASS_INDEX = HTML::CLASS_INDEX diff --git a/lib/rdoc/generator/html.rb b/lib/rdoc/generator/html.rb index d136de7b00..60e0c175fe 100644 --- a/lib/rdoc/generator/html.rb +++ b/lib/rdoc/generator/html.rb @@ -305,9 +305,9 @@ class RDoc::Generator::HTML open 'index.html', 'w' do |f| style_url = style_url '', @options.css - + classes = @classes.sort.map { |klass| klass.value_hash } - + values = { 'initial_page' => @main_url, 'style_url' => style_url('', @options.css), @@ -315,7 +315,7 @@ class RDoc::Generator::HTML 'charset' => @options.charset, 'classes' => classes, } - + values['inline_source'] = @options.inline_source main.write_html_on f, values diff --git a/lib/rdoc/generator/html/hefss.rb b/lib/rdoc/generator/html/hefss.rb index 540c23d869..01425a4556 100644 --- a/lib/rdoc/generator/html/hefss.rb +++ b/lib/rdoc/generator/html/hefss.rb @@ -125,9 +125,9 @@ EOF STYLE = FACTORY.get_STYLE() METHOD_LIST = FACTORY.get_METHOD_LIST() - + BODY = FACTORY.get_BODY() - + FILE_PAGE = FACTORY.get_FILE_PAGE() CLASS_PAGE = FACTORY.get_CLASS_PAGE() diff --git a/lib/rdoc/generator/html/html.rb b/lib/rdoc/generator/html/html.rb index 823d8056e7..5e5b4d5531 100644 --- a/lib/rdoc/generator/html/html.rb +++ b/lib/rdoc/generator/html/html.rb @@ -11,7 +11,7 @@ require 'rdoc/generator/html/common' # '[source]' link. # # This template *also* forms the basis of the frameless template. -# +# # == Authors # # * Michael Granger <[email protected]> diff --git a/lib/rdoc/generator/html/kilmer.rb b/lib/rdoc/generator/html/kilmer.rb index 4c5a9ee8b0..233a9259a2 100644 --- a/lib/rdoc/generator/html/kilmer.rb +++ b/lib/rdoc/generator/html/kilmer.rb @@ -126,9 +126,9 @@ EOF STYLE = FACTORY.get_STYLE() METHOD_LIST = FACTORY.get_METHOD_LIST() - + BODY = FACTORY.get_BODY() - + FILE_PAGE = FACTORY.get_FILE_PAGE() CLASS_PAGE = FACTORY.get_CLASS_PAGE() diff --git a/lib/rdoc/generator/html/kilmerfactory.rb b/lib/rdoc/generator/html/kilmerfactory.rb index ef6f3f3b4d..1407840839 100644 --- a/lib/rdoc/generator/html/kilmerfactory.rb +++ b/lib/rdoc/generator/html/kilmerfactory.rb @@ -61,8 +61,8 @@ class RDoc::Generator::HTML::KilmerFactory # If not supplied, this defaults to "Attributes". # attr_reader :attribute_list_heading - - # + + # # ====Description: # This method constructs a KilmerFactory instance, which # can be used to build Kilmer-style template classes. @@ -72,7 +72,7 @@ class RDoc::Generator::HTML::KilmerFactory # ====Parameters: # [style_attributes] # A Hash describing the appearance of the Kilmer-style. - # + # def initialize(style_attributes) @central_css = style_attributes[:central_css] if(!@central_css) @@ -103,7 +103,7 @@ class RDoc::Generator::HTML::KilmerFactory def get_STYLE return @central_css end - + def get_METHOD_LIST return %{ <% if values["diagram"] then %> diff --git a/lib/rdoc/generator/html/one_page_html.rb b/lib/rdoc/generator/html/one_page_html.rb index 51ae32351a..5bae2f34f7 100644 --- a/lib/rdoc/generator/html/one_page_html.rb +++ b/lib/rdoc/generator/html/one_page_html.rb @@ -54,7 +54,7 @@ module RDoc::Generator::HTML::ONE_PAGE_HTML <% sections["method_list"].each do |method_list| %> <% if method_list["methods"] then %> <% method_list["methods"].each do |methods| %> -<h4><%= methods["type"] %> <%= methods["category"] %> method: +<h4><%= methods["type"] %> <%= methods["category"] %> method: <% if methods["callseq"] then %> <a name="<%= methods["aref"] %>"><%= methods["callseq"] %></a> <% end %> diff --git a/lib/rdoc/generator/texinfo.rb b/lib/rdoc/generator/texinfo.rb index 70db875af9..99a1452f21 100644 --- a/lib/rdoc/generator/texinfo.rb +++ b/lib/rdoc/generator/texinfo.rb @@ -51,7 +51,7 @@ module RDoc def initialize(values, file = 'texinfo.erb') @v, @file = [values, file] end - + def template ::File.read(::File.join(BASE_DIR, 'texinfo', @file)) end diff --git a/lib/rdoc/markup.rb b/lib/rdoc/markup.rb index 9d22b38946..a584a79b75 100644 --- a/lib/rdoc/markup.rb +++ b/lib/rdoc/markup.rb @@ -27,9 +27,9 @@ require 'rdoc' # convert multiple input strings. # # require 'rdoc/markup/to_html' -# +# # h = RDoc::Markup::ToHtml.new -# +# # puts h.convert(input_string) # # You can extend the RDoc::Markup parser to recognise new markup @@ -41,22 +41,22 @@ require 'rdoc' # # require 'rdoc/markup' # require 'rdoc/markup/to_html' -# +# # class WikiHtml < RDoc::Markup::ToHtml # def handle_special_WIKIWORD(special) # "<font color=red>" + special.text + "</font>" # end # end -# +# # m = RDoc::Markup.new # m.add_word_pair("{", "}", :STRIKE) # m.add_html("no", :STRIKE) -# +# # m.add_special(/\b([A-Z][a-z]+[A-Z]\w+)/, :WIKIWORD) -# +# # wh = WikiHtml.new # wh.add_tag(:STRIKE, "<strike>", "</strike>") -# +# # puts "<body>#{wh.convert ARGF.read}</body>" # #-- diff --git a/lib/rdoc/markup/fragments.rb b/lib/rdoc/markup/fragments.rb index b7f9b605c8..0031b809b4 100644 --- a/lib/rdoc/markup/fragments.rb +++ b/lib/rdoc/markup/fragments.rb @@ -203,7 +203,7 @@ class RDoc::Markup # normal paragraph text. # # this is code - # + # # and more code # # You'll end up with the fragments Paragraph, BlankLine, Verbatim, diff --git a/lib/rdoc/markup/to_html.rb b/lib/rdoc/markup/to_html.rb index dce7a69b12..0165042d84 100644 --- a/lib/rdoc/markup/to_html.rb +++ b/lib/rdoc/markup/to_html.rb @@ -309,7 +309,7 @@ class RDoc::Markup::ToHtml < RDoc::Markup::Formatter # convert -- to em-dash, (-- to en-dash) gsub(/---?/, '—'). #gsub(/--/, '–'). - + # convert ... to elipsis (and make sure .... becomes .<elipsis>) gsub(/\.\.\.\./, '.…').gsub(/\.\.\./, '…'). diff --git a/lib/rdoc/markup/to_html_crossref.rb b/lib/rdoc/markup/to_html_crossref.rb index dc64b30da1..e73fbf5c8f 100644 --- a/lib/rdoc/markup/to_html_crossref.rb +++ b/lib/rdoc/markup/to_html_crossref.rb @@ -10,7 +10,7 @@ class RDoc::Markup::ToHtmlCrossref < RDoc::Markup::ToHtml attr_accessor :context # Regular expressions to match class and method references. - # + # # 1.) There can be a '\' in front of text to suppress # any cross-references (note, however, that the single '\' # is written as '\\\\' in order to escape it twice, once diff --git a/lib/rdoc/options.rb b/lib/rdoc/options.rb index 1d92bd4748..2b069f4265 100644 --- a/lib/rdoc/options.rb +++ b/lib/rdoc/options.rb @@ -65,7 +65,7 @@ class RDoc::Options # Formatter to mark up text with attr_accessor :formatter - + ## # image format for diagrams diff --git a/lib/rdoc/parser.rb b/lib/rdoc/parser.rb index 6b1233c62d..275d3cc8f9 100644 --- a/lib/rdoc/parser.rb +++ b/lib/rdoc/parser.rb @@ -22,14 +22,14 @@ require 'rdoc/stats' # following incantation # # require "rdoc/parser" -# +# # class RDoc::Parser::Xyz < RDoc::Parser # parse_files_matching /\.xyz$/ # <<<< -# +# # def initialize(file_name, body, options) # ... # end -# +# # def scan # ... # end diff --git a/lib/rdoc/parser/c.rb b/lib/rdoc/parser/c.rb index 933838debd..c3fb5e5b19 100644 --- a/lib/rdoc/parser/c.rb +++ b/lib/rdoc/parser/c.rb @@ -79,7 +79,7 @@ require 'rdoc/known_classes' # * Encapsulate the writing and reading of the configuration # * file. ... # */ -# +# # /* # * Document-method: read_value # * @@ -124,7 +124,7 @@ class RDoc::Parser::C < RDoc::Parser end def do_classes - @content.scan(/(\w+)\s* = \s*rb_define_module\s*\(\s*"(\w+)"\s*\)/mx) do + @content.scan(/(\w+)\s* = \s*rb_define_module\s*\(\s*"(\w+)"\s*\)/mx) do |var_name, class_name| handle_class_module(var_name, "module", class_name, nil, nil) end diff --git a/lib/rdoc/parser/f95.rb b/lib/rdoc/parser/f95.rb index fd372b098b..0959db4936 100644 --- a/lib/rdoc/parser/f95.rb +++ b/lib/rdoc/parser/f95.rb @@ -79,17 +79,17 @@ require 'rdoc/parser' # ! # ! Comment blocks for the modules (or the programs). # ! -# +# # private -# +# # logical :: a ! a private variable # real, public :: b ! a public variable # integer, parameter :: c = 0 ! a public constant -# +# # public :: c # public :: MULTI_ARRAY # public :: hoge, foo -# +# # type MULTI_ARRAY # ! # ! Comment blocks for the derived-types. @@ -97,9 +97,9 @@ require 'rdoc/parser' # real, pointer :: var(:) =>null() ! Comments block for the variables. # integer :: num = 0 # end type MULTI_ARRAY -# +# # contains -# +# # subroutine hoge( in, & ! Comment blocks between continuation lines are ignored. # & out ) # ! @@ -109,32 +109,32 @@ require 'rdoc/parser' # character(*),intent(out),allocatable,target :: in # ! Comment blocks can be # ! written under Fortran statements. -# +# # character(32) :: file ! This comment parsed as a variable in below NAMELIST. # integer :: id -# +# # namelist /varinfo_nml/ file, id # ! # ! Comment blocks for the NAMELISTs. # ! Information about variables are described above. # ! -# +# # .... -# +# # end subroutine hoge -# +# # integer function foo( in ) # ! # ! This part is considered as comment block. -# +# # ! Comment blocks under blank lines are ignored. # ! # integer, intent(in):: inA ! This part is considered as comment block. -# +# # ! This part is ignored. -# +# # end function foo -# +# # subroutine hide( in, & # & out ) !:nodoc: # ! @@ -145,11 +145,11 @@ require 'rdoc/parser' # ! defined operators, defined assignments, # ! list of imported modules ("use" statement). # ! -# +# # .... -# +# # end subroutine hide -# +# # end module hogehoge class RDoc::Parser::F95 < RDoc::Parser @@ -295,7 +295,7 @@ class RDoc::Parser::F95 < RDoc::Parser @stats.add_module f9x_module - f9x_comment = COMMENTS_ARE_UPPER ? + f9x_comment = COMMENTS_ARE_UPPER ? find_comments(pre_comment.join("\n")) + "\n" + module_trailing : module_trailing + "\n" + find_comments(module_code.sub(/^.*$\n/i, '')) f9x_module.comment = f9x_comment @@ -320,8 +320,8 @@ class RDoc::Parser::F95 < RDoc::Parser program_code = module_program_code program_trailing = module_program_trailing # progress "p" # HACK what stats thingy does this correspond to? - program_comment = COMMENTS_ARE_UPPER ? - find_comments(pre_comment.join("\n")) + "\n" + program_trailing : + program_comment = COMMENTS_ARE_UPPER ? + find_comments(pre_comment.join("\n")) + "\n" + program_trailing : program_trailing + "\n" + find_comments(program_code.sub(/^.*$\n/i, '')) program_comment = "\n\n= <i>Program</i> <tt>#{program_name}</tt>\n\n" \ + program_comment @@ -410,12 +410,12 @@ class RDoc::Parser::F95 < RDoc::Parser # This information is used when "add_method" and # "set_visibility_for" are called. # - visibility_default, visibility_info = + visibility_default, visibility_info = parse_visibility(remaining_lines.join("\n"), visibility, container) @@public_methods.concat visibility_info if visibility_default == :public if !cascaded_modules_list.empty? - cascaded_modules = + cascaded_modules = Attr.new("Cascaded Modules", "Imported modules all of whose components are published again", "", @@ -499,7 +499,7 @@ class RDoc::Parser::F95 < RDoc::Parser type_trailing = find_comments($4) next if type_trailing =~ /^:nodoc:/ type_visibility = $1 - type_comment = COMMENTS_ARE_UPPER ? + type_comment = COMMENTS_ARE_UPPER ? find_comments($~.pre_match) + "\n" + type_trailing : type_trailing + "\n" + find_comments(type_code.sub(/^.*$\n/i, '')) type_element_visibility_public = true @@ -567,8 +567,8 @@ class RDoc::Parser::F95 < RDoc::Parser end if !derived_types_comment.empty? - derived_types_table = - Attr.new("Derived Types", "Derived_Types", "", + derived_types_table = + Attr.new("Derived Types", "Derived_Types", "", derived_types_comment) container.add_attribute(derived_types_table) end @@ -733,8 +733,8 @@ class RDoc::Parser::F95 < RDoc::Parser subroutine_trailing = procedure_trailing subroutine_code = procedure_code - subroutine_comment = COMMENTS_ARE_UPPER ? - pre_comment.join("\n") + "\n" + subroutine_trailing : + subroutine_comment = COMMENTS_ARE_UPPER ? + pre_comment.join("\n") + "\n" + subroutine_trailing : subroutine_trailing + "\n" + subroutine_code.sub(/^.*$\n/i, '') subroutine = AnyMethod.new("subroutine", subroutine_name) parse_subprogram(subroutine, subroutine_params, @@ -787,7 +787,7 @@ class RDoc::Parser::F95 < RDoc::Parser # The visibility of procedure is specified # - set_visibility(container, procedure_name, + set_visibility(container, procedure_name, visibility_default, @@public_methods) # The alias for this procedure from external modules @@ -871,11 +871,11 @@ class RDoc::Parser::F95 < RDoc::Parser next if !old_meth nolink = old_meth.visibility == :private ? true : nil nolink = nil if @options.show_all - new_meth = - initialize_external_method(generic_name, proc, - old_meth.params, nil, - old_meth.comment, - old_meth.clone.token_stream[0].text, + new_meth = + initialize_external_method(generic_name, proc, + old_meth.params, nil, + old_meth.comment, + old_meth.clone.token_stream[0].text, true, nolink) new_meth.singleton = old_meth.singleton @@ -937,10 +937,10 @@ class RDoc::Parser::F95 < RDoc::Parser end if indicated_method - external_method = - initialize_external_method(generic_name, proc, - indicated_method.params, - indicated_file, + external_method = + initialize_external_method(generic_name, proc, + indicated_method.params, + indicated_file, indicated_method.comment) @stats.add_method external_method @@ -1004,12 +1004,12 @@ class RDoc::Parser::F95 < RDoc::Parser # Parse arguments, comment, code of subroutine and function. Return # AnyMethod object. - def parse_subprogram(subprogram, params, comment, code, + def parse_subprogram(subprogram, params, comment, code, before_contains=nil, function=nil, prefix=nil) subprogram.singleton = false prefix = "" if !prefix arguments = params.sub(/\(/, "").sub(/\)/, "").split(",") if params - args_comment, params_opt = + args_comment, params_opt = find_arguments(arguments, code.sub(/^s*?contains\s*?(!.*?)?$.*/im, ""), nil, nil, true) params_opt = "( " + params_opt + " ) " if params_opt @@ -1086,7 +1086,7 @@ class RDoc::Parser::F95 < RDoc::Parser if arg == defitem.varname.strip.chomp || all args_rdocforms << <<-"EOF" -#{indent}<tt><b>#{defitem.varname.chomp.strip}#{defitem.arraysuffix}</b> #{defitem.inivalue}</tt> :: +#{indent}<tt><b>#{defitem.varname.chomp.strip}#{defitem.arraysuffix}</b> #{defitem.inivalue}</tt> :: #{indent} <tt>#{defitem.types.chomp.strip}</tt> EOF if !defitem.comment.chomp.strip.empty? @@ -1096,7 +1096,7 @@ EOF } args_rdocforms << <<-"EOF" -#{indent} <tt></tt> :: +#{indent} <tt></tt> :: #{indent} <tt></tt> #{indent} #{comment.chomp.strip} EOF @@ -1130,7 +1130,7 @@ EOF before_contains = "" if !before_contains while lines =~ /^\s*?namelist\s+\/\s*?(\w+)\s*?\/([\s\w\,]+)$/i lines = $~.post_match - nml_comment = COMMENTS_ARE_UPPER ? + nml_comment = COMMENTS_ARE_UPPER ? find_comments($~.pre_match) : find_comments($~.post_match) nml_name = $1 nml_args = $2.split(",") @@ -1193,7 +1193,7 @@ EOF if internal external_alias_header = "#{INTERNAL_ALIAS_MES} " - external_alias_text = external_alias_header + old + external_alias_text = external_alias_header + old elsif file external_alias_header = "#{EXTERNAL_ALIAS_MES} " external_alias_text = external_alias_header + file + "#" + old @@ -1325,8 +1325,8 @@ EOF subname.upcase == alias_item["old_name"].upcase && @options.ignore_case - new_meth = initialize_external_method(alias_item["new_name"], - subname, params, @file_name, + new_meth = initialize_external_method(alias_item["new_name"], + subname, params, @file_name, comment) new_meth.visibility = alias_item["visibility"] @@ -1402,7 +1402,7 @@ EOF brank_flag = false now_continuing = false next "" - else + else brank_flag = false now_continuing = false ignore = false @@ -1595,7 +1595,7 @@ EOF comment_block = Array.new checked = false lines.each do |line| - if !checked + if !checked if /^\s?#{INTERNAL_ALIAS_MES}/ =~ line || /^\s?#{EXTERNAL_ALIAS_MES}/ =~ line checked = true @@ -1676,9 +1676,9 @@ EOF def to_s return <<-EOF -<Fortran95Definition: +<Fortran95Definition: varname=#{@varname}, types=#{types}, -inivalue=#{@inivalue}, arraysuffix=#{@arraysuffix}, nodoc=#{@nodoc}, +inivalue=#{@inivalue}, arraysuffix=#{@arraysuffix}, nodoc=#{@nodoc}, comment= #{@comment} > diff --git a/lib/rdoc/parser/perl.rb b/lib/rdoc/parser/perl.rb index 43d1e9ff69..0023a013a6 100644 --- a/lib/rdoc/parser/perl.rb +++ b/lib/rdoc/parser/perl.rb @@ -15,7 +15,7 @@ require 'rdoc/parser' # # We would like to support all the markup the POD provides # so that it will convert happily to HTML. At the moment -# I don't think I can do that: time constraints. +# I don't think I can do that: time constraints. # class RDoc::Parser::PerlPOD < RDoc::Parser @@ -45,39 +45,39 @@ class RDoc::Parser::PerlPOD < RDoc::Parser # but I think it would obscure the intent, scatter the # code all over tha place. This machine is necessary # because POD requires that directives be preceded by - # blank lines, so reading line by line is necessary, + # blank lines, so reading line by line is necessary, # and preserving state about what is seen is necesary. def scan @top_level.comment ||= "" - state=:code_blank + state=:code_blank line_number = 0 line = nil # This started out as a really long nested case statement, # which also led to repetitive code. I'd like to avoid that # so I'm using a "table" instead. - + # Firstly we need some procs to do the transition and processing # work. Because these are procs they are closures, and they can # use variables in the local scope. # # First, the "nothing to see here" stuff. - code_noop = lambda do + code_noop = lambda do if line =~ /^\s+$/ state = :code_blank end end - pod_noop = lambda do + pod_noop = lambda do if line =~ /^\s+$/ state = :pod_blank end @top_level.comment += filter(line) end - begin_noop = lambda do + begin_noop = lambda do if line =~ /^\s+$/ state = :begin_blank end @@ -151,7 +151,7 @@ class RDoc::Parser::PerlPOD < RDoc::Parser def filter(comment) return '' if comment =~ /^=pod\s*$/ comment.gsub!(/^=pod/, '==') - comment.gsub!(/^=head(\d+)/) do + comment.gsub!(/^=head(\d+)/) do "=" * $1.to_i end comment.gsub!(/=item/, ''); diff --git a/lib/rdoc/parser/ruby.rb b/lib/rdoc/parser/ruby.rb index 865cb79d39..cf6c1ad221 100644 --- a/lib/rdoc/parser/ruby.rb +++ b/lib/rdoc/parser/ruby.rb @@ -1373,7 +1373,7 @@ end # # ## # # This method tries over and over until it is tired -# +# # def go_go_go(thing_to_try, tries = 10) # :args: thing_to_try # puts thing_to_try # go_go_go thing_to_try, tries - 1 @@ -1393,7 +1393,7 @@ end # # :call-seq: # # my_method(Range) # # my_method(offset, length) -# +# # def my_method(*args) # end # @@ -1404,7 +1404,7 @@ end # # ## # # My method is awesome -# +# # def my_method(&block) # :yields: happy, times # block.call 1, 2 # end @@ -1416,7 +1416,7 @@ end # # ## # # This is a meta-programmed method! -# +# # add_my_method :meta_method, :arg1, :arg2 # # The parser looks at the token after the identifier to determine the name, in @@ -1447,10 +1447,10 @@ end # ## # # :method: ghost_method # # There is a method here, but you can't see it! -# +# # ## # # this is a comment for a regular method -# +# # def regular_method() end # # Note that by default, the :method: directive will be ignored if there is a diff --git a/lib/rdoc/ri/display.rb b/lib/rdoc/ri/display.rb index 7b0158c18a..f6b647fbc1 100644 --- a/lib/rdoc/ri/display.rb +++ b/lib/rdoc/ri/display.rb @@ -119,35 +119,35 @@ class RDoc::RI::DefaultDisplay return display_class_method_list(klass) end end - + ## # Given a Hash mapping a class' methods to method types (returned by # display_class_method_list), this method allows the user to # choose one of the methods. - + def get_class_method_choice(method_map) if CAN_USE_READLINE # prepare abbreviations for tab completion abbreviations = method_map.keys.abbrev - Readline.completion_proc = proc do |string| + Readline.completion_proc = proc do |string| abbreviations.values.uniq.grep(/^#{string}/) end end - + @formatter.raw_print_line "\nEnter the method name you want.\n" @formatter.raw_print_line "Class methods can be preceeded by '::' and instance methods by '#'.\n" if CAN_USE_READLINE @formatter.raw_print_line "You can use tab to autocomplete.\n" @formatter.raw_print_line "Enter a blank line to exit.\n" - + choice_string = Readline.readline(">> ").strip else @formatter.raw_print_line "Enter a blank line to exit.\n" @formatter.raw_print_line ">> " choice_string = $stdin.gets.strip end - + if choice_string == '' return nil else @@ -172,7 +172,7 @@ class RDoc::RI::DefaultDisplay end end end - + ## # Display methods on +klass+ @@ -187,16 +187,16 @@ class RDoc::RI::DefaultDisplay :instance_methods, :instance_method_extensions, ] - + class_data.each do |data_type| data = klass.send data_type - + unless data.nil? or data.empty? then @formatter.blankline - + heading = data_type.to_s.split('_').join(' ').capitalize << ':' @formatter.display_heading heading, 2, '' - + method_names = [] data.each do |item| method_names << item.name @@ -268,7 +268,7 @@ class RDoc::RI::DefaultDisplay end end end - + ## # Display a list of +methods+ and allow the user to select one of them. @@ -280,9 +280,9 @@ class RDoc::RI::DefaultDisplay methods.each_with_index do |method, index| @formatter.raw_print_line "%3d %s [%s]\n" % [index + 1, method.full_name, method.source_path] end - + @formatter.raw_print_line ">> " - + choice = $stdin.gets.strip! if(choice == '') @@ -294,7 +294,7 @@ class RDoc::RI::DefaultDisplay if ((choice == 0) || (choice > methods.size)) then @formatter.raw_print_line "Invalid choice!\n" else - method = methods[choice - 1] + method = methods[choice - 1] display_method_info(method) end end diff --git a/lib/rdoc/ri/driver.rb b/lib/rdoc/ri/driver.rb index 0c91232b70..89534a5972 100644 --- a/lib/rdoc/ri/driver.rb +++ b/lib/rdoc/ri/driver.rb @@ -527,7 +527,7 @@ Options may also be set in the 'RI' environment variable. ancestors = [orig_klass] ancestors.push(*cache.includes.map { |inc| inc['name'] }) ancestors << cache.superclass - + ancestor_index = ancestors.index(klass) if ancestor_index diff --git a/lib/rdoc/ri/formatter.rb b/lib/rdoc/ri/formatter.rb index 933882abc4..258907d141 100644 --- a/lib/rdoc/ri/formatter.rb +++ b/lib/rdoc/ri/formatter.rb @@ -114,7 +114,7 @@ class RDoc::RI::Formatter txt = txt.gsub(%r{<tt>(.*?)</tt>}, '+\1+') txt.gsub!(%r{<code>(.*?)</code>}, '+\1+') txt.gsub!(%r{<b>(.*?)</b>}, '*\1*') - txt.gsub!(%r{<em>(.*?)</em>}, '_\1_') + txt.gsub!(%r{<em>(.*?)</em>}, '_\1_') txt end diff --git a/lib/rdoc/ri/util.rb b/lib/rdoc/ri/util.rb index 4e91eb978d..51cf881bdd 100644 --- a/lib/rdoc/ri/util.rb +++ b/lib/rdoc/ri/util.rb @@ -60,7 +60,7 @@ class RDoc::RI::NameDescriptor end if @method_name =~ /::|\.|#/ or !tokens.empty? - raise RDoc::RI::Error.new("Bad argument: #{arg}") + raise RDoc::RI::Error.new("Bad argument: #{arg}") end if separator && separator != '.' @is_class_method = separator == "::" diff --git a/lib/rexml/attlistdecl.rb b/lib/rexml/attlistdecl.rb index ea5a98b69e..ec4e6c3b8d 100644 --- a/lib/rexml/attlistdecl.rb +++ b/lib/rexml/attlistdecl.rb @@ -31,7 +31,7 @@ module REXML @element_name, @pairs, @contents = *source end end - + # Access the attlist attribute/value pairs. # value = attlist_decl[ attribute_name ] def [](key) diff --git a/lib/rexml/attribute.rb b/lib/rexml/attribute.rb index febcc288b1..28a5923608 100644 --- a/lib/rexml/attribute.rb +++ b/lib/rexml/attribute.rb @@ -14,7 +14,7 @@ module REXML attr_reader :element # The normalized value of this attribute. That is, the attribute with # entities intact. - attr_writer :normalized + attr_writer :normalized PATTERN = /\s*(#{NAME_STR})\s*=\s*(["'])(.*?)\2/um NEEDS_A_SECOND_CHECK = /(<|&((#{Entity::NAME});|(#0*((?:\d+)|(?:x[a-fA-F0-9]+)));)?)/um @@ -22,18 +22,18 @@ module REXML # Constructor. # FIXME: The parser doesn't catch illegal characters in attributes # - # first:: + # first:: # Either: an Attribute, which this new attribute will become a # clone of; or a String, which is the name of this attribute # second:: # If +first+ is an Attribute, then this may be an Element, or nil. # If nil, then the Element parent of this attribute is the parent - # of the +first+ Attribute. If the first argument is a String, - # then this must also be a String, and is the content of the attribute. + # of the +first+ Attribute. If the first argument is a String, + # then this must also be a String, and is the content of the attribute. # If this is the content, it must be fully normalized (contain no # illegal characters). # parent:: - # Ignored unless +first+ is a String; otherwise, may be the Element + # Ignored unless +first+ is a String; otherwise, may be the Element # parent of this attribute, or nil. # # @@ -61,7 +61,7 @@ module REXML end # Returns the namespace of the attribute. - # + # # e = Element.new( "elns:myelement" ) # e.add_attribute( "nsa:a", "aval" ) # e.add_attribute( "b", "bval" ) @@ -78,7 +78,7 @@ module REXML end # 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" @@ -157,7 +157,7 @@ module REXML end # Removes this Attribute from the tree, and returns true if successfull - # + # # This method is usually not called directly. def remove @element.attributes.delete self.name unless @element.nil? diff --git a/lib/rexml/cdata.rb b/lib/rexml/cdata.rb index 123a7c3d82..e1235d60f8 100644 --- a/lib/rexml/cdata.rb +++ b/lib/rexml/cdata.rb @@ -17,7 +17,7 @@ module REXML end # Make a copy of this object - # + # # _Examples_ # c = CData.new( "Some text" ) # d = c.clone diff --git a/lib/rexml/child.rb b/lib/rexml/child.rb index 033057da55..fd59d7283a 100644 --- a/lib/rexml/child.rb +++ b/lib/rexml/child.rb @@ -15,8 +15,8 @@ module REXML # if supplied, the parent of this child will be set to the # supplied value, and self will be added to the parent def initialize( parent = nil ) - @parent = nil - # Declare @parent, but don't define it. The next line sets the + @parent = nil + # Declare @parent, but don't define it. The next line sets the # parent. parent.add( self ) if parent end @@ -68,7 +68,7 @@ module REXML parent.insert_after self, other end - # Sets the previous sibling of this child. This can be used to insert a + # 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") diff --git a/lib/rexml/comment.rb b/lib/rexml/comment.rb index d5be89b652..e401090376 100644 --- a/lib/rexml/comment.rb +++ b/lib/rexml/comment.rb @@ -14,11 +14,11 @@ module REXML ## # Constructor. The first argument can be one of three types: - # @param first If String, the contents of this comment are set to the + # @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 + # @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 def initialize( first, second = nil ) #puts "IN COMMENT CONSTRUCTOR; SECOND IS #{second.type}" diff --git a/lib/rexml/doctype.rb b/lib/rexml/doctype.rb index 35beabc566..1a946a1587 100644 --- a/lib/rexml/doctype.rb +++ b/lib/rexml/doctype.rb @@ -15,11 +15,11 @@ module REXML STOP = ">" SYSTEM = "SYSTEM" PUBLIC = "PUBLIC" - DEFAULT_ENTITIES = { - 'gt'=>EntityConst::GT, - 'lt'=>EntityConst::LT, - 'quot'=>EntityConst::QUOT, - "apos"=>EntityConst::APOS + DEFAULT_ENTITIES = { + 'gt'=>EntityConst::GT, + 'lt'=>EntityConst::LT, + 'quot'=>EntityConst::QUOT, + "apos"=>EntityConst::APOS } # name is the name of the doctype @@ -33,7 +33,7 @@ module REXML # dt = DocType.new( doctype_to_clone ) # # Incomplete. Shallow clone of doctype # - # +Note+ that the constructor: + # +Note+ that the constructor: # # Doctype.new( Source.new( "<!DOCTYPE foo 'bar'>" ) ) # @@ -139,8 +139,8 @@ module REXML @entities = DEFAULT_ENTITIES.clone if @entities == DEFAULT_ENTITIES @entities[ child.name ] = child if child.kind_of? Entity end - - # This method retrieves the public identifier identifying the document's + + # This method retrieves the public identifier identifying the document's # DTD. # # Method contributed by Henrik Martensson @@ -152,7 +152,7 @@ module REXML strip_quotes(@long_name) end end - + # This method retrieves the system identifier identifying the document's DTD # # Method contributed by Henrik Martensson @@ -164,16 +164,16 @@ module REXML @uri.kind_of?(String) ? strip_quotes(@uri) : nil end end - + # This method returns a list of notations that have been declared in the - # _internal_ DTD subset. Notations in the external DTD subset are not + # _internal_ DTD subset. Notations in the external DTD subset are not # listed. # # Method contributed by Henrik Martensson def notations children().select {|node| node.kind_of?(REXML::NotationDecl)} end - + # Retrieves a named notation. Only notations declared in the internal # DTD subset can be retrieved. # @@ -183,9 +183,9 @@ module REXML notation_decl.name == name } end - + private - + # Method contributed by Henrik Martensson def strip_quotes(quoted_string) quoted_string =~ /^[\'\"].*[\'\"]$/ ? @@ -217,7 +217,7 @@ module REXML output << to_s end end - + public class ElementDecl < Declaration def initialize( src ) @@ -250,7 +250,7 @@ module REXML def to_s "<!NOTATION #@name #@middle#{ - @public ? ' ' + public.inspect : '' + @public ? ' ' + public.inspect : '' }#{ @system ? ' ' [email protected] : '' }>" @@ -259,7 +259,7 @@ module REXML def write( output, indent=-1 ) output << to_s end - + # This method retrieves the name of the notation. # # Method contributed by Henrik Martensson diff --git a/lib/rexml/document.rb b/lib/rexml/document.rb index 48f1a0ec6c..0fde6df1a1 100644 --- a/lib/rexml/document.rb +++ b/lib/rexml/document.rb @@ -25,7 +25,7 @@ module REXML DECLARATION = XMLDecl.default # Constructor - # @param source if supplied, must be a Document, String, or IO. + # @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. @@ -69,11 +69,11 @@ module REXML @children.unshift child child.parent = self elsif child.kind_of? DocType - # Find first Element or DocType node and insert the decl right + # Find first Element or DocType node and insert the decl right # before it. If there is no such node, just insert the child at the # end. If there is a child and it is an DocType, then replace it. insert_before_index = 0 - @children.find { |x| + @children.find { |x| insert_before_index += 1 x.kind_of?(Element) || x.kind_of?(DocType) } @@ -167,7 +167,7 @@ module REXML # indent:: # An integer. If -1, no indenting will be used; otherwise, the # indentation will be twice this number of spaces, and children will be - # indented an additional amount. For a value of 3, every item will be + # indented an additional amount. For a value of 3, every item will be # indented 3 more levels, or 6 more spaces (2 * 3). Defaults to -1 # transitive:: # If transitive is true and indent is >= 0, then the output will be @@ -178,7 +178,7 @@ module REXML # 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 + # that IE's limited abilities can handle. This hack inserts a space # before the /> on empty tags. Defaults to false def write( output=$stdout, indent=-1, transitive=false, ie_hack=false ) if xml_decl.encoding != "UTF-8" && !output.kind_of?(Output) @@ -197,7 +197,7 @@ module REXML formatter.write( self, output ) end - + def Document::parse_stream( source, listener ) Parsers::StreamParser.new( source, listener ).parse end @@ -215,7 +215,7 @@ module REXML end attr_reader :entity_expansion_count - + def record_entity_expansion @entity_expansion_count += 1 if @entity_expansion_count > @@entity_expansion_limit diff --git a/lib/rexml/dtd/entitydecl.rb b/lib/rexml/dtd/entitydecl.rb index 0adda6f7b9..a9286b2b90 100644 --- a/lib/rexml/dtd/entitydecl.rb +++ b/lib/rexml/dtd/entitydecl.rb @@ -49,7 +49,7 @@ module REXML def EntityDecl.parse_source source, listener md = source.match( PATTERN_RE, true ) thing = md[0].squeeze(" \t\n\r") - listener.send inspect.downcase, thing + listener.send inspect.downcase, thing end end end diff --git a/lib/rexml/dtd/notationdecl.rb b/lib/rexml/dtd/notationdecl.rb index eae71f2e52..17d1b9ef29 100644 --- a/lib/rexml/dtd/notationdecl.rb +++ b/lib/rexml/dtd/notationdecl.rb @@ -32,7 +32,7 @@ module REXML def NotationDecl.parse_source source, listener md = source.match( PATTERN_RE, true ) thing = md[0].squeeze(" \t\n\r") - listener.send inspect.downcase, thing + listener.send inspect.downcase, thing end end end diff --git a/lib/rexml/element.rb b/lib/rexml/element.rb index 92308a5c99..7a3abc65e5 100644 --- a/lib/rexml/element.rb +++ b/lib/rexml/element.rb @@ -30,13 +30,13 @@ module REXML attr_accessor :context # Constructor - # arg:: + # 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, + # If an Element, the object will be shallowly cloned; name, # attributes, and namespaces will be copied. Children will +not+ be # copied. - # parent:: + # parent:: # if supplied, must be a Parent, and will be used as # the parent of this object. # context:: @@ -97,7 +97,7 @@ module REXML self.class.new self end - # Evaluates to the root node of the document that this element + # 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. @@ -137,8 +137,8 @@ module REXML # 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 + # 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. @@ -162,7 +162,7 @@ module REXML @ignore_whitespace_nodes = false if @context if @context[:ignore_whitespace_nodes] - @ignore_whitespace_nodes = + @ignore_whitespace_nodes = (@context[:ignore_whitespace_nodes] == :all or @context[:ignore_whitespace_nodes].include? expanded_name) end @@ -206,13 +206,13 @@ module REXML return namespaces end - # Evalutas to the URI for a prefix, or the empty string if no such + # 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:: + # prefix:: # the prefix to search for. If not supplied, returns the default # namespace if one exists - # Returns:: + # 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>") @@ -235,10 +235,10 @@ module REXML end # Adds a namespace to this element. - # prefix:: + # prefix:: # the prefix string, or the namespace URI if +uri+ is not # supplied - # uri:: + # uri:: # the namespace URI. May be nil, in which +prefix+ is used as # the URI # Evaluates to: this Element @@ -280,12 +280,12 @@ module REXML # Adds a child to this element, optionally setting attributes in # the element. - # 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 + # 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' @@ -302,9 +302,9 @@ module REXML end # 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) + # 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. @@ -327,14 +327,14 @@ module REXML # Iterates through the child elements, yielding for each Element that # has a particular attribute set. - # key:: + # key:: # the name of the attribute to search for - # value:: + # value:: # the value of the attribute - # max:: - # (optional) causes this method to return after yielding + # max:: + # (optional) causes this method to return after yielding # for this number of matching children - # name:: + # name:: # (optional) if supplied, this is an XPath that filters # the children to check. # @@ -348,7 +348,7 @@ module REXML # # Yields d # doc.root.each_element_with_attribute( 'id', '1', 0, 'd' ) {|e| p e} def each_element_with_attribute( key, value=nil, max=0, name=nil, &block ) # :yields: Element - each_with_something( proc {|child| + each_with_something( proc {|child| if value.nil? child.attributes[key] != nil else @@ -359,13 +359,13 @@ module REXML # Iterates through the children, yielding for each Element that # has a particular text set. - # text:: + # text:: # the text to search for. If nil, or not supplied, will iterate # over all +Element+ children that contain at least one +Text+ node. - # max:: + # max:: # (optional) causes this method to return after yielding # for this number of matching children - # name:: + # name:: # (optional) if supplied, this is an XPath that filters # the children to check. # @@ -379,7 +379,7 @@ module REXML # # Yields d # doc.each_element_with_text(nil, 0, 'd'){|e|p e} def each_element_with_text( text=nil, max=0, name=nil, &block ) # :yields: Element - each_with_something( proc {|child| + each_with_something( proc {|child| if text.nil? child.has_text? else @@ -408,7 +408,7 @@ module REXML # doc.root.elements['c'].next_element #-> nil def next_element element = next_sibling - element = element.next_sibling until element.nil? or element.kind_of? Element + element = element.next_sibling until element.nil? or element.kind_of? Element return element end @@ -477,7 +477,7 @@ module REXML # 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:: + # 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 @@ -520,7 +520,7 @@ module REXML # Note that at the end of this example, the branch has <b>3</b> nodes; the 'e' # element and <b>2</b> Text node children. def add_text( text ) - if text.kind_of? String + if text.kind_of? String if @children[-1].kind_of? Text @children[-1] << text return @@ -559,7 +559,7 @@ module REXML end prefix = nil if prefix == 'xmlns' - ret_val = + ret_val = attributes.get_attribute( "#{prefix ? prefix + ':' : ''}#{name}" ) return ret_val unless ret_val.nil? @@ -586,7 +586,7 @@ module REXML # 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:: + # value:: # Required if +key+ is a String, and ignored if the first argument is # an Attribute. This is a String, and is used as the value # of the new Attribute. This should be the unnormalized value of the @@ -621,7 +621,7 @@ module REXML # 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:: + # Returns:: # the attribute removed, or nil if this Element did not contain # a matching attribute # e = Element.new('E') @@ -638,7 +638,7 @@ module REXML # Other Utilities # ################################################# - # Get an array of all CData children. + # Get an array of all CData children. # IMMUTABLE def cdatas find_all { |child| child.kind_of? CData }.freeze @@ -681,7 +681,7 @@ module REXML # 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 + # that IE's limited abilities can handle. This hack inserts a space # before the /> on empty tags. Defaults to false # # out = '' @@ -707,8 +707,8 @@ module REXML def __to_xpath_helper node rv = node.expanded_name.clone if node.parent - results = node.parent.find_all {|n| - n.kind_of?(REXML::Element) and n.expanded_name == node.expanded_name + results = node.parent.find_all {|n| + n.kind_of?(REXML::Element) and n.expanded_name == node.expanded_name } if results.length > 1 idx = results.index( node ) @@ -734,7 +734,7 @@ module REXML # A class which provides filtering of children for Elements, and # XPath search support. You are expected to only encounter this class as - # the <tt>element.elements</tt> object. Therefore, you are + # the <tt>element.elements</tt> object. Therefore, you are # _not_ expected to instantiate this yourself. class Elements include Enumerable @@ -746,7 +746,7 @@ module REXML # Fetches a child element. Filters only Element children, regardless of # the XPath match. - # index:: + # 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. <em>Because @@ -756,7 +756,7 @@ module REXML # child element is at index 1, not 0, and the +n+th element is at index # +n+, not <tt>n-1</tt>. This is because XPath indexes element children # starting from 1, not 0, and the indexes should be the same. - # name:: + # 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. @@ -772,12 +772,12 @@ module REXML num = 0 @element.find { |child| child.kind_of? Element and - (name.nil? ? true : child.has_name?( name )) and + (name.nil? ? true : child.has_name?( name )) and (num += 1) == index } else return XPath::first( @element, index ) - #{ |element| + #{ |element| # return element if element.kind_of? Element #} #return nil @@ -787,7 +787,7 @@ module REXML # 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:: + # element:: # The element to replace the existing element with # the previous element # Returns:: nil if no previous element was found. @@ -812,12 +812,12 @@ module REXML @element.find{ |child| child.kind_of? Element}.nil? end - # Returns the index of the supplied child (starting at 1), or -1 if + # Returns the index of the supplied child (starting at 1), or -1 if # the element is not a child # element:: an +Element+ child def index element rv = 0 - found = @element.find do |child| + found = @element.find do |child| child.kind_of? Element and (rv += 1) and child == element @@ -827,7 +827,7 @@ module REXML end # Deletes a child Element - # 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. @@ -854,7 +854,7 @@ module REXML # deleted = doc.elements.delete_all 'a/c' #-> [<c/>, <c/>, <c/>, <c/>] def delete_all( xpath ) rv = [] - XPath::each( @element, xpath) {|element| + XPath::each( @element, xpath) {|element| rv << element if element.kind_of? Element } rv.each do |element| @@ -865,7 +865,7 @@ module REXML end # Adds an element - # 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 @@ -890,8 +890,8 @@ module REXML # 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 + # 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 @@ -908,8 +908,8 @@ module REXML def collect( xpath=nil, &block ) collection = [] - XPath::each( @element, xpath ) {|e| - collection << yield(e) if e.kind_of?(Element) + XPath::each( @element, xpath ) {|e| + collection << yield(e) if e.kind_of?(Element) } collection end @@ -944,7 +944,7 @@ module REXML # 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/> ] + # doc.root.elements.to_a("child::node()") #-> [ <b/>, <c/> ] # XPath.match(doc.root, "child::node()") #-> [ sean, <b/>, elliott, <c/> ] def to_a( xpath=nil ) rv = XPath.match( @element, xpath ) @@ -964,7 +964,7 @@ module REXML # ATTRIBUTES # ######################################################################## - # A class that defines the set of Attributes of an Element and provides + # A class that defines the set of Attributes of an Element and provides # operations for accessing elements in that set. class Attributes < Hash # Constructor @@ -976,11 +976,11 @@ module REXML # 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:: + # Returns:: # the String value of the matching attribute, or +nil+ if no # matching attribute was found. This is the unnormalized value # (with entities expanded). - # + # # doc = Document.new "<a foo:att='1' bar:att='2' att='<'/>" # doc.root.attributes['att'] #-> '<' # doc.root.attributes['bar:att'] #-> '2' @@ -1006,7 +1006,7 @@ module REXML # Iterates 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 @@ -1033,7 +1033,7 @@ module REXML end # Fetches an attribute - # name:: + # name:: # the name by which to search for the attribute. Can be a # <tt>prefix:name</tt> namespace name. # Returns:: The first matching attribute, or nil if there was none. This @@ -1077,10 +1077,10 @@ module REXML # Sets an attribute, overwriting any existing attribute value by the # same name. Namespace is significant. # name:: the name of the attribute - # value:: + # value:: # (optional) If supplied, the value of the attribute. If # nil, any existing matching attribute is deleted. - # Returns:: + # Returns:: # Owning element # doc = Document.new "<a x:foo='1' foo='3'/>" # doc.root.attributes['y:foo'] = '2' @@ -1109,13 +1109,13 @@ module REXML old_attr[value.prefix] = value elsif old_attr.prefix != value.prefix # Check for conflicting namespaces - raise ParseException.new( + 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}\" = \"#{@element.namespace(value.prefix)}\"") if value.prefix != "xmlns" and old_attr.prefix != "xmlns" and - @element.namespace( old_attr.prefix ) == + @element.namespace( old_attr.prefix ) == @element.namespace( value.prefix ) store value.name, { old_attr.prefix => old_attr, value.prefix => value } @@ -1125,7 +1125,7 @@ module REXML return @element end - # Returns an array of Strings containing all of the prefixes declared + # 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' "+ @@ -1164,7 +1164,7 @@ module REXML end # Removes an attribute - # 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 @@ -1212,12 +1212,12 @@ module REXML alias :<< :add # Deletes all attributes matching a name. Namespaces are significant. - # name:: + # name:: # A String; all attributes that match this path will be removed # Returns:: an Array of the Attributes that were removed def delete_all( name ) rv = [] - each_attribute { |attribute| + each_attribute { |attribute| rv << attribute if attribute.expanded_name == name } rv.each{ |attr| attr.remove } @@ -1227,7 +1227,7 @@ module REXML # The +get_attribute_ns+ method retrieves a method by its namespace # and name. Thus it is possible to reliably identify an attribute # even if an XML processor has changed the prefix. - # + # # Method contributed by Henrik Martensson def get_attribute_ns(namespace, name) result = nil @@ -1236,7 +1236,7 @@ module REXML namespace == attribute.namespace() && ( !namespace.empty? || !attribute.fully_expanded_name.index(':') ) # foo will match xmlns:foo, but only if foo isn't also an attribute - result = attribute if !result or !namespace.empty? or + result = attribute if !result or !namespace.empty? or !attribute.fully_expanded_name.index(':') end } diff --git a/lib/rexml/encoding.rb b/lib/rexml/encoding.rb index 608c69cd65..3feffb80f4 100644 --- a/lib/rexml/encoding.rb +++ b/lib/rexml/encoding.rb @@ -29,7 +29,7 @@ module REXML if enc and enc != UTF_8 @encoding = enc raise ArgumentError, "Bad encoding name #@encoding" unless @encoding =~ /^[\w-]+$/ - @encoding.untaint + @encoding.untaint begin require 'rexml/encodings/ICONV.rb' Encoding.apply(self, "ICONV") diff --git a/lib/rexml/encodings/CP-1252.rb b/lib/rexml/encodings/CP-1252.rb index 2ef6a1a291..587c5bdd68 100644 --- a/lib/rexml/encodings/CP-1252.rb +++ b/lib/rexml/encodings/CP-1252.rb @@ -58,7 +58,7 @@ module REXML end array_enc.pack('C*') end - + # Convert to UTF-8 def decode_cp1252(str) array_latin9 = str.unpack('C*') diff --git a/lib/rexml/encodings/ISO-8859-15.rb b/lib/rexml/encodings/ISO-8859-15.rb index 953267250e..08a19cb755 100644 --- a/lib/rexml/encodings/ISO-8859-15.rb +++ b/lib/rexml/encodings/ISO-8859-15.rb @@ -46,7 +46,7 @@ module REXML end array_enc.pack('C*') end - + # Convert to UTF-8 def from_iso_8859_15(str) array_latin9 = str.unpack('C*') diff --git a/lib/rexml/encodings/UNILE.rb b/lib/rexml/encodings/UNILE.rb index d054140c40..1a18f0c932 100644 --- a/lib/rexml/encodings/UNILE.rb +++ b/lib/rexml/encodings/UNILE.rb @@ -18,7 +18,7 @@ module REXML def decode_unile(str) array_enc=str.unpack('C*') array_utf8 = [] - 0.step(array_enc.size-1, 2){|i| + 0.step(array_enc.size-1, 2){|i| array_utf8 << (array_enc.at(i) + array_enc.at(i+1)*0x100) } array_utf8.pack('U*') diff --git a/lib/rexml/encodings/UTF-16.rb b/lib/rexml/encodings/UTF-16.rb index 007c493d9c..2ec058eed5 100644 --- a/lib/rexml/encodings/UTF-16.rb +++ b/lib/rexml/encodings/UTF-16.rb @@ -19,7 +19,7 @@ module REXML str = str[2..-1] if /^\376\377/n =~ str array_enc=str.unpack('C*') array_utf8 = [] - 0.step(array_enc.size-1, 2){|i| + 0.step(array_enc.size-1, 2){|i| array_utf8 << (array_enc.at(i+1) + array_enc.at(i)*0x100) } array_utf8.pack('U*') diff --git a/lib/rexml/entity.rb b/lib/rexml/entity.rb index d2f27ecd44..5e3edf4eeb 100644 --- a/lib/rexml/entity.rb +++ b/lib/rexml/entity.rb @@ -30,7 +30,7 @@ module REXML # 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', '&' ) def initialize stream, value=nil, parent=nil, reference=false super(parent) @@ -38,7 +38,7 @@ module REXML if stream.kind_of? Array @name = stream[1] if stream[-1] == '%' - @reference = true + @reference = true stream.pop else @reference = false diff --git a/lib/rexml/formatters/default.rb b/lib/rexml/formatters/default.rb index b4d63bc5b5..56a1d93783 100644 --- a/lib/rexml/formatters/default.rb +++ b/lib/rexml/formatters/default.rb @@ -21,7 +21,7 @@ module REXML def write( node, output ) case node - when Document + when Document if node.xml_decl.encoding != "UTF-8" && !output.kind_of?(Output) output = Output.new( output, node.xml_decl.encoding ) end @@ -70,7 +70,7 @@ module REXML if node.children.empty? output << " " if @ie_hack - output << "/" + output << "/" else output << ">" node.children.each { |child| diff --git a/lib/rexml/formatters/pretty.rb b/lib/rexml/formatters/pretty.rb index 84c442e8bb..17d217d1dc 100644 --- a/lib/rexml/formatters/pretty.rb +++ b/lib/rexml/formatters/pretty.rb @@ -48,7 +48,7 @@ module REXML if @ie_hack output << " " end - output << "/" + output << "/" else output << ">" # If compact and all children are text, and if the formatted output diff --git a/lib/rexml/formatters/transitive.rb b/lib/rexml/formatters/transitive.rb index 6083f0390b..3a52e03f01 100644 --- a/lib/rexml/formatters/transitive.rb +++ b/lib/rexml/formatters/transitive.rb @@ -31,7 +31,7 @@ module REXML output << ' '*@level if node.children.empty? output << " " if @ie_hack - output << "/" + output << "/" else output << ">" # If compact and all children are text, and if the formatted output diff --git a/lib/rexml/functions.rb b/lib/rexml/functions.rb index fc9c4701c4..2d30e5fe92 100644 --- a/lib/rexml/functions.rb +++ b/lib/rexml/functions.rb @@ -48,7 +48,7 @@ module REXML # UNTESTED def Functions::local_name( node_set=nil ) get_namespace( node_set ) do |node| - return node.local_name + return node.local_name end end @@ -57,7 +57,7 @@ module REXML end def Functions::name( node_set=nil ) - get_namespace( node_set ) do |node| + get_namespace( node_set ) do |node| node.expanded_name end end @@ -66,7 +66,7 @@ module REXML def Functions::get_namespace( node_set = nil ) if node_set == nil yield @@context[:node] if defined? @@context[:node].namespace - else + else if node_set.respond_to? :each node_set.each { |node| yield node if defined? node.namespace } elsif node_set.respond_to? :namespace @@ -81,15 +81,15 @@ module REXML # # A number is converted to a string as follows # - # NaN is converted to the string NaN + # NaN is converted to the string NaN # - # positive zero is converted to the string 0 + # positive zero is converted to the string 0 # - # negative zero is converted to the string 0 + # negative zero is converted to the string 0 # - # positive infinity is converted to the string Infinity + # positive infinity is converted to the string Infinity # - # negative 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 @@ -156,7 +156,7 @@ module REXML string(string).include?(string(test)) end - # Kouhei fixed this + # Kouhei fixed this def Functions::substring_before( string, test ) ruby_string = string(string) ruby_index = ruby_string.index(string(test)) @@ -166,7 +166,7 @@ module REXML ruby_string[ 0...ruby_index ] end end - + # Kouhei fixed this too def Functions::substring_after( string, test ) ruby_string = string(string) @@ -175,11 +175,11 @@ module REXML "" end - # Take equal portions of Mike Stok and Sean Russell; mix + # Take equal portions of Mike Stok and Sean Russell; mix # vigorously, and pour into a tall, chilled glass. Serves 10,000. def Functions::substring( string, start, length=nil ) ruby_string = string(string) - ruby_length = if length.nil? + ruby_length = if length.nil? ruby_string.length.to_f else number(length) @@ -188,15 +188,15 @@ module REXML # Handle the special cases return '' if ( - ruby_length.nan? or + 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 + + # 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 @@ -247,7 +247,7 @@ module REXML 0.upto(from.length - 1) { |pos| from_char = from[pos] unless map.has_key? from_char - map[from_char] = + map[from_char] = if pos < to.length to[pos] else @@ -359,7 +359,7 @@ module REXML nodes = [nodes] unless nodes.kind_of? Array nodes.inject(0) { |r,n| r += number(string(n)) } end - + def Functions::floor( number ) number(number).floor end diff --git a/lib/rexml/instruction.rb b/lib/rexml/instruction.rb index 50bf95d17a..f8b734a5b5 100644 --- a/lib/rexml/instruction.rb +++ b/lib/rexml/instruction.rb @@ -13,7 +13,7 @@ module REXML attr_accessor :target, :content # Constructs a new Instruction - # @param target can be one of a number of things. If String, then + # @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 @@ -37,7 +37,7 @@ module REXML def clone Instruction.new self end - + # == DEPRECATED # See the rexml/formatters package # diff --git a/lib/rexml/namespace.rb b/lib/rexml/namespace.rb index 8d43fc85ad..aeb339ee83 100644 --- a/lib/rexml/namespace.rb +++ b/lib/rexml/namespace.rb @@ -40,7 +40,7 @@ module REXML # source file. def fully_expanded_name ns = prefix - return "#{ns}:#@name" if ns.size > 0 + return "#{ns}:#@name" if ns.size > 0 return @name end end diff --git a/lib/rexml/node.rb b/lib/rexml/node.rb index eb39141944..85457f1ad0 100644 --- a/lib/rexml/node.rb +++ b/lib/rexml/node.rb @@ -57,7 +57,7 @@ module REXML } end - # Find (and return) first subnode (recursively) for which the block + # Find (and return) first subnode (recursively) for which the block # evaluates to true. Returns +nil+ if none was found. def find_first_recursive(&block) # :yields: node each_recursive {|node| diff --git a/lib/rexml/output.rb b/lib/rexml/output.rb index 997f2b117d..b7f17b9dff 100644 --- a/lib/rexml/output.rb +++ b/lib/rexml/output.rb @@ -3,7 +3,7 @@ require 'rexml/encoding' module REXML class Output include Encoding - + attr_reader :encoding def initialize real_IO, encd="iso-8859-1" diff --git a/lib/rexml/parent.rb b/lib/rexml/parent.rb index a20aaaef6b..7ed1761654 100644 --- a/lib/rexml/parent.rb +++ b/lib/rexml/parent.rb @@ -6,14 +6,14 @@ module REXML # object. class Parent < Child include Enumerable - + # Constructor # @param parent if supplied, will be set as the parent of this object def initialize parent=nil super(parent) @children = [] end - + def add( object ) #puts "PARENT GOTS #{size} CHILDREN" object.parent = self @@ -21,47 +21,47 @@ module REXML #puts "PARENT NOW GOTS #{size} CHILDREN" object end - + alias :push :add alias :<< :push - + def unshift( object ) object.parent = self @children.unshift object end - + def delete( object ) found = false @children.delete_if {|c| c.equal?(object) and found = true } object.parent = nil if found end - + def each(&block) @children.each(&block) end - + def delete_if( &block ) @children.delete_if(&block) end - + def delete_at( index ) @children.delete_at index end - + def each_index( &block ) @children.each_index(&block) end - + # Fetches a child at a given index # @param index the Integer index of the child to fetch def []( index ) @children[index] end - + alias :each_child :each - - - + + + # 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 @@ -71,7 +71,7 @@ module REXML args[-1].parent = self @children[*args[0..-2]] = args[-1] end - + # 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. @@ -91,7 +91,7 @@ module REXML end self end - + # 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. @@ -111,11 +111,11 @@ module REXML end self end - + def to_a @children.dup end - + # 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 @@ -125,24 +125,24 @@ module REXML @children.find { |i| count += 1 ; i.hash == child.hash } count end - + # @return the number of children of this parent def size @children.size end - + alias :length :size - + # 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 + # @param replacement the child to insert into the nodelist (must be a # Child) def replace_child( to_replace, replacement ) @children.map! {|c| c.equal?( to_replace ) ? replacement : c } to_replace.parent = nil replacement.parent = self end - + # Deeply clones this object. This creates a complete duplicate of this # Parent, including all descendants. def deep_clone @@ -156,9 +156,9 @@ module REXML end cl end - + alias :children :to_a - + def parent? true end diff --git a/lib/rexml/parseexception.rb b/lib/rexml/parseexception.rb index feb7a7e638..0481f72818 100644 --- a/lib/rexml/parseexception.rb +++ b/lib/rexml/parseexception.rb @@ -30,7 +30,7 @@ module REXML err << "Last 80 unconsumed characters:\n" err << @source.buffer[0..80].gsub(/\n/, ' ') end - + err end @@ -40,12 +40,12 @@ module REXML end def line - @source.current_line[2] if @source and defined? @source.current_line and + @source.current_line[2] if @source and defined? @source.current_line and @source.current_line end def context @source.current_line end - end + end end diff --git a/lib/rexml/parsers/baseparser.rb b/lib/rexml/parsers/baseparser.rb index 162d029a62..2f758265bb 100644 --- a/lib/rexml/parsers/baseparser.rb +++ b/lib/rexml/parsers/baseparser.rb @@ -105,11 +105,11 @@ module REXML EREFERENCE = /&(?!#{NAME};)/ - DEFAULT_ENTITIES = { - 'gt' => [/>/, '>', '>', />/], - 'lt' => [/</, '<', '<', /</], - 'quot' => [/"/, '"', '"', /"/], - "apos" => [/'/, "'", "'", /'/] + DEFAULT_ENTITIES = { + 'gt' => [/>/, '>', '>', />/], + 'lt' => [/</, '<', '<', /</], + 'quot' => [/"/, '"', '"', /"/], + "apos" => [/'/, "'", "'", /'/] } @@ -180,9 +180,9 @@ module REXML # 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. + # 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. def peek depth=0 raise %Q[Illegal argument "#{depth}"] if depth < -1 temp = [] @@ -265,7 +265,7 @@ module REXML if @document_status == :in_doctype md = @source.match(/\s*(.*?>)/um) case md[1] - when SYSTEMENTITY + when SYSTEMENTITY match = @source.match( SYSTEMENTITY, true )[1] return [ :externalentity, match ] @@ -344,7 +344,7 @@ module REXML #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]}\")", + "'#{last_tag}' (got \"#{md[1]}\")", @source) unless last_tag == md[1] return [ :end_element, last_tag ] elsif @source.buffer[1] == ?! @@ -377,7 +377,7 @@ module REXML unless md # Check for missing attribute quotes raise REXML::ParseException.new("missing attribute quote", @source) if @source.match(MISSING_ATTRIBUTE_QUOTES ) - raise REXML::ParseException.new("malformed XML: missing tag start", @source) + raise REXML::ParseException.new("malformed XML: missing tag start", @source) end attributes = {} prefixes = Set.new @@ -386,7 +386,7 @@ module REXML if md[4].size > 0 attrs = md[4].scan( ATTRIBUTE_PATTERN ) raise REXML::ParseException.new( "error parsing attributes: [#{attrs.join ', '}], excess = \"#$'\"", @source) if $' and $'.strip.size > 0 - attrs.each { |a,b,c,d,e| + attrs.each { |a,b,c,d,e| if b == "xmlns" if c == "xml" if d != "http://www.w3.org/XML/1998/namespace" @@ -409,10 +409,10 @@ module REXML raise REXML::ParseException.new( msg, @source, self) end - attributes[a] = e + attributes[a] = e } end - + # Verify that all of the prefixes have been defined for prefix in prefixes unless @nsstack.find{|k| k.member?(prefix)} @@ -466,7 +466,7 @@ module REXML # Doing it like this rather than in a loop improves the speed copy.gsub!( EREFERENCE, '&' ) entities.each do |key, value| - copy.gsub!( value, "&#{key};" ) unless entity_filter and + copy.gsub!( value, "&#{key};" ) unless entity_filter and entity_filter.include?(entity) end if entities copy.gsub!( EREFERENCE, '&' ) diff --git a/lib/rexml/parsers/pullparser.rb b/lib/rexml/parsers/pullparser.rb index 36dc7160c3..68a4ff7eae 100644 --- a/lib/rexml/parsers/pullparser.rb +++ b/lib/rexml/parsers/pullparser.rb @@ -68,7 +68,7 @@ module REXML event = @parser.pull case event[0] when :entitydecl - @entities[ event[1] ] = + @entities[ event[1] ] = event[2] unless event[2] =~ /PUBLIC|SYSTEM/ when :text unnormalized = @parser.unnormalize( event[1], @entities ) diff --git a/lib/rexml/parsers/sax2parser.rb b/lib/rexml/parsers/sax2parser.rb index 72131401c3..d0f0c5155e 100644 --- a/lib/rexml/parsers/sax2parser.rb +++ b/lib/rexml/parsers/sax2parser.rb @@ -20,7 +20,7 @@ module REXML def source @parser.source end - + def add_listener( listener ) @parser.add_listener( listener ) end @@ -44,7 +44,7 @@ module REXML # :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 + # This will be called for every event generated, passing in the current # stream position. # # Array contains regular expressions or strings which will be matched @@ -72,7 +72,7 @@ module REXML add([nil, nil, args[0]]) end end - + def deafen( listener=nil, &blok ) if listener @listeners.delete_if {|item| item[-1] == listener } @@ -81,10 +81,10 @@ module REXML @procs.delete_if {|item| item[-1] == blok } end end - + def parse @procs.each { |sym,match,block| block.call if sym == :start_document } - @listeners.each { |sym,match,block| + @listeners.each { |sym,match,block| block.start_document if sym == :start_document or sym.nil? } root = context = [] @@ -126,8 +126,8 @@ module REXML 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] ) + listeners.each { |ob| + ob.start_element( uri, local, event[1], event[2] ) } if listeners when :end_element @tag_stack.pop @@ -140,8 +140,8 @@ module REXML 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] ) + listeners.each { |ob| + ob.end_element( uri, local, event[1] ) } if listeners namespace_mapping = @namespace_stack.pop @@ -160,7 +160,7 @@ module REXML #handle( :characters, normalized ) copy = event[1].clone - esub = proc { |match| + esub = proc { |match| if @entities.has_key?($1) @entities[$1].gsub(Text::REFERENCE, &esub) else @@ -178,7 +178,7 @@ module REXML when :entitydecl @entities[ event[1] ] = event[2] if event.size == 3 handle( *event ) - when :processing_instruction, :comment, :attlistdecl, + when :processing_instruction, :comment, :attlistdecl, :elementdecl, :cdata, :notationdecl, :xmldecl handle( *event ) end @@ -193,8 +193,8 @@ module REXML listeners = get_listeners( symbol, tag ) # notify observers procs.each { |ob| ob.call( *arguments ) } if procs - listeners.each { |l| - l.send( symbol.to_s, *arguments ) + listeners.each { |l| + l.send( symbol.to_s, *arguments ) } if listeners end @@ -205,7 +205,7 @@ module REXML @procs.find_all do |sym, match, block| #puts sym.inspect+"=="+symbol.inspect+ "\t"+match.inspect+"=="+name.inspect+ "\t"+( (sym.nil? or symbol == sym) and ((name.nil? and match.nil?) or match.nil? or ( (name == match) or (match.kind_of? Regexp and name =~ match)))).to_s ( - (sym.nil? or symbol == sym) and + (sym.nil? or symbol == sym) and ((name.nil? and match.nil?) or match.nil? or ( (name == match) or (match.kind_of? Regexp and name =~ match) @@ -218,7 +218,7 @@ module REXML return nil if @listeners.size == 0 @listeners.find_all do |sym, match, block| ( - (sym.nil? or symbol == sym) and + (sym.nil? or symbol == sym) and ((name.nil? and match.nil?) or match.nil? or ( (name == match) or (match.kind_of? Regexp and name =~ match) @@ -237,7 +237,7 @@ module REXML end end - def get_namespace( prefix ) + def get_namespace( prefix ) uris = (@namespace_stack.find_all { |ns| not ns[prefix].nil? }) || (@namespace_stack.find { |ns| not ns[nil].nil? }) uris[-1][prefix] unless uris.nil? or 0 == uris.size diff --git a/lib/rexml/parsers/streamparser.rb b/lib/rexml/parsers/streamparser.rb index 256d0f611c..073fcc2c21 100644 --- a/lib/rexml/parsers/streamparser.rb +++ b/lib/rexml/parsers/streamparser.rb @@ -5,11 +5,11 @@ module REXML @listener = listener @parser = BaseParser.new( source ) end - + def add_listener( listener ) @parser.add_listener( listener ) end - + def parse # entity string while true diff --git a/lib/rexml/parsers/treeparser.rb b/lib/rexml/parsers/treeparser.rb index 30327d0dfd..7f618cb319 100644 --- a/lib/rexml/parsers/treeparser.rb +++ b/lib/rexml/parsers/treeparser.rb @@ -42,8 +42,8 @@ module REXML 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) + @build_context.add( + Text.new(event[1], @build_context.whitespace, nil, true) ) unless ( @build_context.ignore_whitespace_nodes and event[1].strip.size==0 diff --git a/lib/rexml/parsers/xpathparser.rb b/lib/rexml/parsers/xpathparser.rb index 49450b4aef..aafa72ab9e 100644 --- a/lib/rexml/parsers/xpathparser.rb +++ b/lib/rexml/parsers/xpathparser.rb @@ -53,8 +53,8 @@ module REXML string << "*" when :text string << "text()" - when :following, :following_sibling, - :ancestor, :ancestor_or_self, :descendant, + when :following, :following_sibling, + :ancestor, :ancestor_or_self, :descendant, :namespace, :preceding, :preceding_sibling string << "/" unless string.size == 0 string << op.to_s.tr("_", "-") @@ -97,7 +97,7 @@ module REXML case op when :node string << "node()" - when :attribute, :child, :following, :following_sibling, + 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 @@ -249,7 +249,7 @@ module REXML parsed.concat(n) end - + if path.size > 0 if path[0] == ?/ if path[1] == ?/ @@ -332,12 +332,12 @@ module REXML predicates << expr[1..-2] if expr end #puts "PREDICATES = #{predicates.inspect}" - predicates.each{ |pred| + predicates.each{ |pred| #puts "ORING #{pred}" preds = [] parsed << :predicate parsed << preds - OrExpr(pred, preds) + OrExpr(pred, preds) } #puts "PREDICATES = #{predicates.inspect}" path @@ -600,13 +600,13 @@ module REXML #puts "LITERAL or NUMBER: #$1" varname = $1.nil? ? $2 : $1 path = $' - parsed << :literal + parsed << :literal parsed << (varname.include?('.') ? varname.to_f : varname.to_i) when LITERAL #puts "LITERAL or NUMBER: #$1" varname = $1.nil? ? $2 : $1 path = $' - parsed << :literal + parsed << :literal parsed << varname when /^\(/ #/ path, contents = get_group(path) @@ -649,7 +649,7 @@ module REXML return nil unless depth==0 [string[ind..-1], string[0..ind-1]] end - + def parse_args( string ) arguments = [] ind = 0 @@ -683,7 +683,7 @@ module REXML s = string[0,ind].strip arguments << s unless s == "" string = string[ind+1..-1] - ind = -1 + ind = -1 end end end diff --git a/lib/rexml/quickpath.rb b/lib/rexml/quickpath.rb index fd2ebdd0ca..95fc72b7c2 100644 --- a/lib/rexml/quickpath.rb +++ b/lib/rexml/quickpath.rb @@ -68,7 +68,7 @@ module REXML ns = $1 rest = $' elements.delete_if do |element| - !(element.kind_of? Element and + !(element.kind_of? Element and (element.expanded_name == name or (element.name == name and element.namespace == Functions.namespace_context[ns]))) @@ -135,16 +135,16 @@ module REXML matches = filter(elements.collect{|element| element.next_sibling}.uniq, rest) when "previous-sibling" - matches = filter(elements.collect{|element| + matches = filter(elements.collect{|element| element.previous_sibling}.uniq, rest ) end return matches.uniq end # 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 + # 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 @@ -157,7 +157,7 @@ module REXML # 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]. - def QuickPath::predicate( elements, path ) + def QuickPath::predicate( elements, path ) ind = 1 bcount = 1 while bcount > 0 @@ -175,13 +175,13 @@ module REXML # 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!( /@(\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| diff --git a/lib/rexml/rexml.rb b/lib/rexml/rexml.rb index 810af31356..ab2f44561b 100644 --- a/lib/rexml/rexml.rb +++ b/lib/rexml/rexml.rb @@ -5,20 +5,20 @@ # non-validating[http://www.w3.org/TR/2004/REC-xml-20040204/#sec-conformance] # toolkit with an intuitive API. REXML passes 100% of the non-validating Oasis # tests[http://www.oasis-open.org/committees/xml-conformance/xml-test-suite.shtml], -# and provides tree, stream, SAX2, pull, and lightweight APIs. REXML also -# includes a full XPath[http://www.w3c.org/tr/xpath] 1.0 implementation. Since +# and provides tree, stream, SAX2, pull, and lightweight APIs. REXML also +# includes a full XPath[http://www.w3c.org/tr/xpath] 1.0 implementation. Since # Ruby 1.8, REXML is included in the standard Ruby distribution. # # Main page:: http://www.germane-software.com/software/rexml # Author:: Sean Russell <serATgermaneHYPHENsoftwareDOTcom> # Date:: 2008/019 # Version:: 3.1.7.3 -# +# # This API documentation can be downloaded from the REXML home page, or can # be accessed online[http://www.germane-software.com/software/rexml_doc] # # A tutorial is available in the REXML distribution in docs/tutorial.html, -# or can be accessed +# or can be accessed # online[http://www.germane-software.com/software/rexml/docs/tutorial.html] module REXML COPYRIGHT = "Copyright © 2001-2008 Sean Russell <[email protected]>" diff --git a/lib/rexml/sax2listener.rb b/lib/rexml/sax2listener.rb index 9545b08a93..6830e4483a 100644 --- a/lib/rexml/sax2listener.rb +++ b/lib/rexml/sax2listener.rb @@ -1,11 +1,11 @@ module REXML # 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 + # 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 + # === Methods extending SAX2 # +WARNING+ # These methods are certainly going to change, until DTDs are fully # supported. Be aware of this. @@ -58,7 +58,7 @@ module REXML # 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"'> + # <!ENTITY % YN '"Yes"'> # ["%", "YN", "'\"Yes\"'", "\""] # <!ENTITY % YN 'Yes'> # ["%", "YN", "'Yes'", "s"] @@ -93,5 +93,5 @@ module REXML end def progress position end - end + end end diff --git a/lib/rexml/source.rb b/lib/rexml/source.rb index d4335138a1..3f6d4ffa26 100644 --- a/lib/rexml/source.rb +++ b/lib/rexml/source.rb @@ -69,9 +69,9 @@ module REXML # 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 + # 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 @@ -194,7 +194,7 @@ module REXML def read begin str = @source.readline(@line_break) - str = decode(str) if @to_utf and str + str = decode(str) if @to_utf and str @buffer << str if not @to_utf and @buffer.respond_to? :force_encoding @buffer.force_encoding Encoding::UTF_8 @@ -225,7 +225,7 @@ module REXML rv.taint rv end - + def empty? super and ( @source.nil? || @source.eof? ) end diff --git a/lib/rexml/streamlistener.rb b/lib/rexml/streamlistener.rb index 3a4ef9f769..619c529578 100644 --- a/lib/rexml/streamlistener.rb +++ b/lib/rexml/streamlistener.rb @@ -1,14 +1,14 @@ module REXML # 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 + # processed; REXML doesn't yet handle doctype entity declarations, so you # have to parse them out yourself. module StreamListener # 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 + # will result in # tag_start( "tag", # [["attr1","value1"],["attr2","value2"]]) def tag_start name, attrs end @@ -56,7 +56,7 @@ module REXML # 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"'> + # <!ENTITY % YN '"Yes"'> # ["%", "YN", "'\"Yes\"'", "\""] # <!ENTITY % YN 'Yes'> # ["%", "YN", "'Yes'", "s"] diff --git a/lib/rexml/text.rb b/lib/rexml/text.rb index fac5ac3e41..d09dc3ac54 100644 --- a/lib/rexml/text.rb +++ b/lib/rexml/text.rb @@ -19,7 +19,7 @@ module REXML attr_accessor :raw NEEDS_A_SECOND_CHECK = /(<|&((#{Entity::NAME});|(#0*((?:\d+)|(?:x[a-fA-F0-9]+)));)?)/um - NUMERICENTITY = /�*((?:\d+)|(?:x[a-fA-F0-9]+));/ + NUMERICENTITY = /�*((?:\d+)|(?:x[a-fA-F0-9]+));/ VALID_CHAR = [ 0x9, 0xA, 0xD, (0x20..0xD7FF), @@ -50,25 +50,25 @@ module REXML | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16 - )*$/nx; + )*$/nx; end # Constructor # +arg+ if a String, the content is set to the String. If a Text, - # the object is shallowly cloned. + # 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. + # 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 + # 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 + # text. If this value is nil (the default), then the raw value of the # parent will be used as the raw value for this node. If there is no raw # value for the parent, and no value is supplied, the default is false. # Use this field if you have entities defined for some text, and you don't @@ -89,14 +89,14 @@ module REXML # In the last example, the +entity_filter+ argument is ignored. # # +pattern+ INTERNAL USE ONLY - def initialize(arg, respect_whitespace=false, parent=nil, raw=nil, + def initialize(arg, respect_whitespace=false, parent=nil, raw=nil, entity_filter=nil, illegal=NEEDS_A_SECOND_CHECK ) @raw = false if parent super( parent ) - @raw = parent.raw + @raw = parent.raw else @parent = nil end @@ -208,12 +208,12 @@ module REXML # 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 + # + # # 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 = Text.new( "< & sean russell", false, nil, false, ['s'] ) # t.to_s #-> "< & &s; russell" - # t = Text.new( "< & &s; russell", false, nil, false ) + # t = Text.new( "< & &s; russell", false, nil, false ) # t.to_s #-> "< & &s; russell" # u = Text.new( "sean russell", false, nil, true ) # u.to_s #-> "sean russell" @@ -233,9 +233,9 @@ module REXML # console. This ignores the 'raw' attribute setting, and any # entity_filter. # - # # Assume that the entity "s" is defined to be "sean", and that the + # # 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 = Text.new( "< & sean russell", false, nil, false, ['s'] ) # t.value #-> "< & sean russell" # t = Text.new( "< & &s; russell", false, nil, false ) # t.value #-> "< & sean russell" @@ -246,7 +246,7 @@ module REXML @unnormalized = Text::unnormalize( @string, doctype ) end - # Sets the contents of this text node. This expects the text to be + # Sets the contents of this text node. This expects the text to be # unnormalized. It returns self. # # e = Element.new( "a" ) @@ -259,7 +259,7 @@ module REXML @normalized = nil @raw = false end - + def wrap(string, width, addnewline=false) # Recursively wrap string at width. return string if string.length <= width @@ -282,11 +282,11 @@ module REXML new_string.strip! unless indentfirstline return new_string end - + # == DEPRECATED # See REXML::Formatters # - def write( writer, indent=-1, transitive=false, ie_hack=false ) + def write( writer, indent=-1, transitive=false, ie_hack=false ) Kernel.warn("#{self.class.name}.write is deprecated. See REXML::Formatters") formatter = if indent > -1 REXML::Formatters::Pretty.new( indent ) @@ -337,7 +337,7 @@ module REXML 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] ) @@ -365,8 +365,8 @@ module REXML if doctype # Replace all ampersands that aren't part of an entity doctype.entities.each_value do |entity| - copy = copy.gsub( entity.value, - "&#{entity.name};" ) if entity.value and + copy = copy.gsub( entity.value, + "&#{entity.name};" ) if entity.value and not( entity_filter and entity_filter.include?(entity) ) end else diff --git a/lib/rexml/validation/relaxng.rb b/lib/rexml/validation/relaxng.rb index 2b863710b4..2441901d7b 100644 --- a/lib/rexml/validation/relaxng.rb +++ b/lib/rexml/validation/relaxng.rb @@ -79,7 +79,7 @@ module REXML when "mixed" states << Interleave.new( self ) states[-2] << states[-1] - states[-1] << TEXT + states[-1] << TEXT when "define" states << [ event[2]["name"] ] when "ref" @@ -102,7 +102,7 @@ module REXML case event[1] when "element", "attribute" states[-1] << event - when "zeroOrMore", "oneOrMore", "choice", "optional", + when "zeroOrMore", "oneOrMore", "choice", "optional", "interleave", "group", "mixed" states.pop when "define" @@ -139,7 +139,7 @@ module REXML @events.each {|s| s.reset if s.kind_of? State } end - def previous=( previous ) + def previous=( previous ) @previous << previous end @@ -183,7 +183,7 @@ module REXML end def inspect - "< #{to_s} #{@events.collect{|e| + "< #{to_s} #{@events.collect{|e| pre = e == @events[@current] ? '#' : '' pre + e.inspect unless self == e }.join(', ')} >" @@ -201,15 +201,15 @@ module REXML protected def expand_ref_in( arry, ind ) new_events = [] - @references[ arry[ind].to_s ].each{ |evt| + @references[ arry[ind].to_s ].each{ |evt| add_event_to_arry(new_events,evt) } arry[ind,1] = new_events end - def add_event_to_arry( arry, evt ) + def add_event_to_arry( arry, evt ) evt = generate_event( evt ) - if evt.kind_of? String + if evt.kind_of? String arry[-1].event_arg = evt if arry[-1].kind_of? Event and @value @value = false else @@ -272,7 +272,7 @@ module REXML end def matches?(event) - @events[@current].matches?(event) || + @events[@current].matches?(event) || (@current == 0 and @previous[-1].matches?(event)) end @@ -319,7 +319,7 @@ module REXML end def reset - super + super @ord = 0 end @@ -345,7 +345,7 @@ module REXML end def matches?( event ) - @events[@current].matches?(event) || + @events[@current].matches?(event) || (@current == 0 and @ord > 0 and @previous[-1].matches?(event)) end @@ -412,7 +412,7 @@ module REXML #puts "IN CHOICE EXPECTED" #puts "EVENTS = #{@events.inspect}" return [@events[@current]] if @events.size > 0 - return @choices.collect do |x| + return @choices.collect do |x| if x[0].kind_of? State x[0].expected else @@ -426,12 +426,12 @@ module REXML end protected - def add_event_to_arry( arry, evt ) + def add_event_to_arry( arry, evt ) if evt.kind_of? State or evt.class == Ref arry << [evt] - elsif evt[0] == :text + elsif evt[0] == :text if arry[-1] and - arry[-1][-1].kind_of?( Event ) and + arry[-1][-1].kind_of?( Event ) and arry[-1][-1].event_type == :text and @value arry[-1][-1].event_arg = evt[1] @@ -478,7 +478,7 @@ module REXML @choices[idx] = old @choice += 1 end - + #puts "In next with #{event.inspect}." #puts "events is #{@events.inspect}" @events = [] unless @events @@ -490,7 +490,7 @@ module REXML next_current(event) unless @events[@current] return nil unless @events[@current] - expand_ref_in( @events, @current ) if @events[@current].class == Ref + 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 ) @@ -530,7 +530,7 @@ module REXML #puts "IN CHOICE EXPECTED" #puts "EVENTS = #{@events.inspect}" return [@events[@current]] if @events[@current] - return @choices[@choice..-1].collect do |x| + return @choices[@choice..-1].collect do |x| if x[0].kind_of? State x[0].expected else diff --git a/lib/rexml/validation/validation.rb b/lib/rexml/validation/validation.rb index 93f5bfb329..f0ffa78912 100644 --- a/lib/rexml/validation/validation.rb +++ b/lib/rexml/validation/validation.rb @@ -14,7 +14,7 @@ module REXML def dump puts @root.inspect end - def validate( event ) + def validate( event ) #puts "Current: #@current" #puts "Event: #{event.inspect}" @attr_stack = [] unless defined? @attr_stack @@ -33,12 +33,12 @@ module REXML sattr = [:start_attribute, nil] eattr = [:end_attribute] text = [:text, nil] - k,v = event[2].find { |key,value| + k,v = event[2].find { |key,value| sattr[1] = key #puts "Looking for #{sattr.inspect}" m = @current.next( sattr ) #puts "Got #{m.inspect}" - if m + if m # If the state has text children... #puts "Looking for #{eattr.inspect}" #puts "Expect #{m.expected}" diff --git a/lib/rexml/xpath.rb b/lib/rexml/xpath.rb index b22969ec8c..5f7ecefe29 100644 --- a/lib/rexml/xpath.rb +++ b/lib/rexml/xpath.rb @@ -64,7 +64,7 @@ module REXML parser.parse(path, element).each( &block ) end - # Returns an array of nodes matching a given XPath. + # Returns an array of nodes matching a given XPath. def XPath::match element, path=nil, namespaces=nil, variables={} parser = XPathParser.new parser.namespaces = namespaces diff --git a/lib/rexml/xpath_parser.rb b/lib/rexml/xpath_parser.rb index ead5adaf7f..11950ecd93 100644 --- a/lib/rexml/xpath_parser.rb +++ b/lib/rexml/xpath_parser.rb @@ -88,7 +88,7 @@ module REXML case path[0] when :document - # do nothing + # do nothing return first( path[1..-1], node ) when :child for c in node.children @@ -123,7 +123,7 @@ module REXML end - def match( path_stack, nodeset ) + def match( path_stack, nodeset ) #puts "MATCH: path_stack = #{path_stack.inspect}" #puts "MATCH: nodeset = #{nodeset.inspect}" r = expr( path_stack, nodeset ) @@ -136,7 +136,7 @@ module REXML # Returns a String namespace for a node, given a prefix # The rules are: - # + # # 1. Use the supplied namespace mapping first. # 2. If no mapping was supplied, use the context node to look up the namespace def get_namespace( node, prefix ) @@ -187,8 +187,8 @@ module REXML #puts "node.namespace == #{ns.inspect} => #{node.namespace == ns}" end end - !(node.node_type == :element and - node.name == name and + !(node.node_type == :element and + node.name == name and node.namespace == ns ) end node_types = ELEMENTS @@ -205,7 +205,7 @@ module REXML when :processing_instruction target = path_stack.shift nodeset.delete_if do |node| - (node.node_type != :processing_instruction) or + (node.node_type != :processing_instruction) or ( target!='' and ( node.target != target ) ) end @@ -231,7 +231,7 @@ module REXML when :literal return path_stack.shift - + when :attribute new_nodeset = [] case path_stack.shift @@ -481,23 +481,23 @@ module REXML when :function func_name = path_stack.shift.tr('-','_') arguments = path_stack.shift - #puts "FUNCTION 0: #{func_name}(#{arguments.collect{|a|a.inspect}.join(', ')})" + #puts "FUNCTION 0: #{func_name}(#{arguments.collect{|a|a.inspect}.join(', ')})" subcontext = context ? nil : { :size => nodeset.size } res = [] cont = context - nodeset.each_with_index { |n, i| + nodeset.each_with_index { |n, i| if subcontext subcontext[:node] = n subcontext[:index] = i cont = subcontext end arg_clone = arguments.dclone - args = arg_clone.collect { |arg| + args = arg_clone.collect { |arg| #puts "FUNCTION 1: Calling expr( #{arg.inspect}, [#{n.inspect}] )" - expr( arg, [n], cont ) + expr( arg, [n], cont ) } - #puts "FUNCTION 2: #{func_name}(#{args.collect{|a|a.inspect}.join(', ')})" + #puts "FUNCTION 2: #{func_name}(#{args.collect{|a|a.inspect}.join(', ')})" Functions.context = cont res << Functions.send( func_name, *args ) #puts "FUNCTION 3: #{res[-1].inspect}" @@ -515,10 +515,10 @@ module REXML # FIXME # The next two methods are BAD MOJO! # This is my achilles heel. If anybody thinks of a better - # way of doing this, be my guest. This really sucks, but + # way of doing this, be my guest. This really sucks, but # it is a wonder it works at all. # ######################################################## - + def descendant_or_self( path_stack, nodeset ) rs = [] #puts "#"*80 @@ -547,7 +547,7 @@ module REXML # Reorders an array of nodes so that they are in document order # It tries to do this efficiently. # - # FIXME: I need to get rid of this, but the issue is that most of the XPath + # FIXME: I need to get rid of this, but the issue is that most of the XPath # interpreter functions as a filter, which means that we lose context going # in and out of function calls. If I knew what the index of the nodes was, # I wouldn't have to do this. Maybe add a document IDX for each node? @@ -555,7 +555,7 @@ module REXML def document_order( array_of_nodes ) new_arry = [] array_of_nodes.each { |node| - node_idx = [] + node_idx = [] np = node.node_type == :attribute ? node.element : node while np.parent and np.parent.node_type == :element node_idx << np.parent.index( np ) @@ -579,7 +579,7 @@ module REXML # Builds a nodeset of all of the preceding nodes of the supplied node, # in reverse document order - # preceding:: includes every element in the document that precedes this node, + # preceding:: includes every element in the document that precedes this node, # except for ancestors def preceding( node ) #puts "IN PRECEDING" @@ -609,9 +609,9 @@ module REXML #puts "NODE: #{node.inspect}" #puts "PREVIOUS NODE: #{node.previous_sibling_node.inspect}" #puts "PARENT NODE: #{node.parent}" - psn = node.previous_sibling_node + psn = node.previous_sibling_node if psn.nil? - if node.parent.nil? or node.parent.class == Document + if node.parent.nil? or node.parent.class == Document return nil end return node.parent @@ -647,9 +647,9 @@ module REXML end def next_sibling_node(node) - psn = node.next_sibling_node + psn = node.next_sibling_node while psn.nil? - if node.parent.nil? or node.parent.class == Document + if node.parent.nil? or node.parent.class == Document return nil end node = node.parent diff --git a/lib/rinda/rinda.rb b/lib/rinda/rinda.rb index 6c59e68654..18e284a544 100644 --- a/lib/rinda/rinda.rb +++ b/lib/rinda/rinda.rb @@ -58,7 +58,7 @@ module Rinda ## # The number of elements in the tuple. - + def size @tuple.size end @@ -162,7 +162,7 @@ module Rinda end return true end - + ## # Alias for #match. @@ -171,7 +171,7 @@ module Rinda end end - + ## # <i>Documentation?</i> @@ -184,7 +184,7 @@ module Rinda @drb_uri = uri @drb_ref = ref end - + ## # This DRbObjectTemplate matches +ro+ if the remote object's drburi and # drbref are the same. +nil+ is used as a wildcard. @@ -213,14 +213,14 @@ module Rinda def initialize(ts) @ts = ts end - + ## # Adds +tuple+ to the proxied TupleSpace. See TupleSpace#write. def write(tuple, sec=nil) @ts.write(tuple, sec) end - + ## # Takes +tuple+ from the proxied TupleSpace. See TupleSpace#take. @@ -229,14 +229,14 @@ module Rinda @ts.move(DRbObject.new(port), tuple, sec, &block) port[0] end - + ## # Reads +tuple+ from the proxied TupleSpace. See TupleSpace#read. def read(tuple, sec=nil, &block) @ts.read(tuple, sec, &block) end - + ## # Reads all tuples matching +tuple+ from the proxied TupleSpace. See # TupleSpace#read_all. @@ -244,7 +244,7 @@ module Rinda def read_all(tuple) @ts.read_all(tuple) end - + ## # Registers for notifications of event +ev+ on the proxied TupleSpace. # See TupleSpace#notify diff --git a/lib/rinda/ring.rb b/lib/rinda/ring.rb index 4dc7c7d79a..b25fd99856 100644 --- a/lib/rinda/ring.rb +++ b/lib/rinda/ring.rb @@ -49,7 +49,7 @@ module Rinda end end end - + ## # Extracts the response URI from +msg+ and adds it to TupleSpace where it # will be picked up by +reply_service+ for notification. @@ -74,7 +74,7 @@ module Rinda end end end - + ## # Pulls lookup tuples out of the TupleSpace and sends their DRb object the # address of the local TupleSpace. @@ -104,7 +104,7 @@ module Rinda # created RingFinger. def self.finger - unless @@finger + unless @@finger @@finger = self.new @@finger.lookup_ring_any end @@ -207,7 +207,7 @@ module Rinda @rings.push(it) end end - + @primary = queue.pop raise('RingNotFound') if @primary.nil? @primary diff --git a/lib/rinda/tuplespace.rb b/lib/rinda/tuplespace.rb index 6ca30a7b4b..113aa0de15 100644 --- a/lib/rinda/tuplespace.rb +++ b/lib/rinda/tuplespace.rb @@ -73,14 +73,14 @@ module Rinda end ## - # Reset the expiry time according to +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. + # which will reset its expiry time. def renew(sec_or_renewer) sec, @renewer = get_renewer(sec_or_renewer) @@ -168,7 +168,7 @@ module Rinda def match(tuple) @tuple.match(tuple) end - + alias === match def make_tuple(ary) # :nodoc: @@ -224,11 +224,11 @@ module Rinda # # 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: @@ -276,7 +276,7 @@ module Rinda it = pop yield(it) end - rescue + rescue ensure cancel end @@ -295,16 +295,16 @@ module Rinda def initialize @bin = [] end - + def add(tuple) @bin.push(tuple) end - + def delete(tuple) idx = @bin.rindex(tuple) @bin.delete_at(idx) if idx end - + def find(&blk) @bin.reverse_each do |x| return x if yield(x) diff --git a/lib/rss/0.9.rb b/lib/rss/0.9.rb index 7b24e7596d..37dc7af94e 100644 --- a/lib/rss/0.9.rb +++ b/lib/rss/0.9.rb @@ -8,7 +8,7 @@ module RSS def self.append_features(klass) super - + klass.install_must_call_validator('', "") end end @@ -123,7 +123,7 @@ module RSS def not_need_to_call_setup_maker_variables %w(image textInput) end - + class SkipDays < Element include RSS09 @@ -146,11 +146,11 @@ module RSS self.content = args[0] end end - + end - + end - + class SkipHours < Element include RSS09 @@ -174,13 +174,13 @@ module RSS end end end - + end - + class Image < Element include RSS09 - + %w(url title link).each do |name| install_text_element(name, "", nil) end @@ -239,9 +239,9 @@ module RSS end end end - + class Item < Element - + include RSS09 [ @@ -269,7 +269,7 @@ module RSS @enclosure.setup_maker(item) if @enclosure @source.setup_maker(item) if @source end - + class Source < Element include RSS09 @@ -279,7 +279,7 @@ module RSS ].each do |name, uri, required| install_get_attribute(name, uri, required) end - + content_setup def initialize(*args) @@ -341,7 +341,7 @@ module RSS class Category < Element include RSS09 - + [ ["domain", "", false] ].each do |name, uri, required| @@ -369,11 +369,11 @@ module RSS category.domain = domain category.content = content end - + end end - + class TextInput < Element include RSS09 @@ -399,9 +399,9 @@ module RSS maker.textinput end end - + end - + end RSS09::ELEMENTS.each do |name| @@ -412,7 +412,7 @@ module RSS private def initial_start_rss(tag_name, prefix, attrs, ns) check_ns(tag_name, prefix, ns, "") - + @rss = Rss.new(attrs['version'], @version, @encoding, @standalone) @rss.do_validate = @do_validate @rss.xml_stylesheets = @xml_stylesheets @@ -422,7 +422,7 @@ module RSS end @proc_stack.push(pr) end - + end end diff --git a/lib/rss/1.0.rb b/lib/rss/1.0.rb index f04e61c5eb..f2f89739b6 100644 --- a/lib/rss/1.0.rb +++ b/lib/rss/1.0.rb @@ -8,7 +8,7 @@ module RSS def self.append_features(klass) super - + klass.install_must_call_validator('', ::RSS::URI) end @@ -64,13 +64,13 @@ module RSS URI end end - + [ ["resource", [URI, ""], true] ].each do |name, uri, required| install_get_attribute(name, uri, required) end - + def initialize(*args) if Utils.element_initialize_arguments?(args) super @@ -98,10 +98,10 @@ module RSS end @tag_name = 'Seq' - + install_have_children_element("li", URI, "*") install_must_call_validator('rdf', ::RSS::RDF::URI) - + def initialize(*args) if Utils.element_initialize_arguments?(args) super @@ -114,7 +114,7 @@ module RSS def full_name tag_name_with_prefix(PREFIX) end - + def setup_maker(target) lis.each do |li| target << li.resource @@ -135,10 +135,10 @@ module RSS end @tag_name = 'Bag' - + install_have_children_element("li", URI, "*") install_must_call_validator('rdf', URI) - + def initialize(*args) if Utils.element_initialize_arguments?(args) super @@ -151,7 +151,7 @@ module RSS def full_name tag_name_with_prefix(PREFIX) end - + def setup_maker(target) lis.each do |li| target << li.resource @@ -162,7 +162,7 @@ module RSS class Channel < Element include RSS10 - + class << self def required_uri @@ -202,17 +202,17 @@ module RSS def maker_target(maker) maker.channel end - + def setup_maker_attributes(channel) channel.about = about end class Image < Element - + include RSS10 class << self - + def required_uri ::RSS::URI end @@ -225,7 +225,7 @@ module RSS install_get_attribute(name, uri, required, nil, nil, "#{PREFIX}:#{name}") end - + def initialize(*args) if Utils.element_initialize_arguments?(args) super @@ -237,11 +237,11 @@ module RSS end class Textinput < Element - + include RSS10 class << self - + def required_uri ::RSS::URI end @@ -254,7 +254,7 @@ module RSS install_get_attribute(name, uri, required, nil, nil, "#{PREFIX}:#{name}") end - + def initialize(*args) if Utils.element_initialize_arguments?(args) super @@ -264,7 +264,7 @@ module RSS end end end - + class Items < Element include RSS10 @@ -272,16 +272,16 @@ module RSS Seq = ::RSS::RDF::Seq class << self - + def required_uri ::RSS::URI end - + end install_have_child_element("Seq", URI, nil) install_must_call_validator('rdf', URI) - + def initialize(*args) if Utils.element_initialize_arguments?(args) super @@ -309,7 +309,7 @@ module RSS include RSS10 class << self - + def required_uri ::RSS::URI end @@ -351,7 +351,7 @@ module RSS def required_uri ::RSS::URI end - + end diff --git a/lib/rss/2.0.rb b/lib/rss/2.0.rb index 3798da4eb7..9622c598d9 100644 --- a/lib/rss/2.0.rb +++ b/lib/rss/2.0.rb @@ -29,7 +29,7 @@ module RSS Category = Item::Category class Item - + [ ["comments", "?"], ["author", "?"], @@ -57,9 +57,9 @@ module RSS _setup_maker_element(item) @guid.setup_maker(item) if @guid end - + class Guid < Element - + include RSS09 [ diff --git a/lib/rss/converter.rb b/lib/rss/converter.rb index 745d6de965..3e79eba4fb 100644 --- a/lib/rss/converter.rb +++ b/lib/rss/converter.rb @@ -3,7 +3,7 @@ require "rss/utils" module RSS class Converter - + include Utils def initialize(to_enc, from_enc=nil) @@ -63,11 +63,11 @@ module RSS raise UnknownConversionMethodError.new(to_enc, from_enc) end end - + def def_else_enc(to_enc, from_enc) def_iconv_convert(to_enc, from_enc, 0) end - + def def_same_enc() def_convert do |value| value @@ -101,40 +101,40 @@ module RSS def def_to_euc_jp_from_utf_8 def_uconv_convert_if_can('u8toeuc', 'EUC-JP', 'UTF-8', '-We') end - + def def_to_utf_8_from_euc_jp def_uconv_convert_if_can('euctou8', 'UTF-8', 'EUC-JP', '-Ew') end - + def def_to_shift_jis_from_utf_8 def_uconv_convert_if_can('u8tosjis', 'Shift_JIS', 'UTF-8', '-Ws') end - + def def_to_utf_8_from_shift_jis def_uconv_convert_if_can('sjistou8', 'UTF-8', 'Shift_JIS', '-Sw') end - + def def_to_euc_jp_from_shift_jis require "nkf" def_convert do |value| "NKF.nkf('-Se', #{value})" end end - + def def_to_shift_jis_from_euc_jp require "nkf" def_convert do |value| "NKF.nkf('-Es', #{value})" end end - + def def_to_euc_jp_from_iso_2022_jp require "nkf" def_convert do |value| "NKF.nkf('-Je', #{value})" end end - + def def_to_iso_2022_jp_from_euc_jp require "nkf" def_convert do |value| @@ -147,7 +147,7 @@ module RSS "#{value}.unpack('C*').pack('U*')" end end - + def def_to_iso_8859_1_from_utf_8 def_convert do |value| <<-EOC @@ -164,7 +164,7 @@ module RSS EOC end end - + end - + end diff --git a/lib/rss/dublincore.rb b/lib/rss/dublincore.rb index 7ba239f8f1..53a4ca70d6 100644 --- a/lib/rss/dublincore.rb +++ b/lib/rss/dublincore.rb @@ -25,7 +25,7 @@ module RSS def #{full_name} @#{full_name}.first and @#{full_name}.first.value end - + def #{full_name}=(new_value) @#{full_name}[0] = Utils.new_with_value_if_need(#{klass_name}, new_value) end @@ -50,7 +50,7 @@ module RSS EOC end end - + module DublinCoreModel extend BaseModel @@ -76,26 +76,26 @@ module RSS DATE_ELEMENTS = { "date" => "w3cdtf", } - + ELEMENT_NAME_INFOS = DublinCoreModel::TEXT_ELEMENTS.to_a DublinCoreModel::DATE_ELEMENTS.each do |name, | ELEMENT_NAME_INFOS << [name, nil] end - + ELEMENTS = TEXT_ELEMENTS.keys + DATE_ELEMENTS.keys ELEMENTS.each do |name, plural_name| module_eval(<<-EOC, *get_file_and_line_from_caller(0)) class DublinCore#{Utils.to_class_name(name)} < Element include RSS10 - + content_setup class << self def required_prefix DC_PREFIX end - + def required_uri DC_URI end @@ -105,7 +105,7 @@ module RSS alias_method(:value, :content) alias_method(:value=, :content=) - + def initialize(*args) if Utils.element_initialize_arguments?(args) super @@ -114,7 +114,7 @@ module RSS self.content = args[0] end end - + def full_name tag_name_with_prefix(DC_PREFIX) end diff --git a/lib/rss/image.rb b/lib/rss/image.rb index c4714aea12..e79e9f5e65 100644 --- a/lib/rss/image.rb +++ b/lib/rss/image.rb @@ -15,7 +15,7 @@ module RSS BaseListener.install_class_name(IMAGE_URI, name, "Image#{class_name}") IMAGE_ELEMENTS << "#{IMAGE_PREFIX}_#{name}" end - + module ImageModelUtils def validate_one_tag_name(ignore_unknown_element, name, tags) if !ignore_unknown_element @@ -25,7 +25,7 @@ module RSS raise TooMuchTagError.new(name, tag_name) if tags.size > 1 end end - + module ImageItemModel include ImageModelUtils extend BaseModel @@ -43,12 +43,12 @@ module RSS include DublinCoreModel @tag_name = "item" - + class << self def required_prefix IMAGE_PREFIX end - + def required_uri IMAGE_URI end @@ -102,11 +102,11 @@ module RSS end end end - + module ImageFaviconModel include ImageModelUtils extend BaseModel - + def self.append_features(klass) super @@ -122,12 +122,12 @@ module RSS include DublinCoreModel @tag_name = "favicon" - + class << self def required_prefix IMAGE_PREFIX end - + def required_uri IMAGE_URI end @@ -154,7 +154,7 @@ module RSS end set_size(new_value) end - + alias image_size= size= alias image_size size diff --git a/lib/rss/maker/0.9.rb b/lib/rss/maker/0.9.rb index cc7db8c638..ed992028cf 100644 --- a/lib/rss/maker/0.9.rb +++ b/lib/rss/maker/0.9.rb @@ -4,14 +4,14 @@ require "rss/maker/base" module RSS module Maker - + class RSS09 < RSSBase - + def initialize(feed_version) super @feed_type = "rss" end - + private def make_feed Rss.new(@feed_version, @version, @encoding, @standalone) @@ -38,20 +38,20 @@ module RSS raise NotSetError.new("maker.channel", _not_set_required_variables) end end - + private def setup_items(rss) @maker.items.to_feed(rss) end - + def setup_image(rss) @maker.image.to_feed(rss) end - + def setup_textinput(rss) @maker.textinput.to_feed(rss) end - + def variables super + ["pubDate"] end @@ -78,7 +78,7 @@ module RSS end end end - + class Day < DayBase def to_feed(rss, days) day = Rss::Channel::SkipDays::Day.new @@ -96,7 +96,7 @@ module RSS end end end - + class SkipHours < SkipHoursBase def to_feed(rss, channel) unless @hours.empty? @@ -108,7 +108,7 @@ module RSS end end end - + class Hour < HourBase def to_feed(rss, hours) hour = Rss::Channel::SkipHours::Hour.new @@ -126,7 +126,7 @@ module RSS end end end - + class Cloud < CloudBase def to_feed(*args) end @@ -243,7 +243,7 @@ module RSS true end end - + class Items < ItemsBase def to_feed(rss) if rss.channel @@ -253,7 +253,7 @@ module RSS setup_other_elements(rss, rss.items) end end - + class Item < ItemBase def to_feed(rss) item = Rss::Channel::Item.new @@ -439,7 +439,7 @@ module RSS end end end - + class Textinput < TextinputBase def to_feed(rss) textInput = Rss::Channel::TextInput.new diff --git a/lib/rss/maker/1.0.rb b/lib/rss/maker/1.0.rb index a1e2594f70..676f662915 100644 --- a/lib/rss/maker/1.0.rb +++ b/lib/rss/maker/1.0.rb @@ -60,7 +60,7 @@ module RSS rss.channel.items = items set_parent(rss.channel, items) end - + def setup_image(rss) if @maker.image.have_required_values? image = RDF::Channel::Image.new(@maker.image.url) @@ -91,11 +91,11 @@ module RSS class SkipDays < SkipDaysBase def to_feed(*args) end - + class Day < DayBase end end - + class SkipHours < SkipHoursBase def to_feed(*args) end @@ -103,7 +103,7 @@ module RSS class Hour < HourBase end end - + class Cloud < CloudBase def to_feed(*args) end @@ -403,7 +403,7 @@ module RSS end end end - + class Textinput < TextinputBase def to_feed(rss) if @link diff --git a/lib/rss/maker/2.0.rb b/lib/rss/maker/2.0.rb index 67d68126ac..15b1349c2a 100644 --- a/lib/rss/maker/2.0.rb +++ b/lib/rss/maker/2.0.rb @@ -4,9 +4,9 @@ require "rss/maker/0.9" module RSS module Maker - + class RSS20 < RSS09 - + def initialize(feed_version="2.0") super end @@ -17,17 +17,17 @@ module RSS def required_variable_names %w(link) end - + class SkipDays < RSS09::Channel::SkipDays class Day < RSS09::Channel::SkipDays::Day end end - + class SkipHours < RSS09::Channel::SkipHours class Hour < RSS09::Channel::SkipHours::Hour end end - + class Cloud < RSS09::Channel::Cloud def to_feed(rss, channel) cloud = Rss::Channel::Cloud.new @@ -51,7 +51,7 @@ module RSS category.to_feed(rss, channel) end end - + class Category < RSS09::Channel::Categories::Category def to_feed(rss, channel) category = Rss::Channel::Category.new @@ -81,14 +81,14 @@ module RSS end end end - + class Image < RSS09::Image private def required_element? false end end - + class Items < RSS09::Items class Item < RSS09::Items::Item private @@ -179,7 +179,7 @@ module RSS category.to_feed(rss, item) end end - + class Category < RSS09::Items::Item::Categories::Category def to_feed(rss, item) category = Rss::Channel::Item::Category.new @@ -212,11 +212,11 @@ module RSS end end end - + class Textinput < RSS09::Textinput end end - + add_maker("2.0", "2.0", RSS20) add_maker("rss2.0", "2.0", RSS20) end diff --git a/lib/rss/maker/base.rb b/lib/rss/maker/base.rb index 3a7d255ae9..615088f8f7 100644 --- a/lib/rss/maker/base.rb +++ b/lib/rss/maker/base.rb @@ -395,7 +395,7 @@ module RSS end EOC end - + attr_reader :feed_version alias_method(:rss_version, :feed_version) attr_accessor :version, :encoding, :standalone @@ -409,7 +409,7 @@ module RSS @encoding = "UTF-8" @standalone = nil end - + def make yield(self) to_feed @@ -423,7 +423,7 @@ module RSS feed.validate feed end - + private remove_method :make_xml_stylesheets def make_xml_stylesheets @@ -440,7 +440,7 @@ module RSS attr_accessor attribute add_need_initialize_variable(attribute) end - + def to_feed(feed) xss = ::RSS::XMLStyleSheet.new guess_type_if_need(xss) @@ -463,7 +463,7 @@ module RSS end end end - + class ChannelBase < Base include SetupDefaultDate @@ -538,7 +538,7 @@ module RSS end end end - + class SkipHoursBase < Base def_array_element("hour") @@ -549,7 +549,7 @@ module RSS end end end - + class CloudBase < Base %w(domain port path registerProcedure protocol).each do |element| attr_accessor element @@ -619,7 +619,7 @@ module RSS include AtomTextConstructBase end end - + class ImageBase < Base %w(title url width height description).each do |element| attr_accessor element @@ -630,18 +630,18 @@ module RSS @maker.channel.link end end - + class ItemsBase < Base def_array_element("item") attr_accessor :do_sort, :max_size - + def initialize(maker) super @do_sort = false @max_size = -1 end - + def normalize if @max_size >= 0 sort_if_need[0...@max_size] diff --git a/lib/rss/maker/dublincore.rb b/lib/rss/maker/dublincore.rb index ff4813fe19..9069c27d06 100644 --- a/lib/rss/maker/dublincore.rb +++ b/lib/rss/maker/dublincore.rb @@ -90,7 +90,7 @@ EOC class ChannelBase include DublinCoreModel end - + class ImageBase; include DublinCoreModel; end class ItemsBase class ItemBase diff --git a/lib/rss/maker/image.rb b/lib/rss/maker/image.rb index b95cf4c714..e2b36e0a08 100644 --- a/lib/rss/maker/image.rb +++ b/lib/rss/maker/image.rb @@ -89,7 +89,7 @@ EOC end class ChannelBase; include Maker::ImageFaviconModel; end - + class ItemsBase class ItemBase; include Maker::ImageItemModel; end end diff --git a/lib/rss/maker/taxonomy.rb b/lib/rss/maker/taxonomy.rb index 211603840f..13ae9aa805 100644 --- a/lib/rss/maker/taxonomy.rb +++ b/lib/rss/maker/taxonomy.rb @@ -72,12 +72,12 @@ EOC class TaxonomyTopicBase < Base include DublinCoreModel include TaxonomyTopicsModel - + attr_accessor :value add_need_initialize_variable("value") alias_method(:taxo_link, :value) alias_method(:taxo_link=, :value=) - + def have_required_values? @value end @@ -88,11 +88,11 @@ EOC class RSSBase include TaxonomyTopicModel end - + class ChannelBase include TaxonomyTopicsModel end - + class ItemsBase class ItemBase include TaxonomyTopicsModel diff --git a/lib/rss/maker/trackback.rb b/lib/rss/maker/trackback.rb index 278fe53ebe..00f001cb85 100644 --- a/lib/rss/maker/trackback.rb +++ b/lib/rss/maker/trackback.rb @@ -19,7 +19,7 @@ module RSS class TrackBackAboutBase < Base attr_accessor :value add_need_initialize_variable("value") - + alias_method(:resource, :value) alias_method(:resource=, :value=) alias_method(:content, :value) diff --git a/lib/rss/parser.rb b/lib/rss/parser.rb index 9b28f0fa8a..225e07d504 100644 --- a/lib/rss/parser.rb +++ b/lib/rss/parser.rb @@ -98,7 +98,7 @@ module RSS return rss if maybe_xml?(rss) uri = to_uri(rss) - + if uri.respond_to?(:read) uri.read elsif !rss.tainted? and File.readable?(rss) @@ -133,7 +133,7 @@ module RSS listener.raise_for_undefined_entity? end end - + def initialize(rss) @listener = self.class.listener.new @rss = rss @@ -196,13 +196,13 @@ module RSS def available_tags(uri) (@@accessor_bases[uri] || {}).keys end - + # register uri against this name. def register_uri(uri, name) @@registered_uris[name] ||= {} @@registered_uris[name][uri] = nil end - + # test if this uri is registered against this name def uri_registered?(uri, name) @@registered_uris[name].has_key?(uri) @@ -228,11 +228,11 @@ module RSS install_accessor_base(uri, name, accessor_base) def_get_text_element(uri, name, *get_file_and_line_from_caller(1)) end - + def raise_for_undefined_entity? true end - + private # set the accessor for the uri, tag_name pair def install_accessor_base(uri, tag_name, accessor_base) @@ -279,7 +279,7 @@ module RSS @xml_element = nil @last_xml_element = nil end - + # set instance vars for version, encoding, standalone def xmldecl(version, encoding, standalone) @version, @encoding, @standalone = version, encoding, standalone diff --git a/lib/rss/rexmlparser.rb b/lib/rss/rexmlparser.rb index 4dabf59199..7112ac3669 100644 --- a/lib/rss/rexmlparser.rb +++ b/lib/rss/rexmlparser.rb @@ -7,7 +7,7 @@ if ([$1.to_i, $2.to_i] <=> [2, 5]) < 0 end module RSS - + class REXMLParser < BaseParser class << self @@ -15,7 +15,7 @@ module RSS REXMLListener end end - + private def _parse begin @@ -28,9 +28,9 @@ module RSS raise NotWellFormedError.new(line){e.message} end end - + end - + class REXMLListener < BaseListener include REXML::StreamListener @@ -41,7 +41,7 @@ module RSS false end end - + def xmldecl(version, encoding, standalone) super(version, encoding, standalone == "yes") # Encoding is converted to UTF-8 when REXML parse XML. diff --git a/lib/rss/rss.rb b/lib/rss/rss.rb index 4b943ec55b..d1f6181a47 100644 --- a/lib/rss/rss.rb +++ b/lib/rss/rss.rb @@ -249,7 +249,7 @@ EOC # accessor convert_attr_reader name date_writer(name, type, disp_name) - + install_element(name) do |n, elem_name| <<-EOC if @#{n} @@ -634,7 +634,7 @@ EOC include SetupMaker INDENT = " " - + MUST_CALL_VALIDATORS = {} MODELS = [] GET_ATTRIBUTES = [] @@ -830,7 +830,7 @@ EOC def full_name tag_name end - + def converter=(converter) @converter = converter targets = children.dup @@ -865,7 +865,7 @@ EOC ensure @do_validate = do_validate end - + def validate_for_stream(tags, ignore_unknown_element=true) validate_attribute __validate(ignore_unknown_element, tags, false) @@ -985,7 +985,7 @@ EOC end_tag = "\n#{indent}</#{full_name}>" end end - + start_tag + content.join("\n") + end_tag end @@ -1010,7 +1010,7 @@ EOC end attrs end - + def tag_name_with_prefix(prefix) "#{prefix}:#{tag_name}" end @@ -1210,7 +1210,7 @@ EOC module RootElementMixin include XMLStyleSheetMixin - + attr_reader :output_encoding attr_reader :feed_type, :feed_subtype, :feed_version attr_accessor :version, :encoding, :standalone @@ -1296,7 +1296,7 @@ EOC rv << "?>\n" rv end - + def ns_declarations decls = {} self.class::NSPOOL.collect do |prefix, uri| diff --git a/lib/rss/syndication.rb b/lib/rss/syndication.rb index 3eb15429f6..c375645dd6 100644 --- a/lib/rss/syndication.rb +++ b/lib/rss/syndication.rb @@ -8,11 +8,11 @@ module RSS RDF.install_ns(SY_PREFIX, SY_URI) module SyndicationModel - + extend BaseModel - + ELEMENTS = [] - + def self.append_features(klass) super diff --git a/lib/rss/taxonomy.rb b/lib/rss/taxonomy.rb index 276f63b05d..b82e55dacc 100644 --- a/lib/rss/taxonomy.rb +++ b/lib/rss/taxonomy.rb @@ -24,7 +24,7 @@ module RSS module TaxonomyTopicsModel extend BaseModel - + def self.append_features(klass) super @@ -37,21 +37,21 @@ module RSS class TaxonomyTopics < Element include RSS10 - + Bag = ::RSS::RDF::Bag class << self def required_prefix TAXO_PREFIX end - + def required_uri TAXO_URI end end @tag_name = "topics" - + install_have_child_element("Bag", RDF::URI, nil) install_must_call_validator('rdf', RDF::URI) @@ -84,10 +84,10 @@ module RSS end end end - + module TaxonomyTopicModel extend BaseModel - + def self.append_features(klass) super var_name = "#{TAXO_PREFIX}_topic" @@ -99,12 +99,12 @@ module RSS include DublinCoreModel include TaxonomyTopicsModel - + class << self def required_prefix TAXO_PREFIX end - + def required_uri TAXO_URI end @@ -115,7 +115,7 @@ module RSS install_get_attribute("about", ::RSS::RDF::URI, true, nil, nil, "#{RDF::PREFIX}:about") install_text_element("link", TAXO_URI, "?", "#{TAXO_PREFIX}_link") - + def initialize(*args) if Utils.element_initialize_arguments?(args) super diff --git a/lib/rss/trackback.rb b/lib/rss/trackback.rb index ee2491f332..59fedb5f3e 100644 --- a/lib/rss/trackback.rb +++ b/lib/rss/trackback.rb @@ -23,7 +23,7 @@ module RSS module BaseTrackBackModel ELEMENTS = %w(ping about) - + def append_features(klass) super @@ -47,7 +47,7 @@ module RSS end EOC end - + [%w(about s)].each do |name, postfix| var_name = "#{TRACKBACK_PREFIX}_#{name}" klass_name = "TrackBack#{Utils.to_class_name(name)}" @@ -105,7 +105,7 @@ module RSS def required_prefix TRACKBACK_PREFIX end - + def required_uri TRACKBACK_URI end @@ -141,17 +141,17 @@ module RSS include RSS10 class << self - + def required_prefix TRACKBACK_PREFIX end - + def required_uri TRACKBACK_URI end end - + @tag_name = "about" [ @@ -163,7 +163,7 @@ module RSS alias_method(:value, :resource) alias_method(:value=, :resource=) - + def initialize(*args) if Utils.element_initialize_arguments?(args) super @@ -185,7 +185,7 @@ module RSS def setup_maker_attributes(about) about.resource = self.resource end - + end end @@ -197,7 +197,7 @@ module RSS include RSS09 @tag_name = "ping" - + content_setup class << self @@ -205,13 +205,13 @@ module RSS def required_prefix TRACKBACK_PREFIX end - + def required_uri TRACKBACK_URI end end - + alias_method(:value, :content) alias_method(:value=, :content=) @@ -223,26 +223,26 @@ module RSS self.content = args[0] end end - + def full_name tag_name_with_prefix(TRACKBACK_PREFIX) end - + end class TrackBackAbout < Element include RSS09 @tag_name = "about" - + content_setup class << self - + def required_prefix TRACKBACK_PREFIX end - + def required_uri TRACKBACK_URI end @@ -260,11 +260,11 @@ module RSS self.content = args[0] end end - + def full_name tag_name_with_prefix(TRACKBACK_PREFIX) end - + end end diff --git a/lib/rss/utils.rb b/lib/rss/utils.rb index 0e4001e1f3..75b05d45c7 100644 --- a/lib/rss/utils.rb +++ b/lib/rss/utils.rb @@ -8,7 +8,7 @@ module RSS "#{part[0, 1].upcase}#{part[1..-1]}" end.join("") end - + def get_file_and_line_from_caller(i=0) file, line, = caller[i].split(':') line = line.to_i @@ -21,7 +21,7 @@ module RSS s.to_s.gsub(/&/, "&").gsub(/\"/, """).gsub(/>/, ">").gsub(/</, "<") end alias h html_escape - + # If +value+ is an instance of class +klass+, return it, else # create a new instance of +klass+ with value +value+. def new_with_value_if_need(klass, value) diff --git a/lib/rss/xml-stylesheet.rb b/lib/rss/xml-stylesheet.rb index 559d6bcd56..96ee95050e 100644 --- a/lib/rss/xml-stylesheet.rb +++ b/lib/rss/xml-stylesheet.rb @@ -8,7 +8,7 @@ module RSS super @xml_stylesheets = [] end - + private def xml_stylesheet_pi xsss = @xml_stylesheets.collect do |xss| @@ -94,7 +94,7 @@ module RSS xss.__send__("#{attr}=", __send__(attr)) end end - + private def guess_type(filename) /\.([^.]+)$/ =~ filename diff --git a/lib/rss/xmlparser.rb b/lib/rss/xmlparser.rb index 3dfe7d461a..aa902be396 100644 --- a/lib/rss/xmlparser.rb +++ b/lib/rss/xmlparser.rb @@ -26,9 +26,9 @@ module XML end module RSS - + class REXMLLikeXMLParser < ::XML::Parser - + include ::XML::Encoding_ja def listener=(listener) @@ -38,7 +38,7 @@ module RSS def startElement(name, attrs) @listener.tag_start(name, attrs) end - + def endElement(name) @listener.tag_end(name) end @@ -64,7 +64,7 @@ module RSS XMLParserListener end end - + private def _parse begin @@ -75,13 +75,13 @@ module RSS raise NotWellFormedError.new(parser.line){e.message} end end - + end - + class XMLParserListener < BaseListener include ListenerMixin - + def xmldecl(version, encoding, standalone) super # Encoding is converted to UTF-8 when XMLParser parses XML. diff --git a/lib/rss/xmlscanner.rb b/lib/rss/xmlscanner.rb index 61b9fa6bf4..1cdf81c0c3 100644 --- a/lib/rss/xmlscanner.rb +++ b/lib/rss/xmlscanner.rb @@ -2,15 +2,15 @@ require 'xmlscan/scanner' require 'stringio' module RSS - + class XMLScanParser < BaseParser - + class << self def listener XMLScanListener end end - + private def _parse begin @@ -26,11 +26,11 @@ module RSS raise NotWellFormedError.new(lineno){e.message} end end - + end class XMLScanListener < BaseListener - + include XMLScan::Visitor include ListenerMixin diff --git a/lib/rubygems/builder.rb b/lib/rubygems/builder.rb index 6fd8528f56..1c18c38d48 100644 --- a/lib/rubygems/builder.rb +++ b/lib/rubygems/builder.rb @@ -11,7 +11,7 @@ module Gem # to produce a .gem file. # class Builder - + include UserInteraction ## # Constructs a builder instance for the provided specification @@ -38,7 +38,7 @@ module Gem say success @spec.file_name end - + def success <<-EOM Successfully built RubyGem diff --git a/lib/rubygems/command_manager.rb b/lib/rubygems/command_manager.rb index dd9a1aee15..5a8dec451e 100644 --- a/lib/rubygems/command_manager.rb +++ b/lib/rubygems/command_manager.rb @@ -15,12 +15,12 @@ module Gem # sub-commands supported by the gem command. class CommandManager include UserInteraction - + # Return the authoritative instance of the command manager. def self.instance @command_manager ||= CommandManager.new end - + # Register all the subcommands supported by the gem command. def initialize @commands = {} @@ -52,24 +52,24 @@ module Gem register_command :update register_command :which end - + # Register the command object. def register_command(command_obj) @commands[command_obj] = false end - + # Return the registered command from the command name. def [](command_name) command_name = command_name.intern return nil if @commands[command_name].nil? @commands[command_name] ||= load_and_instantiate(command_name) end - + # Return a list of all command names (as strings). def command_names @commands.keys.collect {|key| key.to_s}.sort end - + # Run the config specified by +args+. def run(args) process_args(args) @@ -88,7 +88,7 @@ module Gem if args.size == 0 say Gem::Command::HELP terminate_interaction(1) - end + end case args[0] when '-h', '--help' say Gem::Command::HELP @@ -122,7 +122,7 @@ module Gem len = cmd_name.length self.command_names.select { |n| cmd_name == n[0,len] } end - + private def load_and_instantiate(command_name) @@ -143,4 +143,4 @@ module Gem end end end -end +end diff --git a/lib/rubygems/commands/check_command.rb b/lib/rubygems/commands/check_command.rb index 17c2c8f9c7..4eefca4232 100644 --- a/lib/rubygems/commands/check_command.rb +++ b/lib/rubygems/commands/check_command.rb @@ -46,7 +46,7 @@ class Gem::Commands::CheckCommand < Gem::Command say "\t#{error_entry.problem}" say end - else + else say "#{key} is error-free" end say diff --git a/lib/rubygems/commands/rdoc_command.rb b/lib/rubygems/commands/rdoc_command.rb index 82180d485c..2790ae7e3e 100644 --- a/lib/rubygems/commands/rdoc_command.rb +++ b/lib/rubygems/commands/rdoc_command.rb @@ -20,12 +20,12 @@ module Gem 'installed gems') do |value, options| options[:all] = value end - add_option('--[no-]rdoc', + add_option('--[no-]rdoc', 'Include RDoc generated documents') do |value, options| options[:include_rdoc] = value end - add_option('--[no-]ri', + add_option('--[no-]ri', 'Include RI generated documents' ) do |value, options| options[:include_ri] = value diff --git a/lib/rubygems/commands/search_command.rb b/lib/rubygems/commands/search_command.rb index 96da19c0f7..96f2e2c94d 100644 --- a/lib/rubygems/commands/search_command.rb +++ b/lib/rubygems/commands/search_command.rb @@ -32,6 +32,6 @@ module Gem super end end - + end end diff --git a/lib/rubygems/config_file.rb b/lib/rubygems/config_file.rb index 934516ed91..545ef1a55a 100644 --- a/lib/rubygems/config_file.rb +++ b/lib/rubygems/config_file.rb @@ -30,7 +30,7 @@ class Gem::ConfigFile PLATFORM_DEFAULTS = {} - system_config_path = + system_config_path = begin require 'Win32API' @@ -45,7 +45,7 @@ class Gem::ConfigFile end SYSTEM_WIDE_CONFIG_FILE = File.join system_config_path, 'gemrc' - + # List of arguments supplied to the config file object. attr_reader :args diff --git a/lib/rubygems/digest/digest_adapter.rb b/lib/rubygems/digest/digest_adapter.rb index d5a00b059d..370446b205 100755 --- a/lib/rubygems/digest/digest_adapter.rb +++ b/lib/rubygems/digest/digest_adapter.rb @@ -6,12 +6,12 @@ #++ module Gem - - # There is an incompatibility between the way Ruby 1.8.5 and 1.8.6 - # handles digests. This DigestAdapter will take a pre-1.8.6 digest + + # There is an incompatibility between the way Ruby 1.8.5 and 1.8.6 + # handles digests. This DigestAdapter will take a pre-1.8.6 digest # and adapt it to the 1.8.6 API. # - # Note that only the digest and hexdigest methods are adapted, + # Note that only the digest and hexdigest methods are adapted, # since these are the only functions used by Gems. # class DigestAdapter diff --git a/lib/rubygems/ext/builder.rb b/lib/rubygems/ext/builder.rb index 36e9ec18f6..a521c7b572 100644 --- a/lib/rubygems/ext/builder.rb +++ b/lib/rubygems/ext/builder.rb @@ -15,7 +15,7 @@ class Gem::Ext::Builder def self.make(dest_path, results) unless File.exist? 'Makefile' then - raise Gem::InstallError, "Makefile not found:\n\n#{results.join "\n"}" + raise Gem::InstallError, "Makefile not found:\n\n#{results.join "\n"}" end mf = File.read('Makefile') diff --git a/lib/rubygems/format.rb b/lib/rubygems/format.rb index 7dc127d5f4..49a3951e26 100644 --- a/lib/rubygems/format.rb +++ b/lib/rubygems/format.rb @@ -17,7 +17,7 @@ module Gem class Format attr_accessor :spec, :file_entries, :gem_path extend Gem::UserInteraction - + ## # Constructs an instance of a Format object, representing the gem's # data structure. @@ -27,9 +27,9 @@ module Gem def initialize(gem_path) @gem_path = gem_path end - + ## - # Reads the named gem file and returns a Format object, representing + # Reads the named gem file and returns a Format object, representing # the data from the gem file # # file_path:: [String] Path to the gem file diff --git a/lib/rubygems/gem_runner.rb b/lib/rubygems/gem_runner.rb index 5f91398b5b..7edc93d68f 100644 --- a/lib/rubygems/gem_runner.rb +++ b/lib/rubygems/gem_runner.rb @@ -38,7 +38,7 @@ module Gem end cmd.run(Gem.configuration.args) end_time = Time.now - if Gem.configuration.benchmark + if Gem.configuration.benchmark printf "\nExecution time: %0.2f seconds.\n", end_time-start_time puts "Press Enter to finish" STDIN.gets diff --git a/lib/rubygems/old_format.rb b/lib/rubygems/old_format.rb index ef5d621f52..4b8db70bc6 100644 --- a/lib/rubygems/old_format.rb +++ b/lib/rubygems/old_format.rb @@ -16,7 +16,7 @@ module Gem # class OldFormat attr_accessor :spec, :file_entries, :gem_path - + ## # Constructs an instance of a Format object, representing the gem's # data structure. @@ -26,9 +26,9 @@ module Gem def initialize(gem_path) @gem_path = gem_path end - + ## - # Reads the named gem file and returns a Format object, representing + # Reads the named gem file and returns a Format object, representing # the data from the gem file # # file_path:: [String] Path to the gem file @@ -58,8 +58,8 @@ module Gem end format end - - private + + private ## # Skips the Ruby self-install header. After calling this method, the # IO index will be set after the Ruby code. @@ -79,7 +79,7 @@ module Gem raise Gem::Exception.new("Failed to find end of ruby script while reading gem") end end - + ## # Reads the specification YAML from the supplied IO and constructs # a Gem::Specification from it. After calling this method, the @@ -100,7 +100,7 @@ module Gem raise Gem::Exception.new("Failed to parse gem specification out of gem file") end end - + ## # Reads lines from the supplied IO until a end-of-yaml (---) is # reached diff --git a/lib/rubygems/package/tar_header.rb b/lib/rubygems/package/tar_header.rb index c194cc0530..fa78126a0d 100644 --- a/lib/rubygems/package/tar_header.rb +++ b/lib/rubygems/package/tar_header.rb @@ -233,7 +233,7 @@ class Gem::Package::TarHeader ] header = header.pack PACK_FORMAT - + header << ("\0" * ((512 - header.size) % 512)) end diff --git a/lib/rubygems/package/tar_writer.rb b/lib/rubygems/package/tar_writer.rb index 6e11440e22..04a15c7779 100644 --- a/lib/rubygems/package/tar_writer.rb +++ b/lib/rubygems/package/tar_writer.rb @@ -169,7 +169,7 @@ class Gem::Package::TarWriter name = newname if name.size > 100 or prefix.size > 155 then - raise Gem::Package::TooLongFileName + raise Gem::Package::TooLongFileName end end diff --git a/lib/rubygems/security.rb b/lib/rubygems/security.rb index abf3cf4a6a..5cd3fb756f 100644 --- a/lib/rubygems/security.rb +++ b/lib/rubygems/security.rb @@ -218,7 +218,7 @@ require 'rubygems/gem_openssl' # # # signing key (still kept in an undisclosed location!) # s.signing_key = '/mnt/floppy/alf-private_key.pem' -# +# # # certificate chain (includes the issuer certificate now too) # s.cert_chain = ['/home/alf/doc/seattlerb-public_cert.pem', # '/home/alf/doc/alf_at_seattle-public_cert.pem'] @@ -274,7 +274,7 @@ require 'rubygems/gem_openssl' # # convert a PEM format X509 certificate into DER format: # # (note: Windows .cer files are X509 certificates in DER format) # $ openssl x509 -in input.pem -outform der -out output.der -# +# # # print out the certificate in a human-readable format: # $ openssl x509 -in input.pem -noout -text # @@ -282,7 +282,7 @@ require 'rubygems/gem_openssl' # # # convert a PEM format RSA key into DER format: # $ openssl rsa -in input_key.pem -outform der -out output_key.der -# +# # # print out the key in a human readable format: # $ openssl rsa -in input_key.pem -noout -text # diff --git a/lib/rubygems/source_index.rb b/lib/rubygems/source_index.rb index 8a8db2ef0d..57f6c30ae6 100644 --- a/lib/rubygems/source_index.rb +++ b/lib/rubygems/source_index.rb @@ -376,7 +376,7 @@ class Gem::SourceIndex end def ==(other) # :nodoc: - self.class === other and @gems == other.gems + self.class === other and @gems == other.gems end def dump diff --git a/lib/rubygems/source_info_cache.rb b/lib/rubygems/source_info_cache.rb index fdb30ad8d3..4289cdb52a 100644 --- a/lib/rubygems/source_info_cache.rb +++ b/lib/rubygems/source_info_cache.rb @@ -286,7 +286,7 @@ class Gem::SourceInfoCache next unless Gem.sources.include? source_uri # TODO - Remove this gunk after 2008/11 unless pattern.kind_of?(Gem::Dependency) - pattern = Gem::Dependency.new(pattern, Gem::Requirement.default) + pattern = Gem::Dependency.new(pattern, Gem::Requirement.default) end sic_entry.source_index.search pattern, platform_only end.flatten.compact @@ -306,7 +306,7 @@ class Gem::SourceInfoCache # TODO - Remove this gunk after 2008/11 unless pattern.kind_of?(Gem::Dependency) - pattern = Gem::Dependency.new(pattern, Gem::Requirement.default) + pattern = Gem::Dependency.new(pattern, Gem::Requirement.default) end sic_entry.source_index.search(pattern, only_platform).each do |spec| diff --git a/lib/rubygems/specification.rb b/lib/rubygems/specification.rb index b3a42cf902..634b88f1f0 100644 --- a/lib/rubygems/specification.rb +++ b/lib/rubygems/specification.rb @@ -256,7 +256,7 @@ module Gem # Defines a _singular_ version of an existing _plural_ attribute (i.e. one # whose value is expected to be an array). This means just creating a # helper method that takes a single value and appends it to the array. - # These are created for convenience, so that in a spec, one can write + # These are created for convenience, so that in a spec, one can write # # s.require_path = 'mylib' # @@ -266,13 +266,13 @@ module Gem # # That above convenience is available courtesy of: # - # attribute_alias_singular :require_path, :require_paths + # attribute_alias_singular :require_path, :require_paths def self.attribute_alias_singular(singular, plural) define_method("#{singular}=") { |val| send("#{plural}=", [val]) } - define_method("#{singular}") { + define_method("#{singular}") { val = send("#{plural}") val.nil? ? nil : val.first } @@ -427,7 +427,7 @@ module Gem end alias has_test_suite? has_unit_tests? # :nodoc: deprecated - + ## # Specification constructor. Assigns the default values to the # attributes, adds this spec to the list of loaded specs (see @@ -476,7 +476,7 @@ module Gem # routine (#initialize). This method makes up for that and deals with # gems of different ages. # - # 'input' can be anything that YAML.load() accepts: String or IO. + # 'input' can be anything that YAML.load() accepts: String or IO. def self.from_yaml(input) input = normalize_yaml_input input @@ -493,12 +493,12 @@ module Gem unless (spec.instance_variables.include? '@specification_version' or spec.instance_variables.include? :@specification_version) and spec.instance_variable_get :@specification_version - spec.instance_variable_set :@specification_version, + spec.instance_variable_set :@specification_version, NONEXISTENT_SPECIFICATION_VERSION end spec - end + end ## # Loads ruby format gemspec from +filename+ @@ -522,7 +522,7 @@ module Gem result = "--- " + result unless result =~ /^--- / result end - + ## # Sets the rubygems_version to the current RubyGems version @@ -624,7 +624,7 @@ module Gem # Checks if this specification meets the requirement of +dependency+. def satisfies_requirement?(dependency) - return @name == dependency.name && + return @name == dependency.name && dependency.version_requirements.satisfied_by?(@version) end @@ -804,7 +804,7 @@ module Gem raise Gem::InvalidSpecificationException, "missing value for attribute #{symbol}" end - end + end if require_paths.empty? then raise Gem::InvalidSpecificationException, @@ -850,9 +850,9 @@ module Gem # Normalize the list of files so that: # * All file lists have redundancies removed. # * Files referenced in the extra_rdoc_files are included in the package - # file list. + # file list. # - # Also, the summary and description are converted to a normal format. + # Also, the summary and description are converted to a normal format. def normalize if defined?(@extra_rdoc_files) and @extra_rdoc_files then @@ -935,11 +935,11 @@ module Gem else raise Exception, "ruby_code case not handled: #{obj.class}" end end - + private :ruby_code # :section: Required gemspec attributes - + ## # The version of RubyGems used to create this gem @@ -979,7 +979,7 @@ module Gem ## # A contact email for this gem - + attribute :email ## @@ -990,7 +990,7 @@ module Gem ## # The rubyforge project this gem lives under. i.e. RubyGems' # rubyforge_project is "rubygems". - + attribute :rubyforge_project ## @@ -1108,7 +1108,7 @@ module Gem ## # Singular accessor for executables - + attribute_alias_singular :executable, :executables ## diff --git a/lib/rubygems/test_utilities.rb b/lib/rubygems/test_utilities.rb index 8b23d3236e..85541c9fc3 100644 --- a/lib/rubygems/test_utilities.rb +++ b/lib/rubygems/test_utilities.rb @@ -11,9 +11,9 @@ require 'rubygems/remote_fetcher' # @fetcher = Gem::FakeFetcher.new # @fetcher.data['http://gems.example.com/yaml'] = source_index.to_yaml # Gem::RemoteFetcher.fetcher = @fetcher -# +# # # invoke RubyGems code -# +# # paths = @fetcher.paths # assert_equal 'http://gems.example.com/yaml', paths.shift # assert paths.empty?, paths.join(', ') diff --git a/lib/scanf.rb b/lib/scanf.rb index cbb98b6f9f..386270b924 100644 --- a/lib/scanf.rb +++ b/lib/scanf.rb @@ -63,7 +63,7 @@ to the beginning of the format string, and yields a new array of conversions to the block every time the format string is matched (including partial matches, but not including complete failures). The actual return value of scanf when called with a block is an array -containing the results of all the executions of the block. +containing the results of all the executions of the block. str = "123 abc 456 def 789 ghi" str.scanf("%d%s") { |num,str| [ num * 2, str.upcase ] } @@ -100,7 +100,7 @@ and <tt>tests/scanftests.rb</tt> for examples.) [u] Same as d. -[i] +[i] Matches an optionally signed integer. The integer is read in base 16 if it begins with `0x' or `0X', in base 8 if it begins with `0', and in base 10 other- wise. Only characters that correspond to the @@ -280,7 +280,7 @@ Project contributors:: Nolan Darilek, Jason Johnston Thanks to Hal Fulton for hosting the Codefest. -Thanks to Matz for suggestions about the class design. +Thanks to Matz for suggestions about the class design. Thanks to Gavin Sinclair for some feedback on the documentation. @@ -332,7 +332,7 @@ module Scanf @spec_string = str h = '[A-Fa-f0-9]' - @re_string, @handler = + @re_string, @handler = case @spec_string # %[[:...:]] @@ -482,7 +482,7 @@ module Scanf return width_left || cc_no_width end - + end class FormatString @@ -672,10 +672,10 @@ class String if b block_scanf(fstr,&b) else - fs = + fs = if fstr.is_a? Scanf::FormatString - fstr - else + fstr + else Scanf::FormatString.new(fstr) end fs.match(self) diff --git a/lib/set.rb b/lib/set.rb index f930c5e4a9..7b8896c335 100644 --- a/lib/set.rb +++ b/lib/set.rb @@ -4,15 +4,15 @@ #++ # Copyright (c) 2002-2008 Akinori MUSHA <[email protected]> # -# Documentation by Akinori MUSHA and Gavin Sinclair. +# Documentation by Akinori MUSHA and Gavin Sinclair. # # All rights reserved. You can redistribute and/or modify it under the same # terms as Ruby. # # $Id$ # -# == Overview -# +# == 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 @@ -555,33 +555,33 @@ end # == RestricedSet class # RestricedSet implements a set with restrictions defined by a given # block. -# +# # === Super class # Set -# +# # === Class Methods # --- RestricedSet::new(enum = nil) { |o| ... } # --- RestricedSet::new(enum = nil) { |rset, o| ... } # Creates a new restricted set containing the elements of the given # enumerable object. Restrictions are defined by the given block. -# +# # If the block's arity is 2, it is called with the RestrictedSet # itself and an object to see if the object is allowed to be put in # the set. -# +# # Otherwise, the block is called with an object to see if the object # is allowed to be put in the set. -# +# # === Instance Methods # --- restriction_proc # Returns the restriction procedure of the set. -# +# # =end -# +# # class RestricedSet < Set # def initialize(*args, &block) # @proc = block or raise ArgumentError, "missing a block" -# +# # if @proc.arity == 2 # instance_eval %{ # def add(o) @@ -589,7 +589,7 @@ end # self # end # alias << add -# +# # def add?(o) # if include?(o) || [email protected](self, o) # nil @@ -598,17 +598,17 @@ end # self # end # end -# +# # def replace(enum) # clear # enum.each { |o| add(o) } -# +# # self # end -# +# # def merge(enum) # enum.each { |o| add(o) } -# +# # self # end # } @@ -616,12 +616,12 @@ end # instance_eval %{ # def add(o) # if @proc.call(o) -# @hash[o] = true +# @hash[o] = true # end # self # end # alias << add -# +# # def add?(o) # if include?(o) || [email protected](o) # nil @@ -632,10 +632,10 @@ end # end # } # end -# +# # super(*args) # end -# +# # def restriction_proc # @proc # end @@ -1241,33 +1241,33 @@ end # class TC_RestricedSet < Test::Unit::TestCase # def test_s_new # assert_raises(ArgumentError) { RestricedSet.new } -# +# # s = RestricedSet.new([-1,2,3]) { |o| o > 0 } # assert_equal([2,3], s.sort) # end -# +# # def test_restriction_proc # s = RestricedSet.new([-1,2,3]) { |o| o > 0 } -# +# # f = s.restriction_proc # assert_instance_of(Proc, f) # assert(f[1]) # assert(!f[0]) # end -# +# # def test_replace # s = RestricedSet.new(-3..3) { |o| o > 0 } # assert_equal([1,2,3], s.sort) -# +# # s.replace([-2,0,3,4,5]) # assert_equal([3,4,5], s.sort) # end -# +# # def test_merge # s = RestricedSet.new { |o| o > 0 } # s.merge(-5..5) # assert_equal([1,2,3,4,5], s.sort) -# +# # s.merge([10,-10,-8,8]) # assert_equal([1,2,3,4,5,8,10], s.sort) # end diff --git a/lib/shell.rb b/lib/shell.rb index 6a64cb263f..d2ce26d3b3 100644 --- a/lib/shell.rb +++ b/lib/shell.rb @@ -1,12 +1,12 @@ # -# shell.rb - +# shell.rb - # $Release Version: 0.7 $ # $Revision: 1.9 $ # by Keiju ISHITSUKA([email protected]) # # -- # -# +# # require "e2mmap" diff --git a/lib/shell/builtin-command.rb b/lib/shell/builtin-command.rb index b65056de0f..e489da4eca 100644 --- a/lib/shell/builtin-command.rb +++ b/lib/shell/builtin-command.rb @@ -1,12 +1,12 @@ # -# shell/builtin-command.rb - +# shell/builtin-command.rb - # $Release Version: 0.7 $ # $Revision$ # by Keiju ISHITSUKA([email protected]) # # -- # -# +# # require "shell/filter" @@ -25,7 +25,7 @@ class Shell def initialize(sh, *opts) super sh end - + def each(rs = nil) # do nothing end @@ -36,7 +36,7 @@ class Shell super sh @strings = strings end - + def each(rs = nil) rs = @shell.record_separator unless rs for str in @strings @@ -70,7 +70,7 @@ class Shell end def each(rs = nil) - if @pattern[0] == ?/ + if @pattern[0] == ?/ @files = Dir[@pattern] else prefix = @shell.pwd+"/" diff --git a/lib/shell/command-processor.rb b/lib/shell/command-processor.rb index 900b31a22d..e224d91368 100644 --- a/lib/shell/command-processor.rb +++ b/lib/shell/command-processor.rb @@ -1,12 +1,12 @@ # -# shell/command-controller.rb - +# shell/command-controller.rb - # $Release Version: 0.7 $ # $Revision$ # by Keiju ISHITSUKA([email protected]) # # -- # -# +# # require "e2mmap" @@ -39,7 +39,7 @@ class Shell for m in CommandProcessor.instance_methods(false) - NoDelegateMethods add_delegate_command_to_shell(m) end - + def self.method_added(id) add_delegate_command_to_shell(id) end @@ -84,7 +84,7 @@ class Shell # Shell#test # # - - # + # # CommandProcessor#foreach(path, rs) # path: String # rs: String - record separator @@ -168,7 +168,7 @@ class Shell # sh["e", "foo"] # sh[:exists?, "foo"] # sh["exists?", "foo"] - # + # alias top_level_test test def test(command, file1, file2=nil) file1 = expand_path(file1) @@ -211,11 +211,11 @@ class Shell # CommandProcessor#mkdir(*path) # path: String # same as Dir.mkdir() - # + # def mkdir(*path) @shell.check_point notify("mkdir #{path.join(' ')}") - + perm = nil if path.last.kind_of?(Integer) perm = path.pop @@ -236,7 +236,7 @@ class Shell # CommandProcessor#rmdir(*path) # path: String # same as Dir.rmdir() - # + # def rmdir(*path) @shell.check_point notify("rmdir #{path.join(' ')}") @@ -256,7 +256,7 @@ class Shell # example: # print sh.system("ls", "-l") # sh.system("ls", "-l") | sh.head > STDOUT - # + # def system(command, *opts) if opts.empty? if command =~ /\*|\?|\{|\}|\[|\]|<|>|\(|\)|~|&|\||\\|\$|;|'|`|"|\n/ @@ -338,7 +338,7 @@ class Shell def notify(*opts, &block) Shell.notify(*opts) {|mes| yield mes if iterator? - + mes.gsub!("%pwd", "#{@cwd}") mes.gsub!("%cwd", "#{@cwd}") } @@ -383,10 +383,10 @@ class Shell SystemCommand.new(@shell, '#{path}', *opts) end]), nil, __FILE__, __LINE__ - 1) rescue SyntaxError - Shell.notify "warn: Can't define #{command} path: #{path}." + Shell.notify "warn: Can't define #{command} path: #{path}." end Shell.notify "Define #{command} path: #{path}.", Shell.debug? - Shell.notify("Definition of #{command}: ", d, + Shell.notify("Definition of #{command}: ", d, Shell.debug.kind_of?(Integer) && Shell.debug > 1) end @@ -418,7 +418,7 @@ class Shell @shell.__send__(:#{command}, *(CommandProcessor.alias_map[:#{ali}].call *opts)) end]), nil, __FILE__, __LINE__ - 1) - + else args = opts.collect{|opt| '"' + opt + '"'}.join(",") eval((d = %Q[def #{ali}(*opts) @@ -426,22 +426,22 @@ class Shell end]), nil, __FILE__, __LINE__ - 1) end rescue SyntaxError - Shell.notify "warn: Can't alias #{ali} command: #{command}." + Shell.notify "warn: Can't alias #{ali} command: #{command}." Shell.notify("Definition of #{ali}: ", d) raise end Shell.notify "Define #{ali} command: #{command}.", Shell.debug? - Shell.notify("Definition of #{ali}: ", d, + Shell.notify("Definition of #{ali}: ", d, Shell.debug.kind_of?(Integer) && Shell.debug > 1) self end - + def self.unalias_command(ali) ali = ali.id2name if ali.kind_of?(Symbol) @alias_map.delete ali.intern undef_system_command(ali) end - + # # CommandProcessor.def_builtin_commands(delegation_class, command_specs) # delegation_class: Class or Module @@ -472,7 +472,7 @@ class Shell #{delegation_class}.#{meth}(#{call_arg_str}) end] Shell.notify "Define #{meth}(#{arg_str})", Shell.debug? - Shell.notify("Definition of #{meth}: ", d, + Shell.notify("Definition of #{meth}: ", d, Shell.debug.kind_of?(Integer) && Shell.debug > 1) eval d end @@ -513,7 +513,7 @@ class Shell #---------------------------------------------------------------------- # - # class initializing methods - + # class initializing methods - # #---------------------------------------------------------------------- def self.add_delegate_command_to_shell(id) @@ -561,7 +561,7 @@ class Shell normal_delegation_file_methods = [ ["atime", ["FILENAME"]], ["basename", ["fn", "*opts"]], - ["chmod", ["mode", "*FILENAMES"]], + ["chmod", ["mode", "*FILENAMES"]], ["chown", ["owner", "group", "*FILENAME"]], ["ctime", ["FILENAMES"]], ["delete", ["*FILENAMES"]], @@ -584,7 +584,7 @@ class Shell alias_method :rm, :delete # method related FileTest - def_builtin_commands(FileTest, + def_builtin_commands(FileTest, FileTest.singleton_methods(false).collect{|m| [m, ["FILENAME"]]}) end diff --git a/lib/shell/error.rb b/lib/shell/error.rb index 8bb96c22da..dbb788a6fc 100644 --- a/lib/shell/error.rb +++ b/lib/shell/error.rb @@ -1,12 +1,12 @@ # -# shell/error.rb - +# shell/error.rb - # $Release Version: 0.7 $ # $Revision$ # by Keiju ISHITSUKA([email protected]) # # -- # -# +# # require "e2mmap" diff --git a/lib/shell/filter.rb b/lib/shell/filter.rb index 3bb683db22..3f88d0f5d2 100644 --- a/lib/shell/filter.rb +++ b/lib/shell/filter.rb @@ -1,12 +1,12 @@ # -# shell/filter.rb - +# shell/filter.rb - # $Release Version: 0.7 $ # $Revision$ # by Keiju ISHITSUKA([email protected]) # # -- # -# +# # class Shell @@ -28,7 +28,7 @@ class Shell def input=(filter) @input = filter end - + def each(rs = nil) rs = @shell.record_separator unless rs if @input diff --git a/lib/shell/process-controller.rb b/lib/shell/process-controller.rb index f2bf1d44c8..829ff7900a 100644 --- a/lib/shell/process-controller.rb +++ b/lib/shell/process-controller.rb @@ -1,12 +1,12 @@ # -# shell/process-controller.rb - +# shell/process-controller.rb - # $Release Version: 0.7 $ # $Revision$ # by Keiju ISHITSUKA([email protected]) # # -- # -# +# # require "forwardable" @@ -26,7 +26,7 @@ class Shell class<<self extend Forwardable - def_delegator("@ProcessControllersMonitor", + def_delegator("@ProcessControllersMonitor", "synchronize", "process_controllers_exclusive") def active_process_controllers @@ -118,7 +118,7 @@ class Shell def waiting_jobs @waiting_jobs end - + def jobs_exist? @jobs_sync.synchronize(:SH) do @active_jobs.empty? or @waiting_jobs.empty? @@ -158,7 +158,7 @@ class Shell else command = @waiting_jobs.shift # command.notify "job(%id) pre-start.", @shell.debug? - + return unless command end @active_jobs.push command @@ -253,7 +253,7 @@ class Shell end pid = fork { - Thread.list.each do |th| + Thread.list.each do |th| # th.kill unless [Thread.main, Thread.current].include?(th) th.kill unless Thread.current == th end @@ -261,7 +261,7 @@ class Shell STDIN.reopen(pipe_peer_in) STDOUT.reopen(pipe_peer_out) - ObjectSpace.each_object(IO) do |io| + ObjectSpace.each_object(IO) do |io| if ![STDIN, STDOUT, STDERR].include?(io) io.close unless io.closed? end @@ -295,9 +295,9 @@ class Shell "You can use Shell#transact or Shell#check_point for more safe execution.") redo end - + # command.notify "job(%id) pre-pre-finish.", @shell.debug? - @job_monitor.synchronize do + @job_monitor.synchronize do # command.notify "job(%id) pre-finish.", @shell.debug? terminate_job(command) # command.notify "job(%id) pre-finish2.", @shell.debug? diff --git a/lib/shell/system-command.rb b/lib/shell/system-command.rb index da5d4cb898..af9b0a8e37 100644 --- a/lib/shell/system-command.rb +++ b/lib/shell/system-command.rb @@ -1,12 +1,12 @@ # -# shell/system-command.rb - +# shell/system-command.rb - # $Release Version: 0.7 $ # $Revision$ # by Keiju ISHITSUKA([email protected]) # # -- # -# +# # require "shell/filter" @@ -20,7 +20,7 @@ class Shell super(sh) @command = command @opts = opts - + @input_queue = Queue.new @pid = nil @@ -140,9 +140,9 @@ class Shell end # ex) - # if you wish to output: + # if you wish to output: # "shell: job(#{@command}:#{@pid}) close pipe-out." - # then + # then # mes: "job(%id) close pipe-out." # yorn: Boolean(@shell.debug? or @shell.verbose?) def notify(*opts, &block) diff --git a/lib/shell/version.rb b/lib/shell/version.rb index dd50b06d55..6e4c170351 100644 --- a/lib/shell/version.rb +++ b/lib/shell/version.rb @@ -6,7 +6,7 @@ # # -- # -# +# # class Shell diff --git a/lib/sync.rb b/lib/sync.rb index f4dea76d1f..36c4c08d45 100644 --- a/lib/sync.rb +++ b/lib/sync.rb @@ -34,7 +34,7 @@ # Sync#lock(mode) -- mode = :EX, :SH, :UN # Sync#unlock # Sync#synchronize(mode) {...} -# +# # unless defined? Thread @@ -43,25 +43,25 @@ end module Sync_m RCS_ID='-$Header$-' - + # lock mode UN = :UN SH = :SH EX = :EX - + # exceptions class Err < StandardError def Err.Fail(*opt) fail self, sprintf(self::Message, *opt) end - + class UnknownLocker < Err Message = "Thread(%s) not locked." def UnknownLocker.Fail(th) super(th.inspect) end end - + class LockModeFailer < Err Message = "Unknown lock mode(%s)" def LockModeFailer.Fail(mode) @@ -72,7 +72,7 @@ module Sync_m end end end - + def Sync_m.define_aliases(cl) cl.module_eval %q{ alias locked? sync_locked? @@ -84,7 +84,7 @@ module Sync_m alias synchronize sync_synchronize } end - + def Sync_m.append_features(cl) super # do nothing for Modules @@ -92,12 +92,12 @@ module Sync_m define_aliases(cl) unless cl.instance_of?(Module) self end - + def Sync_m.extend_object(obj) super obj.sync_extend end - + def sync_extend unless (defined? locked? and defined? shared? and @@ -115,15 +115,15 @@ module Sync_m def sync_locked? sync_mode != UN end - + def sync_shared? sync_mode == SH end - + def sync_exclusive? sync_mode == EX end - + # locking methods. def sync_try_lock(mode = EX) return unlock if mode == UN @@ -132,7 +132,7 @@ module Sync_m end ret end - + def sync_lock(m = EX) return unlock if m == UN @@ -153,21 +153,21 @@ module Sync_m end self end - + def sync_unlock(m = EX) wakeup_threads = [] @sync_mutex.synchronize do if sync_mode == UN Err::UnknownLocker.Fail(Thread.current) end - + m = sync_mode if m == EX and sync_mode == SH - + runnable = false case m when UN Err::UnknownLocker.Fail(Thread.current) - + when EX if sync_ex_locker == Thread.current if (self.sync_ex_count = sync_ex_count - 1) == 0 @@ -182,12 +182,12 @@ module Sync_m 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 + 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 @@ -196,7 +196,7 @@ module Sync_m end end end - + if runnable if sync_upgrade_waiting.size > 0 th, count = sync_upgrade_waiting.shift @@ -218,7 +218,7 @@ module Sync_m end self end - + def sync_synchronize(mode = EX) sync_lock(mode) begin @@ -229,7 +229,7 @@ module Sync_m end attr_accessor :sync_mode - + attr_accessor :sync_waiting attr_accessor :sync_upgrade_waiting attr_accessor :sync_sh_locker @@ -258,7 +258,7 @@ module Sync_m super sync_initialize end - + def sync_try_lock_sub(m) case m when SH @@ -282,7 +282,7 @@ module Sync_m end when EX if sync_mode == UN or - sync_mode == SH && sync_sh_locker.size == 1 && sync_sh_locker.include?(Thread.current) + sync_mode == SH && sync_sh_locker.size == 1 && sync_sh_locker.include?(Thread.current) self.sync_mode = m self.sync_ex_locker = Thread.current self.sync_ex_count = 1 diff --git a/lib/tempfile.rb b/lib/tempfile.rb index 601bb8d2f8..e3934b5d08 100644 --- a/lib/tempfile.rb +++ b/lib/tempfile.rb @@ -87,7 +87,7 @@ class Tempfile < DelegateClass(File) else prefix, suffix = basename, '' end - + t = Time.now.strftime("%Y%m%d") path = "#{prefix}#{t}-#{$$}-#{rand(0x100000000).to_s(36)}-#{n}#{suffix}" end @@ -167,7 +167,7 @@ class Tempfile < DelegateClass(File) def callback(data) # :nodoc: pid = $$ Proc.new { - if pid == $$ + if pid == $$ path, tmpfile, cleanlist = *data print "removing ", path, "..." if $DEBUG diff --git a/lib/test/unit.rb b/lib/test/unit.rb index 729ddf6adf..3e2b388273 100644 --- a/lib/test/unit.rb +++ b/lib/test/unit.rb @@ -45,7 +45,7 @@ module Test reject_pat = Regexp.union(reject.map {|r| /#{r}/ }) files.reject! {|f| reject_pat =~ f } - + files.each {|f| d = File.dirname(File.expand_path(f)) unless $:.include? d diff --git a/lib/thread.rb b/lib/thread.rb index e5585c30bd..cb6d8c62fc 100644 --- a/lib/thread.rb +++ b/lib/thread.rb @@ -20,7 +20,7 @@ if $DEBUG Thread.abort_on_exception = true end -# +# # 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. @@ -31,7 +31,7 @@ end # # mutex = Mutex.new # resource = ConditionVariable.new -# +# # a = Thread.new { # mutex.synchronize { # # Thread 'a' now needs the resource @@ -39,7 +39,7 @@ end # # 'a' can now have the resource # } # } -# +# # b = Thread.new { # mutex.synchronize { # # Thread 'b' has finished using the resource @@ -55,7 +55,7 @@ class ConditionVariable @waiters = [] @waiters_mutex = Mutex.new end - + # # Releases the lock held in +mutex+ and waits; reacquires the lock on wakeup. # @@ -68,7 +68,7 @@ class ConditionVariable mutex.sleep end end - + # # Wakes up the first thread in line waiting for this lock. # @@ -80,7 +80,7 @@ class ConditionVariable retry end end - + # # Wakes up all threads waiting for this lock. # @@ -106,9 +106,9 @@ end # Example: # # require 'thread' -# +# # queue = Queue.new -# +# # producer = Thread.new do # 5.times do |i| # sleep rand(i) # simulate expense @@ -116,7 +116,7 @@ end # puts "#{i} produced" # end # end -# +# # consumer = Thread.new do # 5.times do |i| # value = queue.pop @@ -124,7 +124,7 @@ end # puts "consumed #{value}" # end # end -# +# # consumer.join # class Queue @@ -296,7 +296,7 @@ class SizedQueue < Queue @queue_wait.push Thread.current @mutex.sleep end - + @que.push obj begin t = @waiting.shift @@ -305,7 +305,7 @@ class SizedQueue < Queue retry end } - + begin t.run if t rescue ThreadError diff --git a/lib/thwait.rb b/lib/thwait.rb index 029b259157..09d99a6c5b 100644 --- a/lib/thwait.rb +++ b/lib/thwait.rb @@ -15,7 +15,7 @@ # each thread termination. # * th = ThreadsWait.new(thread1,...) # creates synchronization object, specifying thread(s) to wait. -# +# # methods: # * th.threads # list threads to be synchronized @@ -23,7 +23,7 @@ # is there any thread to be synchronized. # * th.finished? # is there already terminated thread. -# * th.join(thread1,...) +# * th.join(thread1,...) # wait for specified thread(s). # * th.join_nowait(threa1,...) # specifies thread(s) to wait. non-blocking. @@ -52,11 +52,11 @@ require "e2mmap.rb" # class ThreadsWait RCS_ID='-$Id: thwait.rb,v 1.3 1998/06/26 03:19:34 keiju Exp keiju $-' - + extend Exception2MessageMapper def_exception("ErrNoWaitingThread", "No threads for waiting.") def_exception("ErrNoFinishedThread", "No finished threads.") - + # # Waits until all specified threads have terminated. If a block is provided, # it is executed for each thread termination. @@ -71,7 +71,7 @@ class ThreadsWait tw.all_waits end end - + # # Creates a ThreadsWait object, specifying the threads to wait on. # Non-blocking. @@ -81,24 +81,24 @@ class ThreadsWait @wait_queue = Queue.new join_nowait(*threads) unless threads.empty? end - + # Returns the array of threads in the wait queue. attr :threads - + # # Returns +true+ if there are no threads to be synchronized. # def empty? @threads.empty? end - + # # Returns +true+ if any thread has terminated. # def finished? !@wait_queue.empty? end - + # # Waits for specified threads to terminate. # @@ -106,7 +106,7 @@ class ThreadsWait join_nowait(*threads) next_wait end - + # # Specifies the threads that this object will wait for, but does not actually # wait. @@ -124,7 +124,7 @@ class ThreadsWait end end end - + # # Waits until any of the specified threads has terminated, and returns the one # that does. @@ -141,7 +141,7 @@ class ThreadsWait ThreadsWait.fail ErrNoFinishedThread end end - + # # Waits until all of the specified threads are terminated. If a block is # supplied for the method, it is executed for each thread termination. diff --git a/lib/time.rb b/lib/time.rb index 53e6697e76..031a4135ef 100644 --- a/lib/time.rb +++ b/lib/time.rb @@ -98,7 +98,7 @@ class Time # In RFC 3339, -00:00 is used for the time in UTC is known, # but the offset to local time is unknown. # They are not appropriate for specific time zone such as - # Europe/London because time zone neutral, + # Europe/London because time zone neutral, # So -00:00 and -0000 are treated as UTC. if /\A(?:-00:00|-0000|-00|UTC|Z|UT)\z/i =~ zone true diff --git a/lib/timeout.rb b/lib/timeout.rb index 19ccb96d3e..893b5f8f58 100644 --- a/lib/timeout.rb +++ b/lib/timeout.rb @@ -63,7 +63,7 @@ module Timeout raise Error, e.message, e.backtrace ensure if y and y.alive? - y.kill + y.kill y.join # make sure y is dead. end end diff --git a/lib/tracer.rb b/lib/tracer.rb index 1fdc608960..8e6586d7c6 100644 --- a/lib/tracer.rb +++ b/lib/tracer.rb @@ -1,12 +1,12 @@ # -# tracer.rb - +# tracer.rb - # $Release Version: 0.2$ # $Revision: 1.8 $ # by Keiju ISHITSUKA(Nippon Rational Inc.) # # -- # -# +# # # @@ -22,7 +22,7 @@ class Tracer alias verbose? verbose attr_accessor :stdout end - + EVENT_SYMBOL = { "line" => "-", "call" => ">", @@ -32,7 +32,7 @@ class Tracer "c-call" => ">", "c-return" => "<", } - + def initialize @threads = Hash.new if defined? Thread.main @@ -45,7 +45,7 @@ class Tracer @filters = [] end - + def stdout Tracer.stdout end @@ -63,7 +63,7 @@ class Tracer stdout.print "Trace on\n" if Tracer.verbose? end end - + def off set_trace_func nil stdout.print "Trace off\n" if Tracer.verbose? @@ -76,7 +76,7 @@ class Tracer def set_get_line_procs(file, p = proc) @get_line_procs[file] = p end - + def get_line(file, line) if p = @get_line_procs[file] return p.call(line) @@ -85,7 +85,7 @@ class Tracer unless list = SCRIPT_LINES__[file] begin f = open(file) - begin + begin SCRIPT_LINES__[file] = list = f.readlines ensure f.close @@ -101,7 +101,7 @@ class Tracer "-\n" end end - + def get_thread_no if no = @threads[Thread.current.object_id] no @@ -109,14 +109,14 @@ class Tracer @threads[Thread.current.object_id] = @threads.size end end - + def trace_func(event, file, line, id, binding, klass, *) return if file == __FILE__ - + for p in @filters return unless p.call event, file, line, id, binding, klass end - + # saved_crit = Thread.critical # Thread.critical = true stdout.printf("#%d:%s:%d:%s:%s: %s", @@ -137,11 +137,11 @@ class Tracer Single.on end end - + def Tracer.off Single.off end - + def Tracer.set_get_line_procs(file_name, p = proc) Single.set_get_line_procs(file_name, p) end @@ -149,14 +149,14 @@ class Tracer def Tracer.add_filter(p = proc) Single.add_filter(p) end - + end SCRIPT_LINES__ = {} unless defined? SCRIPT_LINES__ if $0 == __FILE__ # direct call - + $0 = ARGV[0] ARGV.shift Tracer.on @@ -1,11 +1,11 @@ -# +# # = un.rb -# +# # Copyright (c) 2003 WATANABE Hirofumi <[email protected]> -# +# # 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 diff --git a/lib/uri.rb b/lib/uri.rb index f7110f18fd..41bb09b467 100644 --- a/lib/uri.rb +++ b/lib/uri.rb @@ -3,11 +3,11 @@ # # Author:: Akira Yamada <[email protected]> # Documentation:: Akira Yamada <[email protected]>, Dmitry V. Sabanin <[email protected]> -# License:: +# License:: # Copyright (c) 2001 akira yamada <[email protected]> # You can redistribute it and/or modify it under the same term as Ruby. # Revision:: $Id$ -# +# # See URI for documentation # diff --git a/lib/uri/common.rb b/lib/uri/common.rb index 827ed7883d..828b2b8a4a 100644 --- a/lib/uri/common.rb +++ b/lib/uri/common.rb @@ -2,7 +2,7 @@ # # Author:: Akira Yamada <[email protected]> # Revision:: $Id$ -# License:: +# License:: # You can redistribute it and/or modify it under the same term as Ruby. # @@ -34,7 +34,7 @@ module URI UNRESERVED = "-_.!~*'()#{ALNUM}" # reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | # "$" | "," - # reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | + # reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | # "$" | "," | "[" | "]" (RFC 2732) RESERVED = ";/?:@&=+$,\\[\\]" @@ -103,7 +103,7 @@ module URI # null uri when @regexp[:ABS_URI] - scheme, opaque, userinfo, host, port, + scheme, opaque, userinfo, host, port, registry, path, query, fragment = $~[1..-1] # URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ] @@ -119,19 +119,19 @@ module URI # server = [ [ userinfo "@" ] hostport ] if !scheme - raise InvalidURIError, + raise InvalidURIError, "bad URI(absolute but no scheme): #{uri}" end if !opaque && (!path && (!host && !registry)) raise InvalidURIError, - "bad URI(absolute but no path): #{uri}" + "bad URI(absolute but no path): #{uri}" end when @regexp[:REL_URI] scheme = nil opaque = nil - userinfo, host, port, registry, + userinfo, host, port, registry, rel_segment, abs_path, query, fragment = $~[1..-1] if rel_segment && abs_path path = rel_segment + abs_path @@ -158,7 +158,7 @@ module URI path = '' if !path && !opaque # (see RFC2396 Section 5.2) ret = [ - scheme, + scheme, userinfo, host, port, # X registry, # X path, # Y @@ -170,16 +170,16 @@ module URI end def parse(uri) - scheme, userinfo, host, port, + scheme, userinfo, host, port, registry, path, opaque, query, fragment = self.split(uri) if scheme && URI.scheme_list.include?(scheme.upcase) - URI.scheme_list[scheme.upcase].new(scheme, userinfo, host, port, - registry, path, opaque, query, + URI.scheme_list[scheme.upcase].new(scheme, userinfo, host, port, + registry, path, opaque, query, fragment, self) else - Generic.new(scheme, userinfo, host, port, - registry, path, opaque, query, + Generic.new(scheme, userinfo, host, port, + registry, path, opaque, query, fragment, self) end end @@ -457,7 +457,7 @@ module URI end end else - raise ArgumentError, + raise ArgumentError, "expected Array of or Hash of components of #{klass.to_s} (#{klass.component[1..-1].join(', ')})" end tmp[:scheme] = klass.to_s.sub(/\A.*::/, '').downcase @@ -538,7 +538,7 @@ module URI def self.scheme_list @@schemes end - + # # Base class for all URI exceptions. # @@ -579,7 +579,7 @@ module URI # * Opaque # * Query # * Fragment - # + # # == Usage # # require 'uri' @@ -604,7 +604,7 @@ module URI # == Description # # Creates one of the URI's subclasses instance from the string. - # + # # == Raises # # URI::InvalidURIError @@ -617,11 +617,11 @@ module 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" - # + # p uri.scheme + # # => "http" + # p uri.host + # # => "www.ruby-lang.org" + # def self.parse(uri) DEFAULT_PARSER.parse(uri) end @@ -658,7 +658,7 @@ module URI # # == Args # - # +str+:: + # +str+:: # String to extract URIs from. # +schemes+:: # Limit URI matching to a specific schemes. @@ -686,25 +686,25 @@ module URI # # == Args # - # +match_schemes+:: + # +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 $& diff --git a/lib/uri/ftp.rb b/lib/uri/ftp.rb index 3afdce01b4..a40b958497 100644 --- a/lib/uri/ftp.rb +++ b/lib/uri/ftp.rb @@ -17,12 +17,12 @@ module URI DEFAULT_PORT = 21 COMPONENT = [ - :scheme, + :scheme, :userinfo, :host, :port, :path, :typecode ].freeze # - # Typecode is "a", "i" or "d". + # Typecode is "a", "i" or "d". # # * "a" indicates a text file (the FTP command was ASCII) # * "i" indicates a binary file (FTP command IMAGE) @@ -31,7 +31,7 @@ module URI TYPECODE = ['a', 'i', 'd'].freeze TYPECODE_PREFIX = ';type='.freeze - def self.new2(user, password, host, port, path, + def self.new2(user, password, host, port, path, typecode = nil, arg_check = true) typecode = nil if typecode.size == 0 if typecode && !TYPECODE.include?(typecode) @@ -42,22 +42,22 @@ module URI # do escape self.new('ftp', - [user, password], - host, port, nil, - typecode ? path + TYPECODE_PREFIX + typecode : path, + [user, password], + host, port, nil, + typecode ? path + TYPECODE_PREFIX + typecode : path, nil, nil, nil, arg_check) end # # == Description # - # Creates a new URI::FTP object from components, with syntax checking. + # Creates a new URI::FTP object from components, with syntax checking. # - # The components accepted are +userinfo+, +host+, +port+, +path+ and + # The components accepted are +userinfo+, +host+, +port+, +path+ and # +typecode+. # - # The components should be provided either as an Array, or as a Hash - # with keys formed by preceding the component names with a colon. + # The components should be provided either as an Array, or as a Hash + # with keys formed by preceding the component names with a colon. # # If an Array is used, the components must be passed in the order # [userinfo, host, port, path, typecode] @@ -67,11 +67,11 @@ module URI # # require 'uri' # - # uri = URI::FTP.build(['user:password', 'ftp.example.com', nil, + # uri = URI::FTP.build(['user:password', 'ftp.example.com', nil, # '/path/file.> zip', 'i']) # puts uri.to_s -> ftp://user:[email protected]/%2Fpath/file.zip;type=a # - # uri2 = URI::FTP.build({:host => 'ftp.example.com', + # uri2 = URI::FTP.build({:host => 'ftp.example.com', # :path => 'ruby/src'}) # puts uri2.to_s -> ftp://ftp.example.com/ruby/src # @@ -92,7 +92,7 @@ module URI if tmp[:typecode] if tmp[:typecode].size == 1 - tmp[:typecode] = TYPECODE_PREFIX + tmp[:typecode] + tmp[:typecode] = TYPECODE_PREFIX + tmp[:typecode] end tmp[:path] << tmp[:typecode] end @@ -109,7 +109,7 @@ module URI # Unlike build(), this method does not escape the path component as # required by RFC1738; instead it is treated as per RFC2396. # - # Arguments are +scheme+, +userinfo+, +host+, +port+, +registry+, +path+, + # Arguments are +scheme+, +userinfo+, +host+, +port+, +registry+, +path+, # +opaque+, +query+ and +fragment+, in that order. # def initialize(*arg) @@ -119,7 +119,7 @@ module URI if tmp typecode = @path[tmp + TYPECODE_PREFIX.size..-1] self.set_path(@path[0..tmp - 1]) - + if arg[-1] self.typecode = typecode else @@ -164,9 +164,9 @@ module URI # RFC 1738 specifically states that the path for an FTP URI does not # include the / which separates the URI path from the URI host. Example: # - # ftp://ftp.example.com/pub/ruby + # ftp://ftp.example.com/pub/ruby # - # The above URI indicates that the client should connect to + # The above URI indicates that the client should connect to # ftp.example.com then cd pub/ruby from the initial login directory. # # If you want to cd to an absolute directory, you must include an diff --git a/lib/uri/generic.rb b/lib/uri/generic.rb index 65c6c7379d..adc3805265 100644 --- a/lib/uri/generic.rb +++ b/lib/uri/generic.rb @@ -9,7 +9,7 @@ require 'uri/common' module URI - + # # Base class for all URI classes. # Implements generic URI syntax as per RFC 2396. @@ -31,10 +31,10 @@ module URI end COMPONENT = [ - :scheme, - :userinfo, :host, :port, :registry, - :path, :opaque, - :query, + :scheme, + :userinfo, :host, :port, :registry, + :path, :opaque, + :query, :fragment ].freeze @@ -62,7 +62,7 @@ module URI # == Description # # At first, tries to create a new URI::Generic instance using - # URI::Generic::build. But, if exception URI::InvalidComponentError is raised, + # URI::Generic::build. But, if exception URI::InvalidComponentError is raised, # then it URI::Escape.escape all URI components and tries again. # # @@ -71,7 +71,7 @@ module URI return self.build(args) rescue InvalidComponentError if args.kind_of?(Array) - return self.build(args.collect{|x| + return self.build(args.collect{|x| if x @parser.escape(x) else @@ -117,7 +117,7 @@ module URI end end else - raise ArgumentError, + raise ArgumentError, "expected Array of or Hash of components of #{self.class} (#{self.class.component.join(', ')})" end @@ -155,10 +155,10 @@ module URI # # Creates a new URI::Generic instance from ``generic'' components without check. # - def initialize(scheme, - userinfo, host, port, registry, - path, opaque, - query, + def initialize(scheme, + userinfo, host, port, registry, + path, opaque, + query, fragment, parser = DEFAULT_PARSER, arg_check = false) @@ -196,10 +196,10 @@ module URI self.set_fragment(fragment) end if @registry && !self.class.use_registry - raise InvalidURIError, + 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 @@ -264,7 +264,7 @@ module URI def check_user(v) if @registry || @opaque - raise InvalidURIError, + raise InvalidURIError, "can not set user with registry or opaque" end @@ -281,7 +281,7 @@ module URI def check_password(v, user = @user) if @registry || @opaque - raise InvalidURIError, + raise InvalidURIError, "can not set password with registry or opaque" end return v unless v @@ -317,7 +317,7 @@ module URI set_user(user) # returns user end - + def password=(password) check_password(password) set_password(password) @@ -325,7 +325,7 @@ module URI end def set_userinfo(user, password = nil) - unless password + unless password user, password = split_userinfo(user) end @user = user @@ -382,7 +382,7 @@ module URI return v unless v if @registry || @opaque - raise InvalidURIError, + raise InvalidURIError, "can not set host with registry or opaque" elsif @parser.regexp[:HOST] !~ v raise InvalidComponentError, @@ -408,7 +408,7 @@ module URI return v unless v if @registry || @opaque - raise InvalidURIError, + raise InvalidURIError, "can not set port with registry or opaque" elsif !v.kind_of?(Fixnum) && @parser.regexp[:PORT] !~ v raise InvalidComponentError, @@ -444,7 +444,7 @@ module URI # authority = server | reg_name # server = [ [ userinfo "@" ] hostport ] if @host || @port || @user # userinfo = @user + ':' + @password - raise InvalidURIError, + raise InvalidURIError, "can not set registry with host, port, or userinfo" elsif v && @parser.regexp[:REGISTRY] !~ v raise InvalidComponentError, @@ -471,18 +471,18 @@ module URI # absoluteURI = scheme ":" ( hier_part | opaque_part ) # hier_part = ( net_path | abs_path ) [ "?" query ] if v && @opaque - raise InvalidURIError, + raise InvalidURIError, "path conflicts with opaque" end if @scheme if v && v != '' && @parser.regexp[:ABS_PATH] !~ v - raise InvalidComponentError, + raise InvalidComponentError, "bad component(expected absolute path component): #{v}" end else if v && v != '' && @parser.regexp[:ABS_PATH] !~ v && @parser.regexp[:REL_PATH] !~ v - raise InvalidComponentError, + raise InvalidComponentError, "bad component(expected relative path component): #{v}" end end @@ -509,12 +509,12 @@ module URI # absoluteURI = scheme ":" ( hier_part | opaque_part ) # hier_part = ( net_path | abs_path ) [ "?" query ] if @opaque - raise InvalidURIError, + raise InvalidURIError, "query conflicts with opaque" end if v && v != '' && @parser.regexp[:QUERY] !~ v - raise InvalidComponentError, + raise InvalidComponentError, "bad component(expected query component): #{v}" end @@ -540,7 +540,7 @@ module URI # absoluteURI = scheme ":" ( hier_part | opaque_part ) # hier_part = ( net_path | abs_path ) [ "?" query ] if @host || @port || @user || @path # userinfo = @user + ':' + @password - raise InvalidURIError, + raise InvalidURIError, "can not set opaque with host, port, userinfo or path" elsif v && @parser.regexp[:OPAQUE] !~ v raise InvalidComponentError, @@ -566,7 +566,7 @@ module URI return v unless v if v && v != '' && @parser.regexp[:FRAGMENT] !~ v - raise InvalidComponentError, + raise InvalidComponentError, "bad component(expected fragment component): #{v}" end @@ -784,12 +784,12 @@ module URI end if self.relative? && oth.relative? - raise BadURIError, + raise BadURIError, "both URI are relative" end if self.absolute? && oth.absolute? - #raise BadURIError, + #raise BadURIError, # "both URI are absolute" # hmm... should return oth for usability? return oth, oth @@ -810,7 +810,7 @@ module URI src_path = split_path(src) dst_path = split_path(dst) - # hmm... dst has abnormal absolute path, + # hmm... dst has abnormal absolute path, # like "/./", "/../", "/x/../", ... if dst_path.include?('..') || dst_path.include?('.') @@ -855,11 +855,11 @@ module URI end if self.relative? - raise BadURIError, + raise BadURIError, "relative URI: #{self}" end if oth.relative? - raise BadURIError, + raise BadURIError, "relative URI: #{oth}" end @@ -867,7 +867,7 @@ module URI return self, self.dup end rel = URI::Generic.new(nil, # it is relative URI - self.userinfo, self.host, self.port, + self.userinfo, self.host, self.port, self.registry, self.path, self.opaque, self.query, self.fragment, @parser) @@ -955,7 +955,7 @@ module 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> - # + # def route_to(oth) case oth when Generic @@ -971,7 +971,7 @@ module URI # # Returns normalized URI - # + # def normalize uri = dup uri.normalize! @@ -987,7 +987,7 @@ module URI end if host && host != host.downcase set_host(self.host.downcase) - end + end end def path_query @@ -1001,7 +1001,7 @@ module URI # # Constructs String from URI - # + # def to_s str = '' if @scheme @@ -1103,7 +1103,7 @@ module URI if component.include?(c) self.send(c) else - raise ArgumentError, + raise ArgumentError, "expected of components of #{self.class} (#{self.class.component.join(', ')})" end end diff --git a/lib/uri/http.rb b/lib/uri/http.rb index 87eb8893f2..69a7658918 100644 --- a/lib/uri/http.rb +++ b/lib/uri/http.rb @@ -14,18 +14,18 @@ module URI # The syntax of HTTP URIs is defined in RFC1738 section 3.3. # # Note that the Ruby URI library allows HTTP URLs containing usernames and - # passwords. This is not legal as per the RFC, but used to be - # supported in Internet Explorer 5 and 6, before the MS04-004 security + # passwords. This is not legal as per the RFC, but used to be + # supported in Internet Explorer 5 and 6, before the MS04-004 security # update. See <URL:http://support.microsoft.com/kb/834489>. # class HTTP < Generic DEFAULT_PORT = 80 COMPONENT = [ - :scheme, - :userinfo, :host, :port, - :path, - :query, + :scheme, + :userinfo, :host, :port, + :path, + :query, :fragment ].freeze @@ -37,21 +37,21 @@ module URI # The components accepted are userinfo, host, port, path, query and # fragment. # - # The components should be provided either as an Array, or as a Hash - # with keys formed by preceding the component names with a colon. + # The components should be provided either as an Array, or as a Hash + # with keys formed by preceding the component names with a colon. # # If an Array is used, the components must be passed in the order # [userinfo, host, port, path, query, fragment]. # # Example: # - # newuri = URI::HTTP.build({:host => 'www.example.com', + # newuri = URI::HTTP.build({:host => 'www.example.com', # :path> => '/foo/bar'}) # - # newuri = URI::HTTP.build([nil, "www.example.com", nil, "/path", + # newuri = URI::HTTP.build([nil, "www.example.com", nil, "/path", # "query", 'fragment']) # - # Currently, if passed userinfo components this method generates + # Currently, if passed userinfo components this method generates # invalid HTTP URIs as per RFC 1738. # def self.build(args) @@ -63,10 +63,10 @@ module URI # == Description # # Create a new URI::HTTP object from generic URI components as per - # RFC 2396. No HTTP-specific syntax checking (as per RFC 1738) is + # RFC 2396. No HTTP-specific syntax checking (as per RFC 1738) is # performed. # - # Arguments are +scheme+, +userinfo+, +host+, +port+, +registry+, +path+, + # Arguments are +scheme+, +userinfo+, +host+, +port+, +registry+, +path+, # +opaque+, +query+ and +fragment+, in that order. # # Example: diff --git a/lib/uri/ldap.rb b/lib/uri/ldap.rb index 163d2cda24..6739a018af 100644 --- a/lib/uri/ldap.rb +++ b/lib/uri/ldap.rb @@ -1,10 +1,10 @@ # # = uri/ldap.rb # -# Author:: +# Author:: # Takaaki Tateishi <[email protected]> # Akira Yamada <[email protected]> -# License:: +# 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$ @@ -21,7 +21,7 @@ module URI class LDAP < Generic DEFAULT_PORT = 389 - + COMPONENT = [ :scheme, :host, :port, diff --git a/lib/uri/mailto.rb b/lib/uri/mailto.rb index 38f972e1fb..4fab6e23a5 100644 --- a/lib/uri/mailto.rb +++ b/lib/uri/mailto.rb @@ -68,20 +68,20 @@ module URI # # If a Hash is used, the keys are the component names preceded by colons. # - # The headers can be supplied as a pre-encoded string, such as + # The headers can be supplied as a pre-encoded string, such as # "subject=subscribe&cc=address", or as an Array of Arrays like # [['subject', 'subscribe'], ['cc', 'address']] # # Examples: - # + # # require 'uri' - # + # # m1 = URI::MailTo.build(['[email protected]', 'subject=Ruby']) # puts m1.to_s -> mailto:[email protected]?subject=Ruby - # + # # m2 = URI::MailTo.build(['[email protected]', [['Subject', 'Ruby'], ['Cc', '[email protected]']]]) # puts m2.to_s -> mailto:[email protected]?Subject=Ruby&[email protected] - # + # # m3 = URI::MailTo.build({:to => '[email protected]', :headers => [['subject', 'subscribe']]}) # puts m3.to_s -> mailto:[email protected]?subject=subscribe # @@ -183,7 +183,7 @@ module URI return true unless v return true if v.size == 0 - if @parser.regexp[:OPAQUE] !~ v || + if @parser.regexp[:OPAQUE] !~ v || /\A(#{HEADER_PATTERN}(?:\&#{HEADER_PATTERN})*)\z/o !~ v raise InvalidComponentError, "bad component(expected opaque component): #{v}" @@ -210,12 +210,12 @@ module URI end def to_s - @scheme + ':' + - if @to + @scheme + ':' + + if @to @to else '' - end + + end + if @headers.size > 0 '?' + @headers.collect{|x| x.join('=')}.join('&') else @@ -227,7 +227,7 @@ module URI '' end end - + # Returns the RFC822 e-mail text equivalent of the URL, as a String. # # Example: diff --git a/lib/webrick/cgi.rb b/lib/webrick/cgi.rb index 7114651193..7099d14689 100644 --- a/lib/webrick/cgi.rb +++ b/lib/webrick/cgi.rb @@ -77,7 +77,7 @@ module WEBrick res.set_error(ex) rescue HTTPStatus::Status => ex res.status = ex.code - rescue Exception => ex + rescue Exception => ex @logger.error(ex) res.set_error(ex, true) ensure @@ -122,7 +122,7 @@ module WEBrick include Enumerable private - + def initialize(config, env, stdin, stdout) @config = config @env = env @@ -130,7 +130,7 @@ module WEBrick @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"] @@ -164,7 +164,7 @@ module WEBrick httpv = @config[:HTTPVersion] return "#{meth} #{url} HTTP/#{httpv}" end - + def setup_header @env.each{|key, value| case key @@ -175,7 +175,7 @@ module WEBrick end } end - + def add_header(hdrname, value) unless value.empty? @header_part << hdrname << ": " << value << CRLF @@ -185,21 +185,21 @@ module WEBrick def input @header_part.eof? ? @body_part : @header_part end - + public - + def peeraddr [nil, @remote_port, @remote_host, @remote_addr] end - + def addr [nil, @server_port, @server_name, @server_addr] end - + def gets(eol=LF, size=nil) input.gets(eol, size) end - + def read(size=nil) input.read(size) end @@ -211,7 +211,7 @@ module WEBrick def eof? input.eof? end - + def <<(data) @out_port << data end @@ -256,5 +256,5 @@ module WEBrick end end end - end -end + end +end diff --git a/lib/webrick/config.rb b/lib/webrick/config.rb index 121669c13a..946312e915 100644 --- a/lib/webrick/config.rb +++ b/lib/webrick/config.rb @@ -83,7 +83,7 @@ module WEBrick } DigestAuth = { - :Algorithm => 'MD5-sess', # or 'MD5' + :Algorithm => 'MD5-sess', # or 'MD5' :Domain => nil, # an array includes domain names. :Qop => [ 'auth' ], # 'auth' or 'auth-int' or both. :UseOpaque => true, diff --git a/lib/webrick/httpauth/authenticator.rb b/lib/webrick/httpauth/authenticator.rb index f90d1bf75b..d93f12a97a 100644 --- a/lib/webrick/httpauth/authenticator.rb +++ b/lib/webrick/httpauth/authenticator.rb @@ -25,7 +25,7 @@ module WEBrick unless config[sym] raise ArgumentError, "Argument #{sym.inspect} missing." end - } + } @realm = config[:Realm] @userdb = config[:UserDB] @logger = config[:Logger] || Log::new($stderr) @@ -40,8 +40,8 @@ module WEBrick def check_scheme(req) unless credentials = req[@request_field] error("no credentials in the request.") - return nil - end + return nil + end unless match = /^#{@auth_scheme}\s+/i.match(credentials) error("invalid scheme in %s.", credentials) info("%s: %s", @request_field, credentials) if $DEBUG @@ -60,7 +60,7 @@ module WEBrick if @logger.error? log(:error, fmt, *args) end - end + end def info(fmt, *args) if @logger.info? diff --git a/lib/webrick/httpauth/digestauth.rb b/lib/webrick/httpauth/digestauth.rb index eec064ca26..aac87a06df 100644 --- a/lib/webrick/httpauth/digestauth.rb +++ b/lib/webrick/httpauth/digestauth.rb @@ -118,16 +118,16 @@ module WEBrick } if !check_uri(req, auth_req) - raise HTTPStatus::BadRequest + raise HTTPStatus::BadRequest end - if auth_req['realm'] != @realm + if auth_req['realm'] != @realm error('%s: realm unmatch. "%s" for "%s"', auth_req['username'], auth_req['realm'], @realm) return false end - auth_req['algorithm'] ||= 'MD5' + auth_req['algorithm'] ||= 'MD5' if auth_req['algorithm'] != @algorithm && (@opera_hack && auth_req['algorithm'] != @algorithm.upcase) error('%s: algorithm unmatch. "%s" for "%s"', @@ -230,7 +230,7 @@ module WEBrick def split_param_value(string) ret = {} while string.bytesize != 0 - case string + case string when /^\s*([\w\-\.\*\%\!]+)=\s*\"((\\.|[^\"])*)\"\s*,?/ key = $1 matched = $2 @@ -320,7 +320,7 @@ module WEBrick uri = auth_req['uri'] if uri != req.request_uri.to_s && uri != req.unparsed_uri && (@internet_explorer_hack && uri != req.path) - error('%s: uri unmatch. "%s" for "%s"', auth_req['username'], + error('%s: uri unmatch. "%s" for "%s"', auth_req['username'], auth_req['uri'], req.request_uri.to_s) return false end diff --git a/lib/webrick/httpauth/userdb.rb b/lib/webrick/httpauth/userdb.rb index 33e01405f4..0285f89352 100644 --- a/lib/webrick/httpauth/userdb.rb +++ b/lib/webrick/httpauth/userdb.rb @@ -18,7 +18,7 @@ module WEBrick def set_passwd(realm, user, pass) self[user] = pass - end + end def get_passwd(realm, user, reload_db=false) # reload_db is dummy diff --git a/lib/webrick/httpproxy.rb b/lib/webrick/httpproxy.rb index f35a177777..ce99c55d8f 100644 --- a/lib/webrick/httpproxy.rb +++ b/lib/webrick/httpproxy.rb @@ -64,7 +64,7 @@ module WEBrick def proxy_service(req, res) # Proxy Authentication - proxy_auth(req, res) + proxy_auth(req, res) begin self.send("do_#{req.request_method}", req, res) @@ -81,7 +81,7 @@ module WEBrick handler.call(req, res) end end - + def do_CONNECT(req, res) # Proxy Authentication proxy_auth(req, res) @@ -264,7 +264,7 @@ module WEBrick http = Net::HTTP.new(uri.host, uri.port, upstream.host, upstream.port) http.start do if @config[:ProxyTimeout] - ################################## these issues are + ################################## these issues are http.open_timeout = 30 # secs # necessary (maybe bacause http.read_timeout = 60 # secs # Ruby's bug, but why?) ################################## diff --git a/lib/webrick/httprequest.rb b/lib/webrick/httprequest.rb index 3a8d744016..ff9b6d7849 100644 --- a/lib/webrick/httprequest.rb +++ b/lib/webrick/httprequest.rb @@ -304,7 +304,7 @@ module WEBrick end elsif self['content-length'] || @remaining_size @remaining_size ||= self['content-length'].to_i - while @remaining_size > 0 + while @remaining_size > 0 sz = [@buffer_size, @remaining_size].min break unless buf = read_data(socket, sz) @remaining_size -= buf.bytesize diff --git a/lib/webrick/httpresponse.rb b/lib/webrick/httpresponse.rb index 740a8fe921..98c4a357fa 100644 --- a/lib/webrick/httpresponse.rb +++ b/lib/webrick/httpresponse.rb @@ -201,10 +201,10 @@ module WEBrick def set_error(ex, backtrace=false) case ex - when HTTPStatus::Status + when HTTPStatus::Status @keep_alive = false if HTTPStatus::error?(ex.code) self.status = ex.code - else + else @keep_alive = false self.status = HTTPStatus::RC_INTERNAL_SERVER_ERROR end diff --git a/lib/webrick/httpserver.rb b/lib/webrick/httpserver.rb index 495be263b3..929d856a4a 100644 --- a/lib/webrick/httpserver.rb +++ b/lib/webrick/httpserver.rb @@ -36,12 +36,12 @@ module WEBrick [ $stderr, AccessLog::REFERER_LOG_FORMAT ] ] end - + @virtual_hosts = Array.new end def run(sock) - while true + while true res = HTTPResponse.new(@config) req = HTTPRequest.new(@config) server = self diff --git a/lib/webrick/httpservlet/cgihandler.rb b/lib/webrick/httpservlet/cgihandler.rb index f504f4d63b..ab36b906f1 100644 --- a/lib/webrick/httpservlet/cgihandler.rb +++ b/lib/webrick/httpservlet/cgihandler.rb @@ -1,11 +1,11 @@ -# +# # cgihandler.rb -- CGIHandler Class -# +# # Author: IPR -- Internet Programming with Ruby -- writers # Copyright (c) 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou # Copyright (c) 2002 Internet Programming with Ruby writers. All rights # reserved. -# +# # $IPR: cgihandler.rb,v 1.27 2003/03/21 19:56:01 gotoyuzo Exp $ require 'rbconfig' @@ -68,16 +68,16 @@ module WEBrick if errmsg.bytesize > 0 @logger.error("CGIHandler: #{@script_filename}:\n" + errmsg) end - 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]+/, 2) + raw_header, body = data.split(/^[\xd\xa]+/, 2) raise HTTPStatus::InternalServerError, "Premature end of script headers: #{@script_filename}" if body.nil? diff --git a/lib/webrick/httpservlet/erbhandler.rb b/lib/webrick/httpservlet/erbhandler.rb index 49792193ba..845db07169 100644 --- a/lib/webrick/httpservlet/erbhandler.rb +++ b/lib/webrick/httpservlet/erbhandler.rb @@ -1,11 +1,11 @@ -# +# # erbhandler.rb -- ERBHandler Class -# +# # Author: IPR -- Internet Programming with Ruby -- writers # Copyright (c) 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou # Copyright (c) 2002 Internet Programming with Ruby writers. All rights # reserved. -# +# # $IPR: erbhandler.rb,v 1.25 2003/02/24 19:25:31 gotoyuzo Exp $ require 'webrick/httpservlet/abstract.rb' diff --git a/lib/webrick/httpservlet/filehandler.rb b/lib/webrick/httpservlet/filehandler.rb index f1cc88bed9..1cac0cabe3 100644 --- a/lib/webrick/httpservlet/filehandler.rb +++ b/lib/webrick/httpservlet/filehandler.rb @@ -32,7 +32,7 @@ module WEBrick if not_modified?(req, res, mtime, res['etag']) res.body = '' raise HTTPStatus::NotModified - elsif req['range'] + elsif req['range'] make_partial_content(req, res, @local_path, st.size) raise HTTPStatus::PartialContent else @@ -402,7 +402,7 @@ module WEBrick res.body << "<A HREF=\"?M=#{d1}\">Last modified</A> " res.body << "<A HREF=\"?S=#{d1}\">Size</A>\n" res.body << "<HR>\n" - + list.unshift [ "..", File::mtime(local_path+"/.."), -1 ] list.each{ |name, time, size| if name == ".." @@ -420,7 +420,7 @@ module WEBrick } res.body << "</PRE><HR>" - res.body << <<-_end_of_html_ + res.body << <<-_end_of_html_ <ADDRESS> #{HTMLUtils::escape(@config[:ServerSoftware])}<BR> at #{req.host}:#{req.port} diff --git a/lib/webrick/httpservlet/prochandler.rb b/lib/webrick/httpservlet/prochandler.rb index 783cb27896..2be3c854c1 100644 --- a/lib/webrick/httpservlet/prochandler.rb +++ b/lib/webrick/httpservlet/prochandler.rb @@ -1,11 +1,11 @@ -# +# # prochandler.rb -- ProcHandler Class -# +# # Author: IPR -- Internet Programming with Ruby -- writers # Copyright (c) 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou # Copyright (c) 2002 Internet Programming with Ruby writers. All rights # reserved. -# +# # $IPR: prochandler.rb,v 1.7 2002/09/21 12:23:42 gotoyuzo Exp $ require 'webrick/httpservlet/abstract.rb' @@ -16,7 +16,7 @@ module WEBrick class ProcHandler < AbstractServlet def get_instance(server, *options) self - end + end def initialize(proc) @proc = proc diff --git a/lib/webrick/httpstatus.rb b/lib/webrick/httpstatus.rb index a4b42f5a90..d022ddb446 100644 --- a/lib/webrick/httpstatus.rb +++ b/lib/webrick/httpstatus.rb @@ -19,7 +19,7 @@ module WEBrick class Error < Status; end class ClientError < Error; end class ServerError < Error; end - + class EOFError < StandardError; end StatusMessage = { @@ -84,7 +84,7 @@ module WEBrick class #{err_name} < #{parent} def self.code() RC_#{var_name} end def self.reason_phrase() StatusMessage[code] end - def code() self::class::code end + def code() self::class::code end def reason_phrase() self::class::reason_phrase end alias to_i code end diff --git a/lib/webrick/httputils.rb b/lib/webrick/httputils.rb index f921364786..bed24e09dd 100644 --- a/lib/webrick/httputils.rb +++ b/lib/webrick/httputils.rb @@ -98,7 +98,7 @@ module WEBrick next if /^#/ =~ line line.chomp! mimetype, ext0 = line.split(/\s+/, 2) - next unless ext0 + next unless ext0 next if ext0.empty? ext0.split(/\s+/).each{ |ext| hash[ext] = mimetype } } @@ -216,7 +216,7 @@ module WEBrick super("") else @raw_header = EmptyRawHeader - @header = EmptyHeader + @header = EmptyHeader super(args.shift) unless args.empty? @next_data = self.class.new(*args) @@ -250,7 +250,7 @@ module WEBrick def append_data(data) tmp = self while tmp - unless tmp.next_data + unless tmp.next_data tmp.next_data = data break end @@ -317,7 +317,7 @@ module WEBrick if form_data.has_key?(key) form_data[key].append_data(data) else - form_data[key] = data + form_data[key] = data end end data = FormData.new diff --git a/lib/webrick/log.rb b/lib/webrick/log.rb index 5d4fd0a174..0ffa12dd96 100644 --- a/lib/webrick/log.rb +++ b/lib/webrick/log.rb @@ -72,7 +72,7 @@ module WEBrick end class Log < BasicLog - attr_accessor :time_format + attr_accessor :time_format def initialize(log_file=nil, level=nil) super(log_file, level) diff --git a/lib/webrick/server.rb b/lib/webrick/server.rb index d0b6f2b693..c4d23bd67b 100644 --- a/lib/webrick/server.rb +++ b/lib/webrick/server.rb @@ -157,7 +157,7 @@ module WEBrick begin sock = svr.accept sock.sync = true - Utils::set_non_blocking(sock) + Utils::set_non_blocking(sock) Utils::set_close_on_exec(sock) rescue Errno::ECONNRESET, Errno::ECONNABORTED, Errno::EPROTO, Errno::EINVAL => ex diff --git a/lib/webrick/ssl.rb b/lib/webrick/ssl.rb index 03bfdf4aa0..896206b483 100644 --- a/lib/webrick/ssl.rb +++ b/lib/webrick/ssl.rb @@ -2,7 +2,7 @@ # ssl.rb -- SSL/TLS enhancement for GenericServer # # Copyright (c) 2003 GOTOU Yuuzou All rights reserved. -# +# # $Id$ require 'webrick' @@ -41,7 +41,7 @@ module WEBrick case p when 0; $stderr.putc "." # BN_generate_prime when 1; $stderr.putc "+" # BN_generate_prime - when 2; $stderr.putc "*" # searching good 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, @@ -88,7 +88,7 @@ module WEBrick if @config[:SSLEnable] unless ssl_context @ssl_context = setup_ssl_context(@config) - @logger.info("\n" + @config[:SSLCertificate].to_text) + @logger.info("\n" + @config[:SSLCertificate].to_text) end listeners.collect!{|svr| ssvr = ::OpenSSL::SSL::SSLServer.new(svr, ssl_context) diff --git a/lib/webrick/utils.rb b/lib/webrick/utils.rb index f2ecfc19a8..dee9363441 100644 --- a/lib/webrick/utils.rb +++ b/lib/webrick/utils.rb @@ -86,13 +86,13 @@ module WEBrick RAND_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789" + - "abcdefghijklmnopqrstuvwxyz" + "abcdefghijklmnopqrstuvwxyz" def random_string(len) rand_max = RAND_CHARS.bytesize - ret = "" + ret = "" len.times{ ret << RAND_CHARS[rand(rand_max)] } - ret + ret end module_function :random_string diff --git a/lib/xmlrpc/base64.rb b/lib/xmlrpc/base64.rb index f9a21c703a..bfa8c0a2d5 100644 --- a/lib/xmlrpc/base64.rb +++ b/lib/xmlrpc/base64.rb @@ -9,19 +9,19 @@ Released under the same term of license as Ruby. = XMLRPC::Base64 == Description -This class is necessary for (('xmlrpc4r')) to determine that a string should -be transmitted base64-encoded and not as a raw-string. -You can use (({XMLRPC::Base64})) on the client and server-side as a +This class is necessary for (('xmlrpc4r')) to determine that a string should +be transmitted base64-encoded and not as a raw-string. +You can use (({XMLRPC::Base64})) on the client and server-side as a parameter and/or return-value. == Class Methods --- XMLRPC::Base64.new( str, state = :dec ) Creates a new (({XMLRPC::Base64})) instance with string ((|str|)) as the - internal string. When ((|state|)) is (({:dec})) it assumes that the - string ((|str|)) is not in base64 format (perhaps already decoded), - otherwise if ((|state|)) is (({:enc})) it decodes ((|str|)) + internal string. When ((|state|)) is (({:dec})) it assumes that the + string ((|str|)) is not in base64 format (perhaps already decoded), + otherwise if ((|state|)) is (({:enc})) it decodes ((|str|)) and stores it as the internal string. - + --- XMLRPC::Base64.decode( str ) Decodes string ((|str|)) with base64 and returns that value. @@ -40,7 +40,7 @@ parameter and/or return-value. module XMLRPC class Base64 - + def initialize(str, state = :dec) case state when :enc @@ -51,11 +51,11 @@ class Base64 raise ArgumentError, "wrong argument; either :enc or :dec" end end - + def decoded - @str + @str end - + def encoded Base64.encode(@str) end diff --git a/lib/xmlrpc/client.rb b/lib/xmlrpc/client.rb index 9d0a8bbaf0..65c9cd0c9c 100644 --- a/lib/xmlrpc/client.rb +++ b/lib/xmlrpc/client.rb @@ -26,7 +26,7 @@ Released under the same term of license as Ruby. or require "xmlrpc/client" - + server = XMLRPC::Client.new("www.ruby-lang.org", "/RPC2", 80) ok, param = server.call2("michael.add", 4, 5) if ok then @@ -40,14 +40,14 @@ or == Description Class (({XMLRPC::Client})) provides remote procedure calls to a XML-RPC server. After setting the connection-parameters with ((<XMLRPC::Client.new>)) which -creates a new (({XMLRPC::Client})) instance, you can execute a remote procedure +creates a new (({XMLRPC::Client})) instance, you can execute a remote procedure by sending the ((<call|XMLRPC::Client#call>)) or ((<call2|XMLRPC::Client#call2>)) -message to this new instance. The given parameters indicate which method to +message to this new instance. The given parameters indicate which method to call on the remote-side and of course the parameters for the remote procedure. == Class Methods --- XMLRPC::Client.new( host=nil, path=nil, port=nil, proxy_host=nil, proxy_port=nil, user=nil, password=nil, use_ssl=false, timeout =nil) - Creates an object which represents the remote XML-RPC server on the + Creates an object which represents the remote XML-RPC server on the given host ((|host|)). If the server is CGI-based, ((|path|)) is the path to the CGI-script, which will be called, otherwise (in the case of a standalone server) ((|path|)) should be (({"/RPC2"})). @@ -59,8 +59,8 @@ call on the remote-side and of course the parameters for the remote procedure. Default values for ((|host|)), ((|path|)) and ((|port|)) are 'localhost', '/RPC2' and '80' respectively using SSL '443'. - If ((|user|)) and ((|password|)) are given, each time a request is send, - a Authorization header is send. Currently only Basic Authentification is + If ((|user|)) and ((|password|)) are given, each time a request is send, + a Authorization header is send. Currently only Basic Authentification is implemented no Digest. If ((|use_ssl|)) is set to (({true})), comunication over SSL is enabled. @@ -76,9 +76,9 @@ call on the remote-side and of course the parameters for the remote procedure. : proxy Is of the form "host:port". - + : timeout - Defaults to 30. + Defaults to 30. --- XMLRPC::Client.new3( hash={} ) --- XMLRPC::Client.new_from_hash( hash={} ) @@ -97,10 +97,10 @@ call on the remote-side and of course the parameters for the remote procedure. == Instance Methods --- XMLRPC::Client#call( method, *args ) - Invokes the method named ((|method|)) with the parameters given by + Invokes the method named ((|method|)) with the parameters given by ((|args|)) on the XML-RPC server. - The parameter ((|method|)) is converted into a (({String})) and should - be a valid XML-RPC method-name. + The parameter ((|method|)) is converted into a (({String})) and should + be a valid XML-RPC method-name. Each parameter of ((|args|)) must be of one of the following types, where (({Hash})), (({Struct})) and (({Array})) can contain any of these listed ((:types:)): * (({Fixnum})), (({Bignum})) @@ -110,31 +110,31 @@ call on the remote-side and of course the parameters for the remote procedure. * (({Hash})), (({Struct})) * (({Array})) * (({Date})), (({Time})), (({XMLRPC::DateTime})) - * (({XMLRPC::Base64})) - * A Ruby object which class includes XMLRPC::Marshallable (only if Config::ENABLE_MARSHALLABLE is (({true}))). + * (({XMLRPC::Base64})) + * A Ruby object which class includes XMLRPC::Marshallable (only if Config::ENABLE_MARSHALLABLE is (({true}))). That object is converted into a hash, with one additional key/value pair "___class___" which contains the class name for restoring later that object. - - The method returns the return-value from the RPC - ((-stands for Remote Procedure Call-)). + + The method returns the return-value from the RPC + ((-stands for Remote Procedure Call-)). The type of the return-value is one of the above shown, only that a (({Bignum})) is only allowed when it fits in 32-bit and that a XML-RPC (('dateTime.iso8601')) type is always returned as - a ((<(({XMLRPC::DateTime}))|URL:datetime.html>)) object and + a ((<(({XMLRPC::DateTime}))|URL:datetime.html>)) object and a (({Struct})) is never returned, only a (({Hash})), the same for a (({Symbol})), where - always a (({String})) is returned. + always a (({String})) is returned. A (({XMLRPC::Base64})) is returned as a (({String})) from xmlrpc4r version 1.6.1 on. - - If the remote procedure returned a fault-structure, then a + + If the remote procedure returned a fault-structure, then a (({XMLRPC::FaultException})) exception is raised, which has two accessor-methods (({faultCode})) and (({faultString})) of type (({Integer})) and (({String})). --- XMLRPC::Client#call2( method, *args ) The difference between this method and ((<call|XMLRPC::Client#call>)) is, that this method do ((*not*)) raise a (({XMLRPC::FaultException})) exception. - The method returns an array of two values. The first value indicates if + The method returns an array of two values. The first value indicates if the second value is a return-value ((({true}))) or an object of type - (({XMLRPC::FaultException})). + (({XMLRPC::FaultException})). Both are explained in ((<call|XMLRPC::Client#call>)). Simple to remember: The "2" in "call2" denotes the number of values it returns. @@ -151,19 +151,19 @@ call on the remote-side and of course the parameters for the remote procedure. # => [7, -1] --- XMLRPC::Client#multicall2( *methods ) - Same as ((<XMLRPC::Client#multicall>)), but returns like ((<XMLRPC::Client#call2>)) two parameters + Same as ((<XMLRPC::Client#multicall>)), but returns like ((<XMLRPC::Client#call2>)) two parameters instead of raising an (({XMLRPC::FaultException})). --- XMLRPC::Client#proxy( prefix, *args ) Returns an object of class (({XMLRPC::Client::Proxy})), initialized with ((|prefix|)) and ((|args|)). A proxy object returned by this method behaves like ((<XMLRPC::Client#call>)), i.e. a call on that object will raise a - (({XMLRPC::FaultException})) when a fault-structure is returned by that call. + (({XMLRPC::FaultException})) when a fault-structure is returned by that call. --- XMLRPC::Client#proxy2( prefix, *args ) Almost the same like ((<XMLRPC::Client#proxy>)) only that a call on the returned (({XMLRPC::Client::Proxy})) object behaves like ((<XMLRPC::Client#call2>)), i.e. - a call on that object will return two parameters. + a call on that object will return two parameters. @@ -175,21 +175,21 @@ call on the remote-side and of course the parameters for the remote procedure. --- XMLRPC::Client#proxy_async(...) --- XMLRPC::Client#proxy2_async(...) In contrast to corresponding methods without "_async", these can be - called concurrently and use for each request a new connection, where the + called concurrently and use for each request a new connection, where the non-asynchronous counterparts use connection-alive (one connection for all requests) - if possible. + if possible. - Note, that you have to use Threads to call these methods concurrently. + Note, that you have to use Threads to call these methods concurrently. The following example calls two methods concurrently: - + Thread.new { p client.call_async("michael.add", 4, 5) } - + Thread.new { p client.call_async("michael.div", 7, 9) } - + --- XMLRPC::Client#timeout --- XMLRPC::Client#user @@ -200,12 +200,12 @@ call on the remote-side and of course the parameters for the remote procedure. --- XMLRPC::Client#user= (new_user) --- XMLRPC::Client#password= (new_password) Set the corresponding attributes. - + --- XMLRPC::Client#set_writer( writer ) Sets the XML writer to use for generating XML output. Should be an instance of a class from module (({XMLRPC::XMLWriter})). - If this method is not called, then (({XMLRPC::Config::DEFAULT_WRITER})) is used. + If this method is not called, then (({XMLRPC::Config::DEFAULT_WRITER})) is used. --- XMLRPC::Client#set_parser( parser ) Sets the XML parser to use for parsing XML documents. @@ -220,7 +220,7 @@ call on the remote-side and of course the parameters for the remote procedure. Set extra HTTP headers that are included in the request. --- XMLRPC::Client#http_header_extra - Access the via ((<XMLRPC::Client#http_header_extra=>)) assigned header. + Access the via ((<XMLRPC::Client#http_header_extra=>)) assigned header. --- XMLRPC::Client#http_last_response Returns the (({Net::HTTPResponse})) object of the last RPC. @@ -240,31 +240,31 @@ call on the remote-side and of course the parameters for the remote procedure. == Description Class (({XMLRPC::Client::Proxy})) makes XML-RPC calls look nicer! -You can call any method onto objects of that class - the object handles +You can call any method onto objects of that class - the object handles (({method_missing})) and will forward the method call to a XML-RPC server. Don't use this class directly, but use instead method ((<XMLRPC::Client#proxy>)) or ((<XMLRPC::Client#proxy2>)). == Class Methods ---- XMLRPC::Client::Proxy.new( server, prefix, args=[], meth=:call, delim="." ) +--- XMLRPC::Client::Proxy.new( server, prefix, args=[], meth=:call, delim="." ) Creates an object which provides (({method_missing})). ((|server|)) must be of type (({XMLRPC::Client})), which is the XML-RPC server to be used for a XML-RPC call. ((|prefix|)) and ((|delim|)) will be prepended to the methodname - called onto this object. + called onto this object. Parameter ((|meth|)) is the method (call, call2, call_async, call2_async) to use for a RPC. ((|args|)) are arguments which are automatically given to every XML-RPC call before the arguments provides through (({method_missing})). - + == Instance Methods Every method call is forwarded to the XML-RPC server defined in ((<new|XMLRPC::Client::Proxy#new>)). - + Note: Inherited methods from class (({Object})) cannot be used as XML-RPC names, because they get around -(({method_missing})). - +(({method_missing})). + = History @@ -283,7 +283,7 @@ require "net/http" module XMLRPC class Client - + USER_AGENT = "XMLRPC::Client (Ruby #{RUBY_VERSION})" include ParserWriterChooseMixin @@ -292,11 +292,11 @@ module XMLRPC # Constructors ------------------------------------------------------------------- - def initialize(host=nil, path=nil, port=nil, proxy_host=nil, proxy_port=nil, + 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 + @http_last_response = nil @cookie = nil @host = host || "localhost" @@ -325,7 +325,7 @@ module XMLRPC # HTTP object for synchronous calls Net::HTTP.version_1_2 - @http = Net::HTTP.new(@host, @port, @proxy_host, @proxy_port) + @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 @@ -341,7 +341,7 @@ module XMLRPC if match = /^([^:]+):\/\/(([^@]+)@)?([^\/]+)(\/.*)?$/.match(uri) proto = match[1] user, passwd = (match[3] || "").split(":") - host, port = match[4].split(":") + host, port = match[4].split(":") path = match[5] if proto != "http" and proto != "https" @@ -351,7 +351,7 @@ module XMLRPC 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) @@ -384,7 +384,7 @@ module XMLRPC # Cookie support attr_accessor :cookie - + attr_reader :timeout, :user, :password @@ -407,13 +407,13 @@ module XMLRPC # Call methods -------------------------------------------------------------- def call(method, *args) - ok, param = call2(method, *args) + ok, param = call2(method, *args) if ok param else raise param end - end + end def call2(method, *args) request = create().methodCall(method, *args) @@ -422,13 +422,13 @@ module XMLRPC end def call_async(method, *args) - ok, param = call2_async(method, *args) + ok, param = call2_async(method, *args) if ok param else raise param end - end + end def call2_async(method, *args) request = create().methodCall(method, *args) @@ -467,7 +467,7 @@ module XMLRPC # Proxy generating methods ------------------------------------------ - + def proxy(prefix=nil, *args) Proxy.new(self, prefix, args, :call) end @@ -498,10 +498,10 @@ module XMLRPC end def do_rpc(request, async=false) - header = { + header = { "User-Agent" => USER_AGENT, "Content-Type" => "text/xml; charset=utf-8", - "Content-Length" => request.size.to_s, + "Content-Length" => request.size.to_s, "Connection" => (async ? "close" : "keep-alive") } @@ -512,41 +512,41 @@ module XMLRPC # add authorization header header["Authorization"] = @auth end - + resp = nil @http_last_response = nil if async - # use a new HTTP object for each call + # use a new HTTP object for each call Net::HTTP.version_1_2 - http = Net::HTTP.new(@host, @port, @proxy_host, @proxy_port) + 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 - + # post request http.start { - resp = http.post2(@path, request, header) + resp = http.post2(@path, request, header) } else # reuse the HTTP object for each call => connection alive is possible # we must start connection explicitely first time so that http.request # does not assume that we don't want keepalive @http.start if not @http.started? - + # post request - resp = @http.post2(@path, request, header) + resp = @http.post2(@path, request, header) end - + @http_last_response = resp data = resp.body if resp.code == "401" # Authorization Required - raise "Authorization failed.\nHTTP-Error: #{resp.code} #{resp.message}" + raise "Authorization failed.\nHTTP-Error: #{resp.code} #{resp.message}" elsif resp.code[0,1] != "2" - raise "HTTP-Error: #{resp.code} #{resp.message}" + raise "HTTP-Error: #{resp.code} #{resp.message}" end ct = parse_content_type(resp["Content-Type"]).first @@ -559,8 +559,8 @@ module XMLRPC end expected = resp["Content-Length"] || "<unknown>" - if data.nil? or data.size == 0 - raise "Wrong size. Was #{data.size}, should be #{expected}" + if data.nil? or data.size == 0 + raise "Wrong size. Was #{data.size}, should be #{expected}" elsif expected != "<unknown>" and expected.to_i != data.size and resp["Transfer-Encoding"].nil? raise "Wrong size. Was #{data.size}, should be #{expected}" end @@ -581,11 +581,11 @@ module XMLRPC meth = :call2 meth = :call2_async if async - ok, params = self.send(meth, "system.multicall", + ok, params = self.send(meth, "system.multicall", methods.collect {|m| {'methodName' => m[0], 'params' => m[1..-1]} } ) - if ok + if ok params = params.collect do |param| if param.is_a? Array param[0] @@ -593,7 +593,7 @@ module XMLRPC XMLRPC::FaultException.new(param["faultCode"], param["faultString"]) else raise "Wrong multicall return value" - end + end end end @@ -607,7 +607,7 @@ module XMLRPC def initialize(server, prefix, args=[], meth=:call, delim=".") @server = server @prefix = prefix ? prefix + delim : "" - @args = args + @args = args @meth = meth end diff --git a/lib/xmlrpc/config.rb b/lib/xmlrpc/config.rb index c4d2c41aac..34c3bbaf1b 100644 --- a/lib/xmlrpc/config.rb +++ b/lib/xmlrpc/config.rb @@ -8,7 +8,7 @@ module XMLRPC module Config DEFAULT_WRITER = XMLWriter::Simple # or XMLWriter::XMLParser - + # available parser: # * XMLParser::NQXMLTreeParser # * XMLParser::NQXMLStreamParser @@ -21,16 +21,16 @@ module XMLRPC # enable <nil/> tag ENABLE_NIL_CREATE = false ENABLE_NIL_PARSER = false - + # allows integers greater than 32-bit if true ENABLE_BIGINT = false # enable marshalling ruby objects which include XMLRPC::Marshallable - ENABLE_MARSHALLING = true + ENABLE_MARSHALLING = true # enable multiCall extension by default ENABLE_MULTICALL = false - + # enable Introspection extension by default ENABLE_INTROSPECTION = false diff --git a/lib/xmlrpc/create.rb b/lib/xmlrpc/create.rb index 530d229f66..2d38a44b30 100644 --- a/lib/xmlrpc/create.rb +++ b/lib/xmlrpc/create.rb @@ -1,6 +1,6 @@ # # Creates XML-RPC call/response documents -# +# # Copyright (C) 2001, 2002, 2003 by Michael Neumann ([email protected]) # # $Id$ @@ -41,7 +41,7 @@ module XMLRPC def element(name, attrs, *children) raise "attributes not yet implemented" unless attrs.nil? if children.empty? - "<#{name}/>" + "<#{name}/>" else "<#{name}>" + children.join("") + "</#{name}>" end @@ -69,7 +69,7 @@ module XMLRPC end def document(*params) - XML::SimpleTree::Document.new(*params) + XML::SimpleTree::Document.new(*params) end def pi(name, *params) @@ -120,9 +120,9 @@ module XMLRPC tree = @writer.document( @writer.pi("xml", 'version="1.0"'), - @writer.ele("methodCall", + @writer.ele("methodCall", @writer.tag("methodName", name), - @writer.ele("params", *parameter) + @writer.ele("params", *parameter) ) ) @@ -137,29 +137,29 @@ module XMLRPC # 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 + # + # if is_ret == true then a normal # return-value of all the given params is created. # def methodResponse(is_ret, *params) - if is_ret + 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 + 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.ele("methodResponse", resp) ) @writer.document_to_str(tree) + "\n" @@ -178,7 +178,7 @@ module XMLRPC def conv2value(param) val = case param - when Fixnum + when Fixnum @writer.tag("i4", param.to_s) when Bignum @@ -194,10 +194,10 @@ module XMLRPC when TrueClass, FalseClass @writer.tag("boolean", param ? "1" : "0") - when Symbol + when Symbol @writer.tag("string", param.to_s) - when String + when String @writer.tag("string", param) when NilClass @@ -211,51 +211,51 @@ module XMLRPC @writer.tag("double", param.to_s) when Struct - h = param.members.collect do |key| + h = param.members.collect do |key| value = param[key] - @writer.ele("member", + @writer.ele("member", @writer.tag("name", key.to_s), - conv2value(value) + conv2value(value) ) end - @writer.ele("struct", *h) + @writer.ele("struct", *h) when Hash # TODO: can a Hash be empty? - + h = param.collect do |key, value| - @writer.ele("member", + @writer.ele("member", @writer.tag("name", key.to_s), - conv2value(value) + conv2value(value) ) end - @writer.ele("struct", *h) + @writer.ele("struct", *h) when Array # TODO: can an Array be empty? a = param.collect {|v| conv2value(v) } - - @writer.ele("array", + + @writer.ele("array", @writer.ele("data", *a) ) when Time, Date, ::DateTime - @writer.tag("dateTime.iso8601", param.strftime("%Y%m%dT%H:%M:%S")) + @writer.tag("dateTime.iso8601", param.strftime("%Y%m%dT%H:%M:%S")) when XMLRPC::DateTime - @writer.tag("dateTime.iso8601", + @writer.tag("dateTime.iso8601", format("%.4d%02d%02dT%02d:%02d:%02d", *param.to_a)) - + when XMLRPC::Base64 - @writer.tag("base64", param.encoded) + @writer.tag("base64", param.encoded) - else + else if Config::ENABLE_MARSHALLING and param.class.included_modules.include? XMLRPC::Marshallable # convert Ruby object into Hash ret = {"___class___" => param.class.name} - param.instance_variables.each {|v| + param.instance_variables.each {|v| name = v[1..-1] val = param.instance_variable_get(v) @@ -266,16 +266,16 @@ module XMLRPC end } return conv2value(ret) - else + else ok, pa = wrong_type(param) if ok return conv2value(pa) - else + else raise "Wrong type!" end end end - + @writer.ele("value", val) end @@ -283,7 +283,7 @@ module XMLRPC false end - + end # class Create end # module XMLRPC diff --git a/lib/xmlrpc/datetime.rb b/lib/xmlrpc/datetime.rb index f66ef8963a..d6c80a2cb9 100644 --- a/lib/xmlrpc/datetime.rb +++ b/lib/xmlrpc/datetime.rb @@ -10,19 +10,19 @@ Released under the same term of license as Ruby. = XMLRPC::DateTime == Description This class is important to handle XMLRPC (('dateTime.iso8601')) values, -correcly, because normal UNIX-dates (class (({Date}))) only handle dates +correcly, because normal UNIX-dates (class (({Date}))) only handle dates from year 1970 on, and class (({Time})) handles dates without the time -component. (({XMLRPC::DateTime})) is able to store a XMLRPC +component. (({XMLRPC::DateTime})) is able to store a XMLRPC (('dateTime.iso8601')) value correctly. == Class Methods --- XMLRPC::DateTime.new( year, month, day, hour, min, sec ) Creates a new (({XMLRPC::DateTime})) instance with the - parameters ((|year|)), ((|month|)), ((|day|)) as date and + parameters ((|year|)), ((|month|)), ((|day|)) as date and ((|hour|)), ((|min|)), ((|sec|)) as time. Raises (({ArgumentError})) if a parameter is out of range, or ((|year|)) is not of type (({Integer})). - + == Instance Methods --- XMLRPC::DateTime#year --- XMLRPC::DateTime#month @@ -50,7 +50,7 @@ component. (({XMLRPC::DateTime})) is able to store a XMLRPC --- XMLRPC::DateTime#to_time Return a (({Time})) object of the date/time which (({self})) represents. - If the (('year')) is below 1970, this method returns (({nil})), + If the (('year')) is below 1970, this method returns (({nil})), because (({Time})) cannot handle years below 1970. The used timezone is GMT. @@ -68,7 +68,7 @@ require "date" module XMLRPC class DateTime - + attr_reader :year, :month, :day, :hour, :min, :sec def year= (value) @@ -102,14 +102,14 @@ class DateTime end alias mon month - alias mon= month= - + alias mon= month= + 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 - + def to_time if @year >= 1970 Time.gm(*to_a) diff --git a/lib/xmlrpc/httpserver.rb b/lib/xmlrpc/httpserver.rb index 020e6cbcd9..66d52139db 100644 --- a/lib/xmlrpc/httpserver.rb +++ b/lib/xmlrpc/httpserver.rb @@ -1,7 +1,7 @@ # -# Implements a simple HTTP-server by using John W. Small's ([email protected]) +# Implements a simple HTTP-server by using John W. Small's ([email protected]) # ruby-generic-server. -# +# # Copyright (C) 2001, 2002, 2003 by Michael Neumann ([email protected]) # # $Id$ @@ -14,8 +14,8 @@ class HttpServer < GServer ## # handle_obj specifies the object, that receives calls to request_handler - # and ip_auth_handler - def initialize(handle_obj, port = 8080, host = DEFAULT_HOST, maxConnections = 4, + # and ip_auth_handler + 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) @@ -24,7 +24,7 @@ class HttpServer < GServer private # Constants ----------------------------------------------- - + CRLF = "\r\n" HTTP_PROTO = "HTTP/1.0" SERVER_NAME = "HttpServer (Ruby #{RUBY_VERSION})" @@ -46,27 +46,27 @@ private } # Classes ------------------------------------------------- - + class Request attr_reader :data, :header, :method, :path, :proto - + def initialize(data, method=nil, path=nil, proto=nil) @header, @data = Table.new, data @method, @path, @proto = method, path, proto end - + def content_length len = @header['Content-Length'] return nil if len.nil? - return len.to_i + return len.to_i end - + end - + class Response attr_reader :header attr_accessor :body, :status, :status_message - + def initialize(status=200) @status = status @status_message = nil @@ -82,7 +82,7 @@ private include Enumerable def initialize(hash={}) - @hash = hash + @hash = hash update(hash) end @@ -113,7 +113,7 @@ private def http_header(header=nil) new_header = Table.new(DEFAULT_HEADER) - new_header.update(header) unless header.nil? + new_header.update(header) unless header.nil? new_header["Connection"] = "close" new_header["Date"] = http_date(Time.now) @@ -127,7 +127,7 @@ private def http_resp(status_code, status_message=nil, header=nil, body=nil) status_message ||= StatusCodeMapping[status_code] - + str = "" str << "#{HTTP_PROTO} #{status_code} #{status_message}" << CRLF http_header(header).writeTo(str) @@ -137,8 +137,8 @@ private end # Main Serve Loop ----------------------------------------- - - def serve(io) + + def serve(io) # perform IP authentification unless @handler.ip_auth_handler(io) io << http_resp(403, "Forbidden") @@ -149,10 +149,10 @@ private if io.gets =~ /^(\S+)\s+(\S+)\s+(\S+)/ request = Request.new(io, $1, $2, $3) else - io << http_resp(400, "Bad Request") + io << http_resp(400, "Bad Request") return end - + # parse HTTP headers while (line=io.gets) !~ /^(\n|\r)/ if line =~ /^([\w-]+):\s*(.*)$/ @@ -160,15 +160,15 @@ private end end - io.binmode + io.binmode response = Response.new # execute request handler @handler.request_handler(request, response) - + # write response back to the client io << http_resp(response.status, response.status_message, - response.header, response.body) + response.header, response.body) rescue Exception => e io << http_resp(500, "Internal Server Error") diff --git a/lib/xmlrpc/marshal.rb b/lib/xmlrpc/marshal.rb index 26510124c2..d121828312 100644 --- a/lib/xmlrpc/marshal.rb +++ b/lib/xmlrpc/marshal.rb @@ -1,6 +1,6 @@ # # Marshalling of XML-RPC methodCall and methodResponse -# +# # Copyright (C) 2001, 2002, 2003 by Michael Neumann ([email protected]) # # $Id$ @@ -17,7 +17,7 @@ module XMLRPC include ParserWriterChooseMixin # class methods ------------------------------- - + class << self def dump_call( methodName, *params ) @@ -52,7 +52,7 @@ module XMLRPC create.methodCall( methodName, *params ) end - def dump_response( param ) + def dump_response( param ) create.methodResponse( ! param.kind_of?( XMLRPC::FaultException ) , param ) end diff --git a/lib/xmlrpc/parser.rb b/lib/xmlrpc/parser.rb index 2cf0530c9f..d078de2f4b 100644 --- a/lib/xmlrpc/parser.rb +++ b/lib/xmlrpc/parser.rb @@ -1,6 +1,6 @@ # # Parser for XML-RPC call and response -# +# # Copyright (C) 2001, 2002, 2003 by Michael Neumann ([email protected]) # # $Id$ @@ -60,7 +60,7 @@ module XMLRPC @faultCode = faultCode @faultString = faultString end - + # returns a hash def to_h {"faultCode" => @faultCode, "faultString" => @faultString} @@ -77,7 +77,7 @@ module XMLRPC when "0" then false when "1" then true else - raise "RPC-value of type boolean is wrong" + raise "RPC-value of type boolean is wrong" end end @@ -122,7 +122,7 @@ module XMLRPC def self.struct(hash) # convert to marhalled object klass = hash["___class___"] - if klass.nil? or Config::ENABLE_MARSHALLING == false + if klass.nil? or Config::ENABLE_MARSHALLING == false hash else begin @@ -130,9 +130,9 @@ module XMLRPC klass.split("::").each {|const| mod = mod.const_get(const.strip)} obj = mod.allocate - + hash.delete "___class___" - hash.each {|key, value| + hash.each {|key, value| obj.instance_variable_set("@#{ key }", value) if key =~ /^([\w_][\w_0-9]*)$/ } obj @@ -143,11 +143,11 @@ module XMLRPC end def self.fault(hash) - if hash.kind_of? Hash and hash.size == 2 and - hash.has_key? "faultCode" and hash.has_key? "faultString" and + 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"]) + XMLRPC::FaultException.new(hash["faultCode"], hash["faultString"]) else raise "wrong fault-structure: #{hash.inspect}" end @@ -182,9 +182,9 @@ module XMLRPC # TODO: add nil? unless %w(i4 int boolean string double dateTime.iso8601 base64).include? node.nodeName - if node.nodeName == "value" + if node.nodeName == "value" if not node.childNodes.to_a.detect {|n| _nodeType(n) == :ELEMENT}.nil? - remove << nd if nd.nodeValue.strip == "" + remove << nd if nd.nodeValue.strip == "" end else remove << nd if nd.nodeValue.strip == "" @@ -194,7 +194,7 @@ module XMLRPC remove << nd else removeWhitespacesAndComments(nd) - end + end end remove.each { |i| node.removeChild(i) } @@ -203,13 +203,13 @@ module XMLRPC def nodeMustBe(node, name) cmp = case name - when Array + when Array name.include?(node.nodeName) when String name == node.nodeName else raise "error" - end + end if not cmp then raise "wrong xml-rpc (name)" @@ -233,7 +233,7 @@ module XMLRPC def assert(b) if not b then - raise "assert-fail" + raise "assert-fail" end end @@ -249,21 +249,21 @@ module XMLRPC raise "wrong xml-rpc (size)" end end - + def integer(node) #TODO: check string for float because to_i returnsa # 0 when wrong string - nodeMustBe(node, %w(i4 int)) + nodeMustBe(node, %w(i4 int)) hasOnlyOneChild(node) - + Convert.int(text(node.firstChild)) end def boolean(node) - nodeMustBe(node, "boolean") + nodeMustBe(node, "boolean") hasOnlyOneChild(node) - + Convert.boolean(text(node.firstChild)) end @@ -274,36 +274,36 @@ module XMLRPC end def string(node) - nodeMustBe(node, "string") + nodeMustBe(node, "string") text_zero_one(node) end def double(node) #TODO: check string for float because to_f returnsa # 0.0 when wrong string - nodeMustBe(node, "double") + nodeMustBe(node, "double") hasOnlyOneChild(node) - + Convert.double(text(node.firstChild)) end def dateTime(node) nodeMustBe(node, "dateTime.iso8601") hasOnlyOneChild(node) - + Convert.dateTime( text(node.firstChild) ) end def base64(node) nodeMustBe(node, "base64") #hasOnlyOneChild(node) - + Convert.base64(text_zero_one(node)) end def member(node) nodeMustBe(node, "member") - assert( node.childNodes.to_a.size == 2 ) + assert( node.childNodes.to_a.size == 2 ) [ name(node[0]), value(node[1]) ] end @@ -311,13 +311,13 @@ module XMLRPC def name(node) nodeMustBe(node, "name") #hasOnlyOneChild(node) - text_zero_one(node) + text_zero_one(node) end def array(node) nodeMustBe(node, "array") - hasOnlyOneChild(node, "data") - data(node.firstChild) + hasOnlyOneChild(node, "data") + data(node.firstChild) end def data(node) @@ -325,15 +325,15 @@ module XMLRPC node.childNodes.to_a.collect do |val| value(val) - end + end end def param(node) nodeMustBe(node, "param") hasOnlyOneChild(node, "value") - value(node.firstChild) + value(node.firstChild) end - + def methodResponse(node) nodeMustBe(node, "methodResponse") hasOnlyOneChild(node, %w(params fault)) @@ -341,7 +341,7 @@ module XMLRPC case child.nodeName when "params" - [ true, params(child,false) ] + [ true, params(child,false) ] when "fault" [ false, fault(child) ] else @@ -353,13 +353,13 @@ module XMLRPC def methodName(node) nodeMustBe(node, "methodName") hasOnlyOneChild(node) - text(node.firstChild) + text(node.firstChild) end def params(node, call=true) nodeMustBe(node, "params") - if call + if call node.childNodes.to_a.collect do |n| param(n) end @@ -372,7 +372,7 @@ module XMLRPC def fault(node) nodeMustBe(node, "fault") hasOnlyOneChild(node, "value") - f = value(node.firstChild) + f = value(node.firstChild) Convert.fault(f) end @@ -388,13 +388,13 @@ module XMLRPC end def struct(node) - nodeMustBe(node, "struct") + nodeMustBe(node, "struct") hash = {} node.childNodes.to_a.each do |me| - n, v = member(me) + n, v = member(me) hash[n] = v - end + end Convert.struct(hash) end @@ -403,9 +403,9 @@ module XMLRPC def value(node) nodeMustBe(node, "value") nodes = node.childNodes.to_a.size - if nodes == 0 + if nodes == 0 return "" - elsif nodes > 1 + elsif nodes > 1 raise "wrong xml-rpc (size)" end @@ -423,14 +423,14 @@ module XMLRPC when "dateTime.iso8601" then dateTime(child) when "base64" then base64(child) when "struct" then struct(child) - when "array" then array(child) - when "nil" + when "array" then array(child) + when "nil" if Config::ENABLE_NIL_PARSER v_nil(child) else raise "wrong/unknown XML-RPC type 'nil'" end - else + else raise "wrong/unknown XML-RPC type" end else @@ -441,7 +441,7 @@ module XMLRPC def methodCall(node) nodeMustBe(node, "methodCall") - assert( (1..2).include?( node.childNodes.to_a.size ) ) + assert( (1..2).include?( node.childNodes.to_a.size ) ) name = methodName(node[0]) if node.childNodes.to_a.size == 2 then @@ -461,7 +461,7 @@ module XMLRPC raise "No valid method response!" if parser.method_name != nil if parser.fault != nil # is a fault structure - [false, parser.fault] + [false, parser.fault] else # is a normal return value raise "Missing return value!" if parser.params.size == 0 @@ -508,7 +508,7 @@ module XMLRPC @value = nil when "nil" raise "wrong/unknown XML-RPC type 'nil'" unless Config::ENABLE_NIL_PARSER - @value = :nil + @value = :nil when "array" @val_stack << @values @values = [] @@ -517,7 +517,7 @@ module XMLRPC @name = [] @structs << @struct - @struct = {} + @struct = {} end end @@ -538,7 +538,7 @@ module XMLRPC @value = Convert.base64(@data) when "value" @value = @data if @value.nil? - @values << (@value == :nil ? nil : @value) + @values << (@value == :nil ? nil : @value) when "array" @value = @values @values = @val_stack.pop @@ -548,9 +548,9 @@ module XMLRPC @name = @names.pop @struct = @structs.pop when "name" - @name[0] = @data + @name[0] = @data when "member" - @struct[@name[0]] = @values.pop + @struct[@name[0]] = @values.pop when "param" @params << @values[0] @@ -560,7 +560,7 @@ module XMLRPC @fault = Convert.fault(@values[0]) when "methodName" - @method_name = @data + @method_name = @data end @data = nil @@ -592,7 +592,7 @@ module XMLRPC @parser_class = XMLRPCParser end - class XMLRPCParser + class XMLRPCParser include StreamParserMixin def parse(str) @@ -620,9 +620,9 @@ module XMLRPC def initialize require "xmltreebuilder" - # The new XMLParser library (0.6.2+) uses a slightly different DOM implementation. + # 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 + 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) @@ -637,8 +637,8 @@ module XMLRPC def _nodeType(node) tp = node.nodeType if tp == XML::SimpleTree::Node::TEXT then :TEXT - elsif tp == XML::SimpleTree::Node::COMMENT then :COMMENT - elsif tp == XML::SimpleTree::Node::ELEMENT then :ELEMENT + elsif tp == XML::SimpleTree::Node::COMMENT then :COMMENT + elsif tp == XML::SimpleTree::Node::ELEMENT then :ELEMENT else :ELSE end end @@ -647,14 +647,14 @@ module XMLRPC def methodResponse_document(node) assert( node.nodeType == XML::SimpleTree::Node::DOCUMENT ) hasOnlyOneChild(node, "methodResponse") - + methodResponse(node.firstChild) end def methodCall_document(node) assert( node.nodeType == XML::SimpleTree::Node::DOCUMENT ) hasOnlyOneChild(node, "methodCall") - + methodCall(node.firstChild) end @@ -688,7 +688,7 @@ module XMLRPC end def createCleanedTree(str) - doc = ::NQXML::TreeParser.new(str).document.rootNode + doc = ::NQXML::TreeParser.new(str).document.rootNode removeWhitespacesAndComments(doc) doc end @@ -701,7 +701,7 @@ module XMLRPC @parser_class = StreamListener end - class StreamListener + class StreamListener include StreamParserMixin alias :tag_start :startElement @@ -716,7 +716,7 @@ module XMLRPC def parse(str) parser = REXML::Document.parse_stream(str, self) end - end + end end # --------------------------------------------------------------------------- @@ -751,7 +751,7 @@ module XMLRPC startElement(name) endElement(name) end - + def on_chardata(str) character(str) end @@ -784,7 +784,7 @@ module XMLRPC # valid_name? # valid_chardata? # valid_char? - # parse_error + # parse_error end end @@ -792,8 +792,8 @@ module XMLRPC XMLParser = XMLTreeParser NQXMLParser = NQXMLTreeParser - Classes = [XMLStreamParser, XMLTreeParser, - NQXMLStreamParser, NQXMLTreeParser, + Classes = [XMLStreamParser, XMLTreeParser, + NQXMLStreamParser, NQXMLTreeParser, REXMLStreamParser, XMLScanStreamParser] # yields an instance of each installed parser diff --git a/lib/xmlrpc/server.rb b/lib/xmlrpc/server.rb index 131173fa70..6b5c5d4253 100644 --- a/lib/xmlrpc/server.rb +++ b/lib/xmlrpc/server.rb @@ -14,23 +14,23 @@ Released under the same term of license as Ruby. = XMLRPC::BasicServer == Description Is the base class for all XML-RPC server-types (CGI, standalone). -You can add handler and set a default handler. +You can add handler and set a default handler. Do not use this server, as this is/should be an abstract class. === How the method to call is found -The arity (number of accepted arguments) of a handler (method or (({Proc})) object) is -compared to the given arguments submitted by the client for a RPC ((-Remote Procedure Call-)). -A handler is only called if it accepts the number of arguments, otherwise the search -for another handler will go on. When at the end no handler was found, +The arity (number of accepted arguments) of a handler (method or (({Proc})) object) is +compared to the given arguments submitted by the client for a RPC ((-Remote Procedure Call-)). +A handler is only called if it accepts the number of arguments, otherwise the search +for another handler will go on. When at the end no handler was found, the ((<default_handler|XMLRPC::BasicServer#set_default_handler>)) will be called. With this technique it is possible to do overloading by number of parameters, but only for (({Proc})) handler, because you cannot define two methods of the same name in -the same class. +the same class. == Class Methods --- XMLRPC::BasicServer.new( class_delim="." ) - Creates a new (({XMLRPC::BasicServer})) instance, which should not be + Creates a new (({XMLRPC::BasicServer})) instance, which should not be done, because (({XMLRPC::BasicServer})) is an abstract class. This method should be called from a subclass indirectly by a (({super})) call in the method (({initialize})). The paramter ((|class_delim|)) is used @@ -40,24 +40,24 @@ the same class. == Instance Methods --- XMLRPC::BasicServer#add_handler( name, signature=nil, help=nil ) { aBlock } Adds ((|aBlock|)) to the list of handlers, with ((|name|)) as the name of the method. - Parameters ((|signature|)) and ((|help|)) are used by the Introspection method if specified, - where ((|signature|)) is either an Array containing strings each representing a type of it's - signature (the first is the return value) or an Array of Arrays if the method has multiple + Parameters ((|signature|)) and ((|help|)) are used by the Introspection method if specified, + where ((|signature|)) is either an Array containing strings each representing a type of it's + signature (the first is the return value) or an Array of Arrays if the method has multiple signatures. Value type-names are "int, boolean, double, string, dateTime.iso8601, base64, array, struct". Parameter ((|help|)) is a String with informations about how to call this method etc. A handler method or code-block can return the types listed at - ((<XMLRPC::Client#call|URL:client.html#index:0>)). - When a method fails, it can tell it the client by throwing an + ((<XMLRPC::Client#call|URL:client.html#index:0>)). + When a method fails, it can tell it the client by throwing an (({XMLRPC::FaultException})) like in this example: s.add_handler("michael.div") do |a,b| if b == 0 raise XMLRPC::FaultException.new(1, "division by zero") else - a / b + a / b end - end + end The client gets in the case of (({b==0})) an object back of type (({XMLRPC::FaultException})) that has a ((|faultCode|)) and ((|faultString|)) field. @@ -67,10 +67,10 @@ the same class. To add an object write: server.add_handler("michael", MyHandlerClass.new) All public methods of (({MyHandlerClass})) are accessible to - the XML-RPC clients by (('michael."name of method"')). This is - where the ((|class_delim|)) in ((<new|XMLRPC::BasicServer.new>)) - has it's role, a XML-RPC method-name is defined by - ((|prefix|)) + ((|class_delim|)) + (('"name of method"')). + the XML-RPC clients by (('michael."name of method"')). This is + where the ((|class_delim|)) in ((<new|XMLRPC::BasicServer.new>)) + has it's role, a XML-RPC method-name is defined by + ((|prefix|)) + ((|class_delim|)) + (('"name of method"')). --- XMLRPC::BasicServer#add_handler( interface, obj ) This is the third form of ((<add_handler|XMLRPC::BasicServer#add_handler>)). @@ -91,11 +91,11 @@ the same class. It is a (({Proc})) object or (({nil})). --- XMLRPC::BasicServer#set_default_handler ( &handler ) - Sets ((|handler|)) as the default-handler, which is called when + Sets ((|handler|)) as the default-handler, which is called when no handler for a method-name is found. ((|handler|)) is a code-block. The default-handler is called with the (XML-RPC) method-name as first argument, and the other arguments are the parameters given by the client-call. - + If no block is specified the default of (({XMLRPC::BasicServer})) is used, which raises a XMLRPC::FaultException saying "method missing". @@ -103,7 +103,7 @@ the same class. --- XMLRPC::BasicServer#set_writer( writer ) Sets the XML writer to use for generating XML output. Should be an instance of a class from module (({XMLRPC::XMLWriter})). - If this method is not called, then (({XMLRPC::Config::DEFAULT_WRITER})) is used. + If this method is not called, then (({XMLRPC::Config::DEFAULT_WRITER})) is used. --- XMLRPC::BasicServer#set_parser( parser ) Sets the XML parser to use for parsing XML documents. @@ -111,7 +111,7 @@ the same class. If this method is not called, then (({XMLRPC::Config::DEFAULT_PARSER})) is used. --- XMLRPC::BasicServer#add_introspection - Adds the introspection handlers "system.listMethods", "system.methodSignature" and "system.methodHelp", + Adds the introspection handlers "system.listMethods", "system.methodSignature" and "system.methodHelp", where only the first one works. --- XMLRPC::BasicServer#add_multicall @@ -123,7 +123,7 @@ the same class. --- XMLRPC::BasicServer#set_service_hook ( &handler ) A service-hook is called for each service request (RPC). You can use a service-hook for example to wrap existing methods and catch exceptions of them or - convert values to values recognized by XMLRPC. You can disable it by passing (({nil})) as parameter + convert values to values recognized by XMLRPC. You can disable it by passing (({nil})) as parameter ((|handler|)) . The service-hook is called with a (({Proc})) object and with the parameters for this (({Proc})). @@ -132,7 +132,7 @@ the same class. server.set_service_hook {|obj, *args| begin ret = obj.call(*args) # call the original service-method - # could convert the return value + # could convert the return value resuce # rescue exceptions end @@ -157,7 +157,7 @@ class BasicServer include ParserWriterChooseMixin include ParseContentType - ERR_METHOD_MISSING = 1 + ERR_METHOD_MISSING = 1 ERR_UNCAUGHT_EXCEPTION = 2 ERR_MC_WRONG_PARAM = 3 ERR_MC_MISSING_PARAMS = 4 @@ -169,7 +169,7 @@ class BasicServer def initialize(class_delim=".") @handler = [] - @default_handler = nil + @default_handler = nil @service_hook = nil @class_delim = class_delim @@ -183,7 +183,7 @@ class BasicServer def add_handler(prefix, obj_or_signature=nil, help=nil, &block) if block_given? # proc-handler - @handler << [prefix, block, obj_or_signature, help] + @handler << [prefix, block, obj_or_signature, help] else if prefix.kind_of? String # class-handler @@ -208,7 +208,7 @@ class BasicServer @service_hook = handler self end - + def get_default_handler @default_handler end @@ -216,18 +216,18 @@ class BasicServer def set_default_handler (&handler) @default_handler = handler self - end + end def add_multicall add_handler("system.multicall", %w(array array), "Multicall Extension") do |arrStructs| - unless arrStructs.is_a? Array + 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"] + params = call["params"] if params.nil? multicall_fault(ERR_MC_MISSING_PARAMS, "Missing params") @@ -246,16 +246,16 @@ class BasicServer [val] else # exception - multicall_fault(val.faultCode, val.faultString) + multicall_fault(val.faultCode, val.faultString) end end end - end - + end + else multicall_fault(ERR_MC_EXPECTED_STRUCT, "system.multicall expected struct") end - } + } end # end add_handler self end @@ -284,7 +284,7 @@ class BasicServer sig.each {|s| sigs << s} else # sig is a single signature, e.g. ["array"] - sigs << sig + sigs << sig end end end @@ -292,11 +292,11 @@ class BasicServer end add_handler("system.methodHelp", %w(string string), "Returns help on using this method") do |meth| - help = nil + help = nil @handler.each do |name, obj, sig, hlp| - if obj.kind_of? Proc and name == meth + if obj.kind_of? Proc and name == meth help = hlp - break + break end end help || "" @@ -306,18 +306,18 @@ class BasicServer end - + def process(data) - method, params = parser().parseMethodCall(data) + method, params = parser().parseMethodCall(data) handle(method, *params) end - + private # -------------------------------------------------------------- def multicall_fault(nr, str) {"faultCode" => nr, "faultString" => str} end - + # # method dispatch # @@ -333,17 +333,17 @@ class BasicServer if check_arity(obj, args.size) if @service_hook.nil? - return obj.call(*args) + return obj.call(*args) else return @service_hook.call(obj, *args) end end - end - + end + if @default_handler.nil? raise XMLRPC::FaultException.new(ERR_METHOD_MISSING, "Method #{methodname} missing or wrong number of parameters!") else - @default_handler.call(methodname, *args) + @default_handler.call(methodname, *args) end end @@ -357,7 +357,7 @@ class BasicServer if ary >= 0 n_args == ary else - n_args >= (ary+1).abs + n_args >= (ary+1).abs end end @@ -366,8 +366,8 @@ class BasicServer def call_method(methodname, *args) begin [true, dispatch(methodname, *args)] - rescue XMLRPC::FaultException => e - [false, e] + rescue XMLRPC::FaultException => e + [false, e] rescue Exception => e [false, XMLRPC::FaultException.new(ERR_UNCAUGHT_EXCEPTION, "Uncaught exception #{e.message} in method #{methodname}")] end @@ -388,8 +388,8 @@ end = XMLRPC::CGIServer == Synopsis require "xmlrpc/server" - - s = XMLRPC::CGIServer.new + + s = XMLRPC::CGIServer.new s.add_handler("michael.add") do |a,b| a + b @@ -399,15 +399,15 @@ end if b == 0 raise XMLRPC::FaultException.new(1, "division by zero") else - a / b + a / b end - end + end s.set_default_handler do |name, *args| raise XMLRPC::FaultException.new(-99, "Method #{name} missing" + " or wrong number of parameters!") end - + s.serve == Description @@ -419,7 +419,7 @@ Implements a CGI-based XML-RPC server. == Class Methods --- XMLRPC::CGIServer.new( *a ) Creates a new (({XMLRPC::CGIServer})) instance. All parameters given - are by-passed to ((<XMLRPC::BasicServer.new>)). You can only create + are by-passed to ((<XMLRPC::BasicServer.new>)). You can only create ((*one*)) (({XMLRPC::CGIServer})) instance, because more than one makes no sense. @@ -427,7 +427,7 @@ Implements a CGI-based XML-RPC server. --- XMLRPC::CGIServer#serve Call this after you have added all you handlers to the server. This method processes a XML-RPC methodCall and sends the answer - back to the client. + back to the client. Make sure that you don't write to standard-output in a handler, or in any other part of your program, this would case a CGI-based server to fail! =end @@ -443,14 +443,14 @@ class CGIServer < BasicServer def initialize(*a) super(*a) end - + def serve catch(:exit_serve) { length = ENV['CONTENT_LENGTH'].to_i - http_error(405, "Method Not Allowed") unless ENV['REQUEST_METHOD'] == "POST" + 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 + http_error(411, "Length Required") unless length > 0 # TODO: do we need a call to binmode? $stdin.binmode if $stdin.respond_to? :binmode @@ -467,7 +467,7 @@ class CGIServer < BasicServer def http_error(status, message) err = "#{status} #{message}" - msg = <<-"MSGEND" + msg = <<-"MSGEND" <html> <head> <title>#{err}</title> @@ -487,7 +487,7 @@ class CGIServer < BasicServer h = {} header.each {|key, value| h[key.to_s.capitalize] = value} h['Status'] ||= "200 OK" - h['Content-length'] ||= body.size.to_s + h['Content-length'] ||= body.size.to_s str = "" h.each {|key, value| str << "#{key}: #{value}\r\n"} @@ -507,7 +507,7 @@ Use it in the same way as CGIServer! == Superclass ((<XMLRPC::BasicServer>)) -=end +=end class ModRubyServer < BasicServer @@ -523,9 +523,9 @@ class ModRubyServer < BasicServer length = header['Content-length'].to_i - http_error(405, "Method Not Allowed") unless @ap.request_method == "POST" + 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 + http_error(411, "Length Required") unless length > 0 # TODO: do we need a call to binmode? @ap.binmode @@ -542,7 +542,7 @@ class ModRubyServer < BasicServer def http_error(status, message) err = "#{status} #{message}" - msg = <<-"MSGEND" + msg = <<-"MSGEND" <html> <head> <title>#{err}</title> @@ -562,12 +562,12 @@ class ModRubyServer < BasicServer h = {} header.each {|key, value| h[key.to_s.capitalize] = value} h['Status'] ||= "200 OK" - h['Content-length'] ||= body.size.to_s + h['Content-length'] ||= body.size.to_s h.each {|key, value| @ap.headers_out[key] = value } - @ap.content_type = h["Content-type"] - @ap.status = status.to_i - @ap.send_http_header + @ap.content_type = h["Content-type"] + @ap.status = status.to_i + @ap.send_http_header @ap.print body end @@ -578,8 +578,8 @@ end = XMLRPC::Server == Synopsis require "xmlrpc/server" - - s = XMLRPC::Server.new(8080) + + s = XMLRPC::Server.new(8080) s.add_handler("michael.add") do |a,b| a + b @@ -589,15 +589,15 @@ end if b == 0 raise XMLRPC::FaultException.new(1, "division by zero") else - a / b + a / b end - end + end s.set_default_handler do |name, *args| raise XMLRPC::FaultException.new(-99, "Method #{name} missing" + " or wrong number of parameters!") end - + s.serve == Description @@ -610,13 +610,13 @@ program. == Class Methods --- XMLRPC::Server.new( port=8080, host="127.0.0.1", maxConnections=4, stdlog=$stdout, audit=true, debug=true, *a ) Creates a new (({XMLRPC::Server})) instance, which is a XML-RPC server listening on - port ((|port|)) and accepts requests for the host ((|host|)), which is by default only the localhost. + port ((|port|)) and accepts requests for the host ((|host|)), which is by default only the localhost. The server is not started, to start it you have to call ((<serve|XMLRPC::Server#serve>)). Parameters ((|audit|)) and ((|debug|)) are obsolete! - All additionally given parameters in ((|*a|)) are by-passed to ((<XMLRPC::BasicServer.new>)). - + All additionally given parameters in ((|*a|)) are by-passed to ((<XMLRPC::BasicServer.new>)). + == Instance Methods --- XMLRPC::Server#serve Call this after you have added all you handlers to the server. @@ -624,7 +624,7 @@ program. --- XMLRPC::Server#shutdown Stops and shuts the server down. - + =end class WEBrickServlet < BasicServer; end # forward declaration @@ -634,22 +634,22 @@ class Server < WEBrickServlet 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, + @server = WEBrick::HTTPServer.new(:Port => port, :BindAddress => host, :MaxClients => maxConnections, :Logger => WEBrick::Log.new(stdlog)) @server.mount("/", self) end - + def serve signals = %w[INT TERM HUP] & Signal.list.keys signals.each { |signal| trap(signal) { @server.shutdown } } @server.start end - + def shutdown @server.shutdown end - + end =begin @@ -668,16 +668,16 @@ end if b == 0 raise XMLRPC::FaultException.new(1, "division by zero") else - a / b + a / b end - end + end s.set_default_handler do |name, *args| raise XMLRPC::FaultException.new(-99, "Method #{name} missing" + " or wrong number of parameters!") end - httpserver = WEBrick::HTTPServer.new(:Port => 8080) + httpserver = WEBrick::HTTPServer.new(:Port => 8080) httpserver.mount("/RPC2", s) trap("HUP") { httpserver.shutdown } # use 1 instead of "HUP" on Windows httpserver.start @@ -691,7 +691,7 @@ end --- XMLRPC::WEBrickServlet#get_valid_ip Return the via method ((<set_valid_ip|XMLRPC::Server#set_valid_ip>)) specified valid IP addresses. - + == Description Implements a servlet for use with WEBrick, a pure Ruby (HTTP-) server framework. @@ -707,10 +707,10 @@ class WEBrickServlet < BasicServer @valid_ip = nil end - # deprecated from WEBrick/1.2.2. + # deprecated from WEBrick/1.2.2. # but does not break anything. def require_path_info? - false + false end def get_instance(config, *options) @@ -732,7 +732,7 @@ class WEBrickServlet < BasicServer def service(request, response) - if @valid_ip + if @valid_ip raise WEBrick::HTTPStatus::Forbidden unless @valid_ip.any? { |ip| request.peeraddr[3] =~ ip } end @@ -741,9 +741,9 @@ class WEBrickServlet < BasicServer "unsupported method `#{request.request_method}'." end - if parse_content_type(request['Content-type']).first != "text/xml" + if parse_content_type(request['Content-type']).first != "text/xml" raise WEBrick::HTTPStatus::BadRequest - end + end length = (request['Content-length'] || 0).to_i @@ -756,14 +756,14 @@ class WEBrickServlet < BasicServer end resp = process(data) - if resp.nil? or resp.size <= 0 + 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 + response.body = resp end end @@ -773,6 +773,6 @@ end # module XMLRPC =begin = History - $Id$ + $Id$ =end diff --git a/lib/xmlrpc/utils.rb b/lib/xmlrpc/utils.rb index 4c2b63c9c6..60d4ef5d99 100644 --- a/lib/xmlrpc/utils.rb +++ b/lib/xmlrpc/utils.rb @@ -1,12 +1,12 @@ # # 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 +# The Mixin is used in client.rb (class Client) and server.rb (class # BasicServer) -# +# # Copyright (C) 2001, 2002, 2003 by Michael Neumann ([email protected]) # -# $Id$ +# $Id$ # module XMLRPC @@ -15,7 +15,7 @@ module XMLRPC # 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 - # + # module Marshallable end @@ -72,9 +72,9 @@ module XMLRPC mname = nil sig = [sig] if sig.kind_of? String - sig = sig.collect do |s| + sig = sig.collect do |s| name, si = parse_sig(s) - raise "Wrong signatures!" if mname != nil and name != mname + raise "Wrong signatures!" if mname != nil and name != mname mname = name si end @@ -83,12 +83,12 @@ module XMLRPC end private # --------------------------------- - + def parse_sig(sig) # sig is a String if sig =~ /^\s*(\w+)\s+([^(]+)(\(([^)]*)\))?\s*$/ params = [$1] - name = $2.strip + name = $2.strip $4.split(",").each {|i| params << i.strip} if $4 != nil return name, params else @@ -109,10 +109,10 @@ module XMLRPC instance_eval(&p) end - def get_methods(obj, delim=".") + def get_methods(obj, delim=".") prefix = @prefix + delim - @methods.collect { |name, meth, sig, help| - [prefix + name, obj.method(meth).to_proc, sig, help] + @methods.collect { |name, meth, sig, help| + [prefix + name, obj.method(meth).to_proc, sig, help] } end @@ -132,7 +132,7 @@ module XMLRPC 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] + [prefix + name, obj.method(name).to_proc, nil, nil] } end end @@ -141,16 +141,16 @@ module XMLRPC end # module Service - # + # # short-form to create a Service::Interface # def self.interface(prefix, &p) - Service::Interface.new(prefix, &p) + Service::Interface.new(prefix, &p) end # short-cut for creating a PublicInstanceMethodsInterface def self.iPIMethods(prefix) - Service::PublicInstanceMethodsInterface.new(prefix) + Service::PublicInstanceMethodsInterface.new(prefix) end diff --git a/lib/yaml.rb b/lib/yaml.rb index 12853401c1..0c95b7e82c 100644 --- a/lib/yaml.rb +++ b/lib/yaml.rb @@ -4,7 +4,7 @@ # = yaml.rb: top-level module with methods for loading and parsing YAML documents # # Author:: why the lucky stiff -# +# require 'stringio' require 'yaml/error' @@ -24,18 +24,18 @@ require 'yaml/constants' # serialization format. Together with the Unicode standard for characters, it # provides all the information necessary to understand YAML Version 1.0 # and construct computer programs to process it. -# +# # See http://yaml.org/ for more information. For a quick tutorial, please # visit YAML In Five Minutes (http://yaml.kwiki.org/?YamlInFiveMinutes). -# +# # == About This Library -# +# # The YAML 1.0 specification outlines four stages of YAML loading and dumping. # This library honors all four of those stages, although data is really only # available to you in three stages. -# +# # The four stages are: native, representation, serialization, and presentation. -# +# # The native stage refers to data which has been loaded completely into Ruby's # own types. (See +YAML::load+.) # @@ -43,14 +43,14 @@ require 'yaml/constants' # +YAML::BaseNode+ objects. In this stage, the document is available as a # tree of node objects. You can perform YPath queries and transformations # at this level. (See +YAML::parse+.) -# +# # The serialization stage happens inside the parser. The YAML parser used in # Ruby is called Syck. Serialized nodes are available in the extension as # SyckNode structs. -# +# # The presentation stage is the YAML document itself. This is accessible # to you as a string. (See +YAML::dump+.) -# +# # For more information about the various information models, see Chapter # 3 of the YAML 1.0 Specification (http://yaml.org/spec/#id2491269). # @@ -102,7 +102,7 @@ module YAML # # 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 @@ -168,8 +168,8 @@ module YAML # Can also load from a string. # # YAML.parse( "--- :locked" ) - # #=> #<YAML::Syck::Node:0x82edddc - # @type_id="tag:ruby.yaml.org,2002:sym", + # #=> #<YAML::Syck::Node:0x82edddc + # @type_id="tag:ruby.yaml.org,2002:sym", # @value=":locked", @kind=:scalar> # def YAML.parse( io ) @@ -263,7 +263,7 @@ module YAML end # - # Loads all documents from the current _io_ stream, + # Loads all documents from the current _io_ stream, # returning a +YAML::Stream+ object containing all # loaded documents. # @@ -271,7 +271,7 @@ module YAML d = nil parser.load_documents( io ) do |doc| d = YAML::Stream.new if not d - d.add( doc ) + d.add( doc ) end return d end @@ -288,7 +288,7 @@ module YAML def YAML.dump_stream( *objs ) d = YAML::Stream.new objs.each do |doc| - d.add( doc ) + d.add( doc ) end d.emit end @@ -378,7 +378,7 @@ module YAML # Allocate an Emitter if needed # def YAML.quick_emit( oid, opts = {}, &e ) - out = + out = if opts.is_a? YAML::Emitter opts else @@ -390,7 +390,7 @@ module YAML end out.emit( oid, &e ) end - + end require 'yaml/rubytypes' @@ -422,7 +422,7 @@ module Kernel # # _produces:_ # - # --- !ruby/struct:S + # --- !ruby/struct:S # name: dave # state: TX # diff --git a/lib/yaml/baseemitter.rb b/lib/yaml/baseemitter.rb index 4bdc796cbf..59d9eddc76 100644 --- a/lib/yaml/baseemitter.rb +++ b/lib/yaml/baseemitter.rb @@ -42,7 +42,7 @@ module YAML '|' else '>' - end + end indt = $&.to_i if block =~ /\d+/ if valx =~ /(\A\n*[ \t#]|^---\s+)/ indt = options(:Indent) unless indt.to_i > 0 @@ -64,8 +64,8 @@ module YAML valx = fold( YAML::escape( valx, esc_skip ) + "\"" ).chomp self << '"' + indent_text( valx, indt, false ) else - if block[0] == ?> - valx = fold( valx ) + if block[0] == ?> + valx = fold( valx ) end #p [block, indt] self << block + indent_text( valx, indt ) @@ -84,7 +84,7 @@ module YAML # Emit double-quoted string # def double( value ) - "\"#{YAML.escape( value )}\"" + "\"#{YAML.escape( value )}\"" end # @@ -150,8 +150,8 @@ module YAML @seq_map = false else # FIXME - # if @buffer.length == 1 and options(:UseHeader) == false and type.length.zero? - # @headless = 1 + # if @buffer.length == 1 and options(:UseHeader) == false and type.length.zero? + # @headless = 1 # end defkey = @options.delete( :DefaultKey ) @@ -174,7 +174,7 @@ module YAML self << "\n" indent! end - self << ": " + self << ": " v[1].to_yaml( :Emitter => self ) } end @@ -187,7 +187,7 @@ module YAML # @seq_map = false # else self << "\n" - indent! + indent! # end end @@ -207,8 +207,8 @@ module YAML self << "[]" else # FIXME - # if @buffer.length == 1 and options(:UseHeader) == false and type.length.zero? - # @headless = 1 + # if @buffer.length == 1 and options(:UseHeader) == false and type.length.zero? + # @headless = 1 # end # diff --git a/lib/yaml/constants.rb b/lib/yaml/constants.rb index fb833d3077..728d3b7932 100644 --- a/lib/yaml/constants.rb +++ b/lib/yaml/constants.rb @@ -13,7 +13,7 @@ module YAML # Parser tokens # WORD_CHAR = 'A-Za-z0-9' - PRINTABLE_CHAR = '-_A-Za-z0-9!?/()$\'". ' + PRINTABLE_CHAR = '-_A-Za-z0-9!?/()$\'". ' NOT_PLAIN_CHAR = '\x7f\x0-\x1f\x80-\x9f' ESCAPE_CHAR = '[\\x00-\\x09\\x0b-\\x1f]' INDICATOR_CHAR = '*&!|\\\\^@%{}[]=' @@ -27,7 +27,7 @@ module YAML \x18 \x19 \x1a \e \x1c \x1d \x1e \x1f } UNESCAPES = { - 'a' => "\x07", 'b' => "\x08", 't' => "\x09", + 'a' => "\x07", 'b' => "\x08", 't' => "\x09", 'n' => "\x0a", 'v' => "\x0b", 'f' => "\x0c", 'r' => "\x0d", 'e' => "\x1b", '\\' => '\\', } diff --git a/lib/yaml/dbm.rb b/lib/yaml/dbm.rb index 87d6009250..a28fd04f19 100644 --- a/lib/yaml/dbm.rb +++ b/lib/yaml/dbm.rb @@ -35,14 +35,14 @@ class DBM < ::DBM def delete( key ) v = super( key ) if String === v - v = YAML::load( v ) + v = YAML::load( v ) end v end def delete_if del_keys = keys.dup del_keys.delete_if { |k| yield( k, fetch( k ) ) == false } - del_keys.each { |k| delete( k ) } + del_keys.each { |k| delete( k ) } self end def reject diff --git a/lib/yaml/encoding.rb b/lib/yaml/encoding.rb index 57dc553606..98e83c3853 100644 --- a/lib/yaml/encoding.rb +++ b/lib/yaml/encoding.rb @@ -23,9 +23,9 @@ module YAML if $3 ["#$3".hex ].pack('U*') elsif $2 - [$2].pack( "H2" ) + [$2].pack( "H2" ) else - UNESCAPES[$1] + UNESCAPES[$1] end } end diff --git a/lib/yaml/error.rb b/lib/yaml/error.rb index 15865a9aa9..75de0ec18a 100644 --- a/lib/yaml/error.rb +++ b/lib/yaml/error.rb @@ -26,7 +26,7 @@ module YAML # # YAML Error classes # - + class Error < StandardError; end class ParseError < Error; end class TypeError < StandardError; end diff --git a/lib/yaml/rubytypes.rb b/lib/yaml/rubytypes.rb index ae65b355e1..b2745b4542 100644 --- a/lib/yaml/rubytypes.rb +++ b/lib/yaml/rubytypes.rb @@ -64,7 +64,7 @@ class Struct end if not struct_type struct_def = [ tag.split( ':', 4 ).last ] - struct_type = Struct.new( *struct_def.concat( val.keys.collect { |k| k.intern } ) ) + struct_type = Struct.new( *struct_def.concat( val.keys.collect { |k| k.intern } ) ) end # @@ -317,7 +317,7 @@ class Time 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) + if (difference_to_utc < 0) difference_sign = '-' absolute_difference = -difference_to_utc else @@ -388,9 +388,9 @@ class Rational Rational( val['numerator'], val['denominator'] ) end end - def to_yaml( opts = {} ) + def to_yaml( opts = {} ) YAML::quick_emit( self, opts ) do |out| - out.map( taguri, nil ) do |map| + out.map( taguri, nil ) do |map| map.add( 'denominator', denominator ) map.add( 'numerator', numerator ) end @@ -435,7 +435,7 @@ class FalseClass end end -class NilClass +class NilClass yaml_as "tag:yaml.org,2002:null" def to_yaml( opts = {} ) YAML::quick_emit( nil, opts ) do |out| diff --git a/lib/yaml/stream.rb b/lib/yaml/stream.rb index 060fbc4200..651a1bbbef 100644 --- a/lib/yaml/stream.rb +++ b/lib/yaml/stream.rb @@ -11,7 +11,7 @@ module YAML @options = opts @documents = [] end - + def []( i ) @documents[ i ] end diff --git a/lib/yaml/stringio.rb b/lib/yaml/stringio.rb index 8ad949fa2b..b0fda19e28 100644 --- a/lib/yaml/stringio.rb +++ b/lib/yaml/stringio.rb @@ -13,7 +13,7 @@ rescue LoadError end def pos @pos - end + end def eof @eof end diff --git a/lib/yaml/tag.rb b/lib/yaml/tag.rb index 0fb6bef9a0..add3c49894 100644 --- a/lib/yaml/tag.rb +++ b/lib/yaml/tag.rb @@ -4,13 +4,13 @@ # = yaml/tag.rb: methods for associating a taguri to a class. # # Author:: why the lucky stiff -# +# module YAML # A dictionary of taguris which map to # Ruby classes. @@tagged_classes = {} - - # + + # # 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: # @@ -19,7 +19,7 @@ module YAML # 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: # diff --git a/lib/yaml/types.rb b/lib/yaml/types.rb index 3871c628fe..60aebc0481 100644 --- a/lib/yaml/types.rb +++ b/lib/yaml/types.rb @@ -58,7 +58,7 @@ module YAML # # YAML Hash class to support comments and defaults # - class SpecialHash < ::Hash + class SpecialHash < ::Hash attr_accessor :default def inspect self.default.to_s @@ -112,7 +112,7 @@ module YAML if ( tmp = self.assoc( k ) ) and not set tmp[1] = val else - self << [ k, val ] + self << [ k, val ] end val end @@ -163,7 +163,7 @@ module YAML self.assoc( k ).to_a end def []=( k, val ) - self << [ k, val ] + self << [ k, val ] val end def has_key?( k ) |