diff --git a/ext/Win32API/lib/win32/registry.rb b/ext/Win32API/lib/win32/registry.rb index 9a2f3827b7..ac6c05b51a 100644 --- a/ext/Win32API/lib/win32/registry.rb +++ b/ext/Win32API/lib/win32/registry.rb @@ -11,10 +11,10 @@ It uses Win32API to call Win32 Registry APIs. reg['foo'] = 'bar' # write a value reg['foo', Win32::Registry::REG_SZ] = 'bar' # write a value with type reg.write('foo', Win32::Registry::REG_SZ, 'bar') # write a value - + reg.each_value { |name, type, data| ... } # Enumerate values reg.each_key { |key, wtime| ... } # Enumerate subkeys - + reg.delete_value(name) # Delete a value reg.delete_key(name) # Delete a subkey reg.delete_key(name, true) # Delete a subkey recursively @@ -35,26 +35,26 @@ It uses Win32API to call Win32 Registry APIs. Open the registry key ((|subkey|)) under ((|key|)). ((|key|)) is Win32::Registry object of parent key. You can use predefined key HKEY_* (see (())) - + ((|desired|)) and ((|opt|)) is access mask and key option. For detail, see (()). - + If block is given, the key is closed automatically. --- Registry.create(key, subkey, desired = KEY_ALL_ACCESS, opt = REG_OPTION_RESERVED) --- Registry.create(key, subkey, desired = KEY_ALL_ACCESS, opt = REG_OPTION_RESERVED) { |reg| ... } Create or open the registry key ((|subkey|)) under ((|key|)). You can use predefined key HKEY_* (see (())) - + If subkey is already exists, key is opened and Registry#(()) method will return false. - + If block is given, the key is closed automatically. --- Registry.expand_environ(str) Replace (({%\w+%})) into the environment value of ((|str|)). This method is used for REG_EXPAND_SZ. - + For detail, see (()) Win32 API. --- Registry.type2name(type) @@ -75,14 +75,14 @@ It uses Win32API to call Win32 Registry APIs. --- close Close key. - + After closed, most method raises error. --- read(name, *rtype) Read a registry value named ((|name|)) and return array of [ ((|type|)), ((|data|)) ]. When name is nil, the `default' value is read. - + ((|type|)) is value type. (see (())) ((|data|)) is value data, its class is: :REG_SZ, REG_EXPAND_SZ @@ -93,19 +93,19 @@ It uses Win32API to call Win32 Registry APIs. Integer :REG_BINARY String (contains binary data) - + When ((|rtype|)) is specified, the value type must be included by ((|rtype|)) array, or TypeError is raised. --- self[name, *rtype] Read a registry value named ((|name|)) and return its value data. The class of value is same as (()) method returns. - + If the value type is REG_EXPAND_SZ, returns value data whose environment variables are replaced. If the value type is neither REG_SZ, REG_MULTI_SZ, REG_DWORD, REG_DWORD_BIG_ENDIAN, nor REG_QWORD, TypeError is raised. - + The meaning of ((|rtype|)) is same as (()) method. --- read_s(name) @@ -113,26 +113,26 @@ It uses Win32API to call Win32 Registry APIs. --- read_bin(name) Read a REG_SZ(read_s), REG_DWORD(read_i), or REG_BINARY(read_bin) registry value named ((|name|)). - + If the values type does not match, TypeError is raised. --- read_s_expand(name) Read a REG_SZ or REG_EXPAND_SZ registry value named ((|name|)). - + If the value type is REG_EXPAND_SZ, environment variables are replaced. Unless the value type is REG_SZ or REG_EXPAND_SZ, TypeError is raised. --- write(name, type, data) Write ((|data|)) to a registry value named ((|name|)). When name is nil, write to the `default' value. - + ((|type|)) is type value. (see (())) Class of ((|data|)) must be same as which (()) method returns. --- self[name, wtype = nil] = value Write ((|value|)) to a registry value named ((|name|)). - + If ((|wtype|)) is specified, the value type is it. Otherwise, the value type is depend on class of ((|value|)): :Integer @@ -146,7 +146,7 @@ It uses Win32API to call Win32 Registry APIs. --- write_i(name, value) --- write_bin(name, value) Write ((|value|)) to a registry value named ((|name|)). - + The value type is REG_SZ(write_s), REG_DWORD(write_i), or REG_BINARY(write_bin). @@ -156,7 +156,7 @@ It uses Win32API to call Win32 Registry APIs. --- each_key { |subkey, wtime| ... } Enumerate subkeys. - + ((|subkey|)) is String which contains name of subkey. ((|wtime|)) is last write time as FILETIME (64-bit integer). (see (())) @@ -168,7 +168,7 @@ It uses Win32API to call Win32 Registry APIs. --- delete_key(name, recursive = false) Delete a subkey named ((|name|)) and all its values. - + If ((|recursive|)) is false, the subkey must not have subkeys. Otherwise, this method deletes all subkeys and values recursively. @@ -215,7 +215,7 @@ It uses Win32API to call Win32 Registry APIs. Length of security descriptor. :wtime Last write time as FILETIME(64-bit integer) - + For detail, see (()) Win32 API. --- num_keys @@ -275,7 +275,7 @@ module Win32 HKEY_PERFORMANCE_NLSTEXT = 0x80000060 HKEY_CURRENT_CONFIG = 0x80000005 HKEY_DYN_DATA = 0x80000006 - + REG_NONE = 0 REG_SZ = 1 REG_EXPAND_SZ = 2 @@ -290,7 +290,7 @@ module Win32 REG_RESOURCE_REQUIREMENTS_LIST = 10 REG_QWORD = 11 REG_QWORD_LITTLE_ENDIAN = 11 - + STANDARD_RIGHTS_READ = 0x00020000 STANDARD_RIGHTS_WRITE = 0x00020000 KEY_QUERY_VALUE = 0x0001 @@ -305,7 +305,7 @@ module Win32 KEY_SET_VALUE | KEY_CREATE_SUB_KEY KEY_EXECUTE = KEY_READ KEY_ALL_ACCESS = KEY_READ | KEY_WRITE | KEY_CREATE_LINK - + REG_OPTION_RESERVED = 0x0000 REG_OPTION_NON_VOLATILE = 0x0000 REG_OPTION_VOLATILE = 0x0001 @@ -315,21 +315,21 @@ module Win32 REG_LEGAL_OPTION = REG_OPTION_RESERVED | REG_OPTION_NON_VOLATILE | REG_OPTION_CREATE_LINK | REG_OPTION_BACKUP_RESTORE | REG_OPTION_OPEN_LINK - + REG_CREATED_NEW_KEY = 1 REG_OPENED_EXISTING_KEY = 2 - + REG_WHOLE_HIVE_VOLATILE = 0x0001 REG_REFRESH_HIVE = 0x0002 REG_NO_LAZY_FLUSH = 0x0004 REG_FORCE_RESTORE = 0x0008 - + MAX_KEY_LENGTH = 514 MAX_VALUE_LENGTH = 32768 end include Constants include Enumerable - + # # Error # @@ -343,7 +343,7 @@ module Win32 end attr_reader :code end - + # # Predefined Keys # @@ -354,23 +354,23 @@ module Win32 @keyname = keyname @disposition = REG_OPENED_EXISTING_KEY end - + # Predefined keys cannot be closed def close raise Error.new(5) ## ERROR_ACCESS_DENIED end - + # Fake class for Registry#open, Registry#create def class Registry end - + # Make all Constants.constants.grep(/^HKEY_/) do |c| Registry.const_set c, new(Constants.const_get(c), c) end end - + # # Win32 APIs # @@ -390,37 +390,37 @@ module Win32 ].each do |fn| const_set fn[0].intern, Win32API.new('advapi32.dll', *fn) end - + module_function - + def check(result) raise Error, result, caller(2) if result != 0 end - + def packdw(dw) [dw].pack('V') end - + def unpackdw(dw) dw += [0].pack('V') dw.unpack('V')[0] end - + def packqw(qw) [ qw & 0xFFFFFFFF, qw >> 32 ].pack('VV') end - + def unpackqw(qw) qw = qw.unpack('VV') (qw[1] << 32) | qw[0] end - + def OpenKey(hkey, name, opt, desired) result = packdw(0) check RegOpenKeyExA.call(hkey, name, opt, desired, result) unpackdw(result) end - + def CreateKey(hkey, name, opt, desired) result = packdw(0) disp = packdw(0) @@ -428,14 +428,14 @@ module Win32 0, result, disp) [ unpackdw(result), unpackdw(disp) ] end - + def EnumValue(hkey, index) name = ' ' * Constants::MAX_KEY_LENGTH size = packdw(Constants::MAX_KEY_LENGTH) check RegEnumValueA.call(hkey, index, name, size, 0, 0, 0, 0) name[0, unpackdw(size)] end - + def EnumKey(hkey, index) name = ' ' * Constants::MAX_KEY_LENGTH size = packdw(Constants::MAX_KEY_LENGTH) @@ -443,7 +443,7 @@ module Win32 check RegEnumKeyExA.call(hkey, index, name, size, 0, 0, 0, wtime) [ name[0, unpackdw(size)], unpackqw(wtime) ] end - + def QueryValue(hkey, name) type = packdw(0) size = packdw(0) @@ -452,27 +452,27 @@ module Win32 check RegQueryValueExA.call(hkey, name, 0, type, data, size) [ unpackdw(type), data[0, unpackdw(size)] ] end - + def SetValue(hkey, name, type, data, size) check RegSetValueExA.call(hkey, name, 0, type, data, size) end - + def DeleteValue(hkey, name) check RegDeleteValue.call(hkey, name) end - + def DeleteKey(hkey, name) check RegDeleteKey.call(hkey, name) end - + def FlushKey(hkey) check RegFlushKey.call(hkey) end - + def CloseKey(hkey) check RegCloseKey.call(hkey) end - + def QueryInfoKey(hkey) subkeys = packdw(0) maxsubkeylen = packdw(0) @@ -488,14 +488,14 @@ module Win32 unpackdw(secdescs), unpackqw(wtime) ] end end - + # # utility functions # def self.expand_environ(str) str.gsub(/%([^%]+)%/) { ENV[$1] || ENV[$1.upcase] || $& } end - + @@type2name = { } %w[ REG_NONE REG_SZ REG_EXPAND_SZ REG_BINARY REG_DWORD @@ -505,24 +505,24 @@ module Win32 ].each do |type| @@type2name[Constants.const_get(type)] = type end - + def self.type2name(type) @@type2name[type] || type.to_s end - + def self.wtime2time(wtime) Time.at((wtime - 116444736000000000) / 10000000) end - + def self.time2wtime(time) time.to_i * 10000000 + 116444736000000000 end - + # # constructors # private_class_method :new - + def self.open(hkey, subkey, desired = KEY_READ, opt = REG_OPTION_RESERVED) subkey = subkey.chomp('\\') newkey = API.OpenKey(hkey.hkey, subkey, opt, desired) @@ -537,7 +537,7 @@ module Win32 obj end end - + def self.create(hkey, subkey, desired = KEY_ALL_ACCESS, opt = REG_OPTION_RESERVED) newkey, disp = API.CreateKey(hkey.hkey, subkey, opt, desired) obj = new(newkey, hkey, subkey, disp) @@ -551,12 +551,12 @@ module Win32 obj end end - + # # finalizer # @@final = proc { |hkey| proc { API.CloseKey(hkey[0]) if hkey[0] } } - + # # initialize # @@ -569,18 +569,18 @@ module Win32 ObjectSpace.define_finalizer self, @@final.call(@hkeyfinal) end attr_reader :hkey, :parent, :keyname, :disposition - + # # attributes # def created? @disposition == REG_CREATED_NEW_KEY end - + def open? !@hkey.nil? end - + def name parent = self name = @keyname @@ -589,35 +589,35 @@ module Win32 end name end - + def inspect "\#" end - + # # marshalling # def _dump(depth) raise TypeError, "can't dump Win32::Registry" end - + # # open/close # def open(subkey, desired = KEY_READ, opt = REG_OPTION_RESERVED, &blk) self.class.open(self, subkey, desired, opt, &blk) end - + def create(subkey, desired = KEY_ALL_ACCESS, opt = REG_OPTION_RESERVED, &blk) self.class.create(self, subkey, desired, opt, &blk) end - + def close API.CloseKey(@hkey) @hkey = @parent = @keyname = nil @hkeyfinal[0] = nil end - + # # iterator # @@ -640,7 +640,7 @@ module Win32 index end alias each each_value - + def each_key index = 0 while true @@ -654,13 +654,13 @@ module Win32 end index end - + def keys keys_ary = [] each_key { |key,| keys_ary << key } keys_ary end - + # # reader # @@ -686,7 +686,7 @@ module Win32 raise TypeError, "Type #{type} is not supported." end end - + def [](name, *rtype) type, data = read(name, *rtype) case type @@ -698,11 +698,11 @@ module Win32 raise TypeError, "Type #{type} is not supported." end end - + def read_s(name) read(name, REG_SZ)[1] end - + def read_s_expand(name) type, data = read(name, REG_SZ, REG_EXPAND_SZ) if type == REG_EXPAND_SZ @@ -711,15 +711,15 @@ module Win32 data end end - + def read_i(name) read(name, REG_DWORD, REG_DWORD_BIG_ENDIAN, REG_QWORD)[1] end - + def read_bin(name) read(name, REG_BINARY)[1] end - + # # writer # @@ -742,7 +742,7 @@ module Win32 end API.SetValue(@hkey, name, type, data, data.length) end - + def []=(name, rtype, value = nil) if value write name, rtype, value @@ -760,19 +760,19 @@ module Win32 end value end - + def write_s(name, value) write name, REG_SZ, value.to_s end - + def write_i(name, value) write name, REG_DWORD, value.to_i end - + def write_bin(name, value) write name, REG_BINARY, value.to_s end - + # # delete # @@ -780,7 +780,7 @@ module Win32 API.DeleteValue(@hkey, name) end alias delete delete_value - + def delete_key(name, recursive = false) if recursive open(name, KEY_ALL_ACCESS) do |reg| @@ -802,14 +802,14 @@ module Win32 raise Error.new(5) ## ERROR_ACCESS_DENIED end end - + # # flush # def flush API.FlushKey @hkey end - + # # key information # diff --git a/ext/Win32API/lib/win32/resolv.rb b/ext/Win32API/lib/win32/resolv.rb index 92336fac28..5730586d24 100644 --- a/ext/Win32API/lib/win32/resolv.rb +++ b/ext/Win32API/lib/win32/resolv.rb @@ -8,13 +8,13 @@ require 'win32/registry' module Win32 module Resolv API = Registry::API - + def self.get_hosts_path path = get_hosts_dir path = File.expand_path('hosts', path) File.exist?(path) ? path : nil end - + def self.get_resolv_info search, nameserver = get_info if search.empty? @@ -42,7 +42,7 @@ if info.unpack('V5')[4] == 2 # VER_PLATFORM_WIN32_NT #==================================================================== module_eval <<-'__EOS__', __FILE__, __LINE__+1 TCPIP_NT = 'SYSTEM\CurrentControlSet\Services\Tcpip\Parameters' - + class << self private def get_hosts_dir @@ -50,7 +50,7 @@ if info.unpack('V5')[4] == 2 # VER_PLATFORM_WIN32_NT reg.read_s_expand('DataBasePath') end end - + def get_info search = nil nameserver = [] @@ -60,7 +60,7 @@ if info.unpack('V5')[4] == 2 # VER_PLATFORM_WIN32_NT search = slist.split(/,\s*/) unless slist.empty? rescue Registry::Error end - + if add_search = search.nil? search = [] begin @@ -76,7 +76,7 @@ if info.unpack('V5')[4] == 2 # VER_PLATFORM_WIN32_NT rescue Registry::Error end end - + reg.open('Interfaces') do |reg| reg.each_key do |iface,| reg.open(iface) do |regif| @@ -90,7 +90,7 @@ if info.unpack('V5')[4] == 2 # VER_PLATFORM_WIN32_NT end rescue Registry::Error end - + if add_search begin [ 'Domain', 'DhcpDomain' ].each do |key| @@ -120,16 +120,16 @@ else TCPIP_9X = 'SYSTEM\CurrentControlSet\Services\VxD\MSTCP' DHCP_9X = 'SYSTEM\CurrentControlSet\Services\VxD\DHCP' WINDOWS = 'Software\Microsoft\Windows\CurrentVersion' - + class << self # private - + def get_hosts_dir Registry::HKEY_LOCAL_MACHINE.open(WINDOWS) do |reg| reg.read_s_expand('SystemRoot') end end - + def get_info search = [] nameserver = [] @@ -146,13 +146,13 @@ else end rescue Registry::Error end - + dhcpinfo = get_dhcpinfo search.concat(dhcpinfo[0]) nameserver.concat(dhcpinfo[1]) [ search, nameserver ] end - + def get_dhcpinfo macaddrs = {} ipaddrs = {} @@ -161,7 +161,7 @@ else ipaddr.each { |ipaddr| ipaddrs[ipaddr] = 1 } end iflist = [ macaddrs, ipaddrs ] - + search = [] nameserver = [] version = -1 @@ -170,7 +170,7 @@ else version = API.unpackdw(reg.read_bin("Version")) rescue Registry::Error end - + reg.each_key do |key,| catch(:not_used) do reg.open(key) do |regdi| @@ -183,7 +183,7 @@ else end [ search, nameserver ] end - + def get_dhcpinfo_95(reg) dhcp = reg.read_bin("DhcpInfo") [ @@ -194,7 +194,7 @@ else reg.read_bin("OptionInfo"), ] end - + def get_dhcpinfo_98(reg) [ API.unpackdw(reg.read_bin("DhcpIPAddress")), @@ -204,7 +204,7 @@ else reg.read_bin("OptionInfo"), ] end - + def get_dhcpinfo_key(version, reg, iflist) info = case version when 1 @@ -225,7 +225,7 @@ else macaddr and macaddr.size == 6 and hwtype == 1 and iflist[0][macaddr] and iflist[1][ipaddr] - + size = opt.size idx = 0 while idx <= size @@ -249,11 +249,11 @@ else throw :not_used end end - + module WsControl WsControl = Win32API.new('wsock32.dll', 'WsControl', 'LLPPPP', 'L') WSAGetLastError = Win32API.new('wsock32.dll', 'WSAGetLastError', 'V', 'L') - + MAX_TDI_ENTITIES = 512 IPPROTO_TCP = 6 WSCTL_TCP_QUERY_INFORMATION = 0 @@ -269,7 +269,7 @@ else IF_MIB = 0x202 IF_MIB_STATS_ID = 1 IP_MIB_ADDRTABLE_ENTRY_ID = 0x102 - + def self.wsctl(tei_entity, tei_instance, toi_class, toi_type, toi_id, buffsize) @@ -295,7 +295,7 @@ else [ buff, API.unpackdw(buffsize) ] end private_class_method :wsctl - + def self.get_iflist # Get TDI Entity List entities, size = @@ -332,7 +332,7 @@ else end end end - + # Get IP Addresses entities.each do |entity, instance| if entity == CL_NL_ENTITY diff --git a/ext/bigdecimal/lib/bigdecimal/ludcmp.rb b/ext/bigdecimal/lib/bigdecimal/ludcmp.rb index 8f4888725e..176ed84caf 100644 --- a/ext/bigdecimal/lib/bigdecimal/ludcmp.rb +++ b/ext/bigdecimal/lib/bigdecimal/ludcmp.rb @@ -17,7 +17,7 @@ module LUSolve end if nrmrow>zero then scales <<= one.div(nrmrow,prec) - else + else raise "Singular matrix" end end diff --git a/ext/bigdecimal/lib/bigdecimal/math.rb b/ext/bigdecimal/lib/bigdecimal/math.rb index f3248a3c5c..24e928b901 100644 --- a/ext/bigdecimal/lib/bigdecimal/math.rb +++ b/ext/bigdecimal/lib/bigdecimal/math.rb @@ -30,10 +30,10 @@ # module BigMath - # Computes the square root of x to the specified number of digits of + # Computes the square root of x to the specified number of digits of # precision. # - # BigDecimal.new('2').sqrt(16).to_s + # BigDecimal.new('2').sqrt(16).to_s # -> "0.14142135623730950488016887242096975E1" # def sqrt(x,prec) @@ -120,7 +120,7 @@ module BigMath y end - # Computes the value of e (the base of natural logarithms) raised to the + # Computes the value of e (the base of natural logarithms) raised to the # power of x, to the specified number of digits of precision. # # If x is infinite or NaN, returns NaN. @@ -148,7 +148,7 @@ module BigMath y end - # Computes the natural logarithm of x to the specified number of digits + # Computes the natural logarithm of x to the specified number of digits # of precision. # # Returns x if x is infinite or NaN. diff --git a/ext/bigdecimal/lib/bigdecimal/newton.rb b/ext/bigdecimal/lib/bigdecimal/newton.rb index 59ac0f7f04..d78c3d7647 100644 --- a/ext/bigdecimal/lib/bigdecimal/newton.rb +++ b/ext/bigdecimal/lib/bigdecimal/newton.rb @@ -1,5 +1,5 @@ # -# newton.rb +# newton.rb # # Solves the nonlinear algebraic equation system f = 0 by Newton's method. # This program is not dependent on BigDecimal. @@ -28,7 +28,7 @@ require "bigdecimal/jacobian" module Newton include LUSolve include Jacobian - + def norm(fv,zero=0.0) s = zero n = fv.size diff --git a/ext/bigdecimal/lib/bigdecimal/util.rb b/ext/bigdecimal/lib/bigdecimal/util.rb index 09e926acd5..b5e48a2471 100644 --- a/ext/bigdecimal/lib/bigdecimal/util.rb +++ b/ext/bigdecimal/lib/bigdecimal/util.rb @@ -41,7 +41,7 @@ class BigDecimal < Numeric end # Converts a BigDecimal to a Rational. - def to_r + def to_r sign,digits,base,power = self.split numerator = sign*digits.to_i denomi_power = power - digits.size # base is always 10 diff --git a/ext/curses/view.rb b/ext/curses/view.rb index d9a82a57db..c134df615a 100644 --- a/ext/curses/view.rb +++ b/ext/curses/view.rb @@ -67,10 +67,10 @@ while TRUE else break end - i += 1 + i += 1 end #wscrl(i) - + when "p" #when KEY_UP i = 0 while i < n @@ -79,8 +79,8 @@ while TRUE else break end - i += 1 - end + i += 1 + end #wscrl(-i) when "q" diff --git a/ext/digest/lib/digest.rb b/ext/digest/lib/digest.rb index 30805c0a6d..ce0d00ad4a 100644 --- a/ext/digest/lib/digest.rb +++ b/ext/digest/lib/digest.rb @@ -23,7 +23,7 @@ module Digest class ::Digest::Class # creates a digest object and reads a given file, _name_. - # + # # p Digest::SHA256.file("X11R6.8.2-src.tar.bz2").hexdigest # # => "f02e3c85572dc9ad7cb77c2a638e3be24cc1b5bea9fdbb0b0299c9668475c534" def self.file(name) diff --git a/ext/dl/lib/dl/import.rb b/ext/dl/lib/dl/import.rb index 01ee2490e8..10b3d9bc17 100644 --- a/ext/dl/lib/dl/import.rb +++ b/ext/dl/lib/dl/import.rb @@ -149,7 +149,7 @@ module DL mname[0,1] = mname[0,1].downcase end @SYM[mname] = [sym,rdec,enc,dec] - + module_eval [ "def #{mname}(*args)", " sym,rdec,enc,dec = @SYM['#{mname}']", diff --git a/ext/dl/lib/dl/struct.rb b/ext/dl/lib/dl/struct.rb index 33f303fe22..5a784b9093 100644 --- a/ext/dl/lib/dl/struct.rb +++ b/ext/dl/lib/dl/struct.rb @@ -113,7 +113,7 @@ module DL } @size = DL.sizeof(@tys) end - + def parse_elem(elem) elem.strip! case elem @@ -135,7 +135,7 @@ module DL return [name,ty,num,enc,dec] end end # class Struct - + class Union < Struct def new ptr = DL::malloc(@size) diff --git a/ext/dl/lib/dl/types.rb b/ext/dl/lib/dl/types.rb index 1144917dae..9742f3bf56 100644 --- a/ext/dl/lib/dl/types.rb +++ b/ext/dl/lib/dl/types.rb @@ -9,7 +9,7 @@ module DL # ["alias name", # "type name", encoding_method, decoding_method, for function prototypes # "type name", encoding_method, decoding_method] for structures (not implemented) - + # for Windows ["DWORD", "unsigned long", nil, nil, "unsigned long", nil, nil], @@ -49,7 +49,7 @@ module DL "unsigned int", nil, nil], ["HWND", "unsigned int", nil, nil, "unsigned int", nil, nil], - + # Others ["uint", "unsigned int", nil, nil, "unsigned int", nil, nil], diff --git a/ext/dl/sample/c++sample.rb b/ext/dl/sample/c++sample.rb index 29887df845..649677efeb 100644 --- a/ext/dl/sample/c++sample.rb +++ b/ext/dl/sample/c++sample.rb @@ -15,7 +15,7 @@ LIBNAME = ARGV[0] || "libsample.so" class Person module Core extend DL::Importable - + dlload LIBNAME # mangled symbol names diff --git a/ext/dl/sample/drives.rb b/ext/dl/sample/drives.rb index 8a590404b1..40a740f360 100644 --- a/ext/dl/sample/drives.rb +++ b/ext/dl/sample/drives.rb @@ -43,7 +43,7 @@ types = [ "unknown", "no root dir", "Removable", - "Fixed", + "Fixed", "Remote", "CDROM", "RAM", diff --git a/ext/nkf/lib/kconv.rb b/ext/nkf/lib/kconv.rb index 4ffe8d984e..15b52de123 100644 --- a/ext/nkf/lib/kconv.rb +++ b/ext/nkf/lib/kconv.rb @@ -18,9 +18,9 @@ module Kconv # # Public Constants # - + #Constant of Encoding - + # Auto-Detect AUTO = NKF::AUTO # ISO-2022-JP @@ -47,16 +47,16 @@ module Kconv # # Private Constants # - + # Revision of kconv.rb REVISION = %q$Revision$ - + #Regexp of Encoding - + # Regexp of Shift_JIS string (private constant) RegexpShiftjis = /\A(?: [\x00-\x7f\xa1-\xdf] | - [\x81-\x9f\xe0-\xfc][\x40-\x7e\x80-\xfc] + [\x81-\x9f\xe0-\xfc][\x40-\x7e\x80-\xfc] )*\z/nx # Regexp of EUC-JP string (private constant) @@ -81,7 +81,7 @@ module Kconv # # Public Methods # - + # call-seq: # Kconv.kconv(str, out_code, in_code = Kconv::AUTO) # @@ -277,11 +277,11 @@ class String def kconv(out_code, in_code=Kconv::AUTO) Kconv::kconv(self, out_code, in_code) end - + # # to Encoding # - + # call-seq: # String#tojis -> string # diff --git a/ext/openssl/lib/net/ftptls.rb b/ext/openssl/lib/net/ftptls.rb index a21c1f6c3c..9cec04033d 100644 --- a/ext/openssl/lib/net/ftptls.rb +++ b/ext/openssl/lib/net/ftptls.rb @@ -14,7 +14,7 @@ = Version $Id$ - + = Notes Tested on FreeBSD 5-CURRENT and 4-STABLE - ruby 1.6.8 (2003-01-17) [i386-freebsd5] diff --git a/ext/openssl/lib/net/telnets.rb b/ext/openssl/lib/net/telnets.rb index 2b69280432..c7b75fce77 100644 --- a/ext/openssl/lib/net/telnets.rb +++ b/ext/openssl/lib/net/telnets.rb @@ -12,7 +12,7 @@ = Version $Id$ - + 2001/11/06: Contiributed to Ruby/OpenSSL project. == class Net::Telnet @@ -145,7 +145,7 @@ module Net end end end # preprocess - + alias waitfor_org waitfor def waitfor(options) @@ -181,7 +181,7 @@ module Net begin c = @rest + @sock.sysread(1024 * 1024) @dumplog.log_dump('<', c) if @options.has_key?("Dump_log") - if @options["Telnetmode"] + if @options["Telnetmode"] pos = 0 catch(:next){ while true @@ -213,11 +213,11 @@ module Net end @log.print(buf) if @options.has_key?("Output_log") line.concat(buf) - yield buf if block_given? + yield buf if block_given? rescue EOFError # End of file reached if line == '' line = nil - yield nil if block_given? + yield nil if block_given? end break end diff --git a/ext/pty/expect_sample.rb b/ext/pty/expect_sample.rb index 2a2e29f866..d3b072b83c 100644 --- a/ext/pty/expect_sample.rb +++ b/ext/pty/expect_sample.rb @@ -12,9 +12,9 @@ require 'expect' fnames = [] PTY.spawn("ftp ftp.ruby-lang.org") do |r_f,w_f,pid| w_f.sync = true - + $expect_verbose = false - + if !ENV['USER'].nil? username = ENV['USER'] elsif !ENV['LOGNAME'].nil? @@ -22,14 +22,14 @@ PTY.spawn("ftp ftp.ruby-lang.org") do |r_f,w_f,pid| else username = 'guest' end - + r_f.expect(/^(Name).*: |(word):|> /) do w_f.puts($1 ? "ftp" : $2 ? "#{username}@" : "cd pub/ruby") end r_f.expect("> ") do w_f.print "dir\n" end - + r_f.expect(/[^\-]> /) do |output| for x in output[0].split("\n") if x =~ /(ruby.*?\.tar\.gz)/ then diff --git a/ext/pty/script.rb b/ext/pty/script.rb index dbb933171f..903a6f75bd 100644 --- a/ext/pty/script.rb +++ b/ext/pty/script.rb @@ -18,7 +18,7 @@ PTY.spawn("/bin/csh") do |r_pty,w_pty,pid| w_pty.flush end end - + begin while true c = r_pty.sysread(512) diff --git a/ext/rational/lib/rational.rb b/ext/rational/lib/rational.rb index 65d8c44110..e1087e9669 100644 --- a/ext/rational/lib/rational.rb +++ b/ext/rational/lib/rational.rb @@ -6,7 +6,7 @@ # by Keiju ISHITSUKA(SHL Japan Inc.) # # Documentation by Kevin Jackson and Gavin Sinclair. -# +# # Performance improvements by Kurt Stephens. # # When you require 'rational', all interactions between numbers @@ -15,7 +15,7 @@ # 1.quo(2) # -> 0.5 # require 'rational' # 1.quo(2) # -> Rational(1,2) -# +# # See Rational for full documentation. # @@ -24,7 +24,7 @@ require "rational.so" # # Creates a Rational number (i.e. a fraction). +a+ and +b+ should be Integers: -# +# # Rational(1,3) # -> 1/3 # # Note: trying to construct a Rational with floating point or real values @@ -55,7 +55,7 @@ end # Examples: # Rational(5,6) # -> 5/6 # Rational(5) # -> 5/1 -# +# # Rational numbers are reduced to their lowest terms: # Rational(6,10) # -> 3/5 # diff --git a/ext/syslog/test.rb b/ext/syslog/test.rb index cfa33eff8f..5172aa981e 100644 --- a/ext/syslog/test.rb +++ b/ext/syslog/test.rb @@ -47,7 +47,7 @@ class TestSyslog < Test::Unit::TestCase Syslog.close # given parameters - Syslog.open("foo", Syslog::LOG_NDELAY | Syslog::LOG_PERROR, Syslog::LOG_DAEMON) + Syslog.open("foo", Syslog::LOG_NDELAY | Syslog::LOG_PERROR, Syslog::LOG_DAEMON) assert_equal('foo', Syslog.ident) assert_equal(Syslog::LOG_NDELAY | Syslog::LOG_PERROR, Syslog.options) diff --git a/ext/win32ole/extconf.rb b/ext/win32ole/extconf.rb index cee922554a..ed6bf83cfa 100644 --- a/ext/win32ole/extconf.rb +++ b/ext/win32ole/extconf.rb @@ -20,7 +20,7 @@ end def create_win32ole_makefile if have_library("ole32") and have_library("oleaut32") and - have_library("uuid") and + have_library("uuid") and have_library("user32") and have_library("kernel32") and have_library("advapi32") and diff --git a/ext/win32ole/sample/ieconst.rb b/ext/win32ole/sample/ieconst.rb index 234272c7ed..2c6a7a383c 100644 --- a/ext/win32ole/sample/ieconst.rb +++ b/ext/win32ole/sample/ieconst.rb @@ -20,7 +20,7 @@ end # Remark!!! CONSTANTS has not tested enoughly!!! # CONSTANTS is alpha release. # If there are constants which first letter is not [a-zA-Z], -# like a '_Foo', then maybe you can access the value by +# like a '_Foo', then maybe you can access the value by # using CONSTANTS['_Foo'] #------------------------------------------------------------ IE_CONST::CONSTANTS.each do |k, v| diff --git a/ext/win32ole/sample/ienavi.rb b/ext/win32ole/sample/ienavi.rb index c7fa3f5ec2..8b279ddaae 100644 --- a/ext/win32ole/sample/ienavi.rb +++ b/ext/win32ole/sample/ienavi.rb @@ -26,7 +26,7 @@ ev = WIN32OLE_EVENT.new(ie, 'DWebBrowserEvents') ev.on_event {|*args| default_handler(*args)} ev.on_event("NavigateComplete") {|url| navigate(url)} -ev.on_event("Quit") {|*args| stop_msg_loop} +ev.on_event("Quit") {|*args| stop_msg_loop} $LOOP = TRUE while ($LOOP) diff --git a/ext/win32ole/sample/oledirs.rb b/ext/win32ole/sample/oledirs.rb index 1c77e76f14..dbacc2131d 100644 --- a/ext/win32ole/sample/oledirs.rb +++ b/ext/win32ole/sample/oledirs.rb @@ -7,7 +7,7 @@ require "win32ole" def listup(items) # items.each do |i| for i in items - puts i.name + puts i.name end end diff --git a/ext/win32ole/sample/olegen.rb b/ext/win32ole/sample/olegen.rb index 48d86893fe..9249561f65 100644 --- a/ext/win32ole/sample/olegen.rb +++ b/ext/win32ole/sample/olegen.rb @@ -50,7 +50,7 @@ class WIN32COMGen ts = '' typedetails.each do |t| case t - when 'CARRAY', 'VOID', 'UINT', 'RESULT', 'DECIMAL', 'I8', 'UI8' + when 'CARRAY', 'VOID', 'UINT', 'RESULT', 'DECIMAL', 'I8', 'UI8' # raise "Sorry type\"" + t + "\" not supported" ts << "\"??? NOT SUPPORTED TYPE:`#{t}'\"" when 'USERDEFINED', 'Unknown Type 9' @@ -81,7 +81,7 @@ class WIN32COMGen generate_argtype(param.ole_type_detail) }.join(", ") if proptypes - types += ", " if types.size > 0 + types += ", " if types.size > 0 types += generate_argtype(proptypes) end types @@ -98,8 +98,8 @@ class WIN32COMGen end def generate_method_help(method, type = nil) - str = " # " - if type + str = " # " + if type str += type else str += method.return_type @@ -124,7 +124,7 @@ class WIN32COMGen def generate_method_args_help(method) args = [] method.params.each_with_index {|param, i| - h = " # #{param.ole_type} arg#{i} --- #{param.name}" + h = " # #{param.ole_type} arg#{i} --- #{param.name}" inout = [] inout.push "IN" if param.input? inout.push "OUT" if param.output? @@ -167,14 +167,14 @@ class WIN32COMGen method.visible? && method.size_params > 0 }.each do |method| - types = method.return_type_detail + types = method.return_type_detail io.puts "\n" io.puts generate_method_help(method, types[0]) io.puts " def #{method.name}" if klass.ole_type == "Class" - io.print " OLEProperty.new(@dispatch, #{method.dispid}, [" + io.print " OLEProperty.new(@dispatch, #{method.dispid}, [" else - io.print " OLEProperty.new(self, #{method.dispid}, [" + io.print " OLEProperty.new(self, #{method.dispid}, [" end io.print generate_argtypes(method, nil) io.print "], [" @@ -321,8 +321,8 @@ STR ole_classes(typelib).select{|klass| klass.visible? && - (klass.ole_type == "Class" || - klass.ole_type == "Interface" || + (klass.ole_type == "Class" || + klass.ole_type == "Interface" || klass.ole_type == "Dispatch" || klass.ole_type == "Enum") }.each do |klass| @@ -330,7 +330,7 @@ STR end begin @ole.quit if @ole - rescue + rescue end end end diff --git a/ext/win32ole/sample/xml.rb b/ext/win32ole/sample/xml.rb index b95d6d5275..4b1a54dc75 100644 --- a/ext/win32ole/sample/xml.rb +++ b/ext/win32ole/sample/xml.rb @@ -1,11 +1,11 @@ -# +# # This file created by olegen.rb as following. # ruby olegen.rb 'Microsoft XML, version 2.0' > xml.rb -# +# require 'win32ole' require 'win32ole/property' -# +# module IXMLDOMImplementation include WIN32OLE::VARIANT attr_reader :lastargs @@ -343,7 +343,7 @@ module OLEtagDOMNodeType NODE_NOTATION = 12 end -# +# module IXMLDOMNodeList include WIN32OLE::VARIANT attr_reader :lastargs @@ -380,7 +380,7 @@ module IXMLDOMNodeList end end -# +# module IXMLDOMNamedNodeMap include WIN32OLE::VARIANT attr_reader :lastargs @@ -464,7 +464,7 @@ module IXMLDOMNamedNodeMap end end -# +# module IXMLDOMDocument include WIN32OLE::VARIANT attr_reader :lastargs @@ -1040,7 +1040,7 @@ module IXMLDOMDocument end end -# +# module IXMLDOMDocumentType include WIN32OLE::VARIANT attr_reader :lastargs @@ -1368,7 +1368,7 @@ module IXMLDOMDocumentType end end -# +# module IXMLDOMElement include WIN32OLE::VARIANT attr_reader :lastargs @@ -1752,7 +1752,7 @@ module IXMLDOMElement end end -# +# module IXMLDOMAttribute include WIN32OLE::VARIANT attr_reader :lastargs @@ -2080,7 +2080,7 @@ module IXMLDOMAttribute end end -# +# module IXMLDOMDocumentFragment include WIN32OLE::VARIANT attr_reader :lastargs @@ -2384,7 +2384,7 @@ module IXMLDOMDocumentFragment end end -# +# module IXMLDOMText include WIN32OLE::VARIANT attr_reader :lastargs @@ -2771,7 +2771,7 @@ module IXMLDOMText end end -# +# module IXMLDOMCharacterData include WIN32OLE::VARIANT attr_reader :lastargs @@ -3149,7 +3149,7 @@ module IXMLDOMCharacterData end end -# +# module IXMLDOMComment include WIN32OLE::VARIANT attr_reader :lastargs @@ -3527,7 +3527,7 @@ module IXMLDOMComment end end -# +# module IXMLDOMCDATASection include WIN32OLE::VARIANT attr_reader :lastargs @@ -3914,7 +3914,7 @@ module IXMLDOMCDATASection end end -# +# module IXMLDOMProcessingInstruction include WIN32OLE::VARIANT attr_reader :lastargs @@ -4242,7 +4242,7 @@ module IXMLDOMProcessingInstruction end end -# +# module IXMLDOMEntityReference include WIN32OLE::VARIANT attr_reader :lastargs @@ -4608,7 +4608,7 @@ module IXMLDOMParseError end end -# +# module IXMLDOMNotation include WIN32OLE::VARIANT attr_reader :lastargs @@ -4928,7 +4928,7 @@ module IXMLDOMNotation end end -# +# module IXMLDOMEntity include WIN32OLE::VARIANT attr_reader :lastargs diff --git a/ext/win32ole/tests/testOLEMETHOD.rb b/ext/win32ole/tests/testOLEMETHOD.rb index 390c9999f8..6bd879b409 100644 --- a/ext/win32ole/tests/testOLEMETHOD.rb +++ b/ext/win32ole/tests/testOLEMETHOD.rb @@ -1,4 +1,4 @@ -# You need RubyUnit and MS Excel and MSI to run this test script +# You need RubyUnit and MS Excel and MSI to run this test script require 'rubyunit' diff --git a/ext/win32ole/tests/testOLEPARAM.rb b/ext/win32ole/tests/testOLEPARAM.rb index 4014fadbfc..6c6af2dbf1 100644 --- a/ext/win32ole/tests/testOLEPARAM.rb +++ b/ext/win32ole/tests/testOLEPARAM.rb @@ -1,4 +1,4 @@ -# You need RubyUnit and MS Excel and MSI to run this test script +# You need RubyUnit and MS Excel and MSI to run this test script require 'rubyunit' @@ -46,7 +46,7 @@ class TestOLEPARAM < RUNIT::TestCase f = methods.find {|m| m.name == 'SaveAs'} assert(f.params[0].input?) end - + def test_output classes = WIN32OLE_TYPE.ole_classes(MS_EXCEL_TYPELIB) methods = classes.find {|c| c.name == 'Worksheet'}.ole_methods diff --git a/ext/win32ole/tests/testOLETYPE.rb b/ext/win32ole/tests/testOLETYPE.rb index d4eb1146e1..0f86781130 100644 --- a/ext/win32ole/tests/testOLETYPE.rb +++ b/ext/win32ole/tests/testOLETYPE.rb @@ -1,4 +1,4 @@ -# You need RubyUnit and MS Excel and MSI to run this test script +# You need RubyUnit and MS Excel and MSI to run this test script require 'rubyunit' diff --git a/ext/win32ole/tests/testOLEVARIABLE.rb b/ext/win32ole/tests/testOLEVARIABLE.rb index b4bb0b57d9..91ebcb30f3 100644 --- a/ext/win32ole/tests/testOLEVARIABLE.rb +++ b/ext/win32ole/tests/testOLEVARIABLE.rb @@ -1,4 +1,4 @@ -# You need RubyUnit and MS Excel and MSI to run this test script +# You need RubyUnit and MS Excel and MSI to run this test script require 'rubyunit' diff --git a/ext/win32ole/tests/testVARIANT.rb b/ext/win32ole/tests/testVARIANT.rb index f274778f27..a7b1ee0af3 100644 --- a/ext/win32ole/tests/testVARIANT.rb +++ b/ext/win32ole/tests/testVARIANT.rb @@ -1,4 +1,4 @@ -# You need RubyUnit and MS Excel and MSI to run this test script +# You need RubyUnit and MS Excel and MSI to run this test script require 'rubyunit' diff --git a/ext/win32ole/tests/testWIN32OLE.rb b/ext/win32ole/tests/testWIN32OLE.rb index d7f9dd2543..29ed829020 100644 --- a/ext/win32ole/tests/testWIN32OLE.rb +++ b/ext/win32ole/tests/testWIN32OLE.rb @@ -1,4 +1,4 @@ -# You need RubyUnit and MS Excel and MSI to run this test script +# You need RubyUnit and MS Excel and MSI to run this test script require 'runit/testcase' require 'runit/cui/testrunner' @@ -289,7 +289,7 @@ class TestWin32OLE_WITH_MSI < RUNIT::TestCase @record = installer.CreateRecord(2) end - # Sorry, this test fails. + # Sorry, this test fails. # Win32OLE does not support this style to set property. # Use Win32OLE#setproperty or Win32OLE#[]= . # def test_invoke @@ -317,7 +317,7 @@ end # a subclass of Win32OLE # override new() and connect() class MyExcel # of the contents of all the files # given as command-line arguments, or $stdin # (in the case where there are no -# arguments). $< supports methods similar to a +# arguments). $< supports methods similar to a # +File+ object: # +inmode+, +close+, # closed?, +each+, @@ -91,7 +91,7 @@ alias $DEFAULT_OUTPUT $> # +eof+, eof?, +file+, # +filename+, +fileno+, # +getc+, +gets+, +lineno+, -# lineno=, +path+, +# lineno=, +path+, # +pos+, pos=, # +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 9b901a7597..d175ec158b 100644 --- a/lib/base64.rb +++ b/lib/base64.rb @@ -1,7 +1,7 @@ # # = base64.rb: methods for base64-encoding and -decoding strings # -# Author:: Yukihiro Matsumoto +# Author:: Yukihiro Matsumoto # Documentation:: Dave Thomas and Gavin Sinclair # # Until Ruby 1.8.1, these methods were defined at the top-level. Now @@ -16,7 +16,7 @@ require "kconv" # The Base64 module provides for the encoding (#encode64) and decoding # (#decode64) of binary data using a Base64 representation. -# +# # The following particular features are also provided: # - encode into lines of a given length (#b64encode) # - decode the special format specified in RFC2047 for the @@ -24,12 +24,12 @@ require "kconv" # # == 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" # @@ -78,7 +78,7 @@ module Base64 decode64($1) } str = Kconv::toeuc(str) - str.gsub!(/\n/, ' ') + str.gsub!(/\n/, ' ') str.gsub!(/\0/, '') str end @@ -135,7 +135,7 @@ module Base64 # +len+ (default 60) characters. # # require 'base64' - # data = "Now is the time for all good coders\nto learn Ruby" + # data = "Now is the time for all good coders\nto learn Ruby" # Base64.b64encode(data) # # Generates: @@ -147,7 +147,7 @@ module Base64 encode64(bin).scan(/.{1,#{len}}/) do print $&, "\n" end - end + end module Deprecated # :nodoc: 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 (gotoken@notwork.org). +# +# Created by Gotoken (gotoken@notwork.org). # # 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 - # + # # Generates: - # + # # user system total real # for: 1.016667 0.016667 1.033333 ( 0.485749) # times: 1.450000 0.016667 1.466667 ( 0.681367) # upto: 1.533333 0.000000 1.533333 ( 0.722166) # >total: 4.000000 0.033333 4.033333 ( 1.889282) # >avg: 1.333333 0.011111 1.344444 ( 0.629761) - # + # 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 - # + # # Generates: - # + # # 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 - # + # # Generates: - # + # # Rehearsal ----------------------------------------- # sort! 11.928000 0.010000 11.938000 ( 12.756000) # sort 13.048000 0.020000 13.068000 ( 13.857000) # ------------------------------- total: 25.006000sec - # + # # user system total real # sort! 12.959000 0.010000 12.969000 ( 13.793000) # sort 12.007000 0.000000 12.007000 ( 12.791000) @@ -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 # # %u:: Replaced by the user CPU time, as reported by Tms#utime. # %y:: Replaced by the system CPU time, as reported by #stime (Mnemonic: y of "s*y*stem") - # %U:: Replaced by the children's user CPU time, as reported by Tms#cutime + # %U:: Replaced by the children's user CPU time, as reported by Tms#cutime # %Y:: Replaced by the children's system CPU time, as reported by Tms#cstime # %t:: Replaced by the total CPU time, as reported by Tms#total # %r:: Replaced by the elapsed real time, as reported by Tms#real # %n:: Replaced by the label string, as reported by Tms#label (Mnemonic: n of "*n*ame") - # + # # If _fmtstr_ is not given, FMTSTR is used as default value, detailing the # user, system and real elapsed time. - # + # 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 deb3caaaf3..418a18c6e2 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 # -# 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 @@ -77,18 +77,18 @@ require 'English' # # # 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: # @@ -107,7 +107,7 @@ require 'English' # # === 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 @@ -138,7 +138,7 @@ require 'English' # # 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 @@ -152,57 +152,57 @@ require 'English' # 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' @@ -210,37 +210,37 @@ require 'English' # 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 @@ -264,7 +264,7 @@ require 'English' # end # end # end -# +# # # add HTML generation methods # CGI.new("html3") # html3.2 # CGI.new("html4") # html4.01 (Strict) @@ -286,7 +286,7 @@ class CGI REVISION = '$Id$' #:nodoc: - NEEDS_BINMODE = true if /WIN/ni.match(RUBY_PLATFORM) + NEEDS_BINMODE = true if /WIN/ni.match(RUBY_PLATFORM) # Path separators in different environments. PATH_SEPARATOR = {'UNIX'=>'/', 'WINDOWS'=>'\\', 'MACINTOSH'=>':'} @@ -321,7 +321,7 @@ class CGI # :startdoc: - def env_table + def env_table ENV end @@ -431,7 +431,7 @@ class CGI # print CGI::unescapeElement( # CGI::escapeHTML('
'), "A", "IMG") # # "<BR>" - # + # # print CGI::unescapeElement( # CGI::escapeHTML('
'), ["A", "IMG"]) # # "<BR>" @@ -475,7 +475,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. @@ -485,19 +485,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", @@ -512,9 +512,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" @@ -533,8 +533,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") @@ -670,13 +670,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'], @@ -689,16 +689,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: @@ -755,16 +755,16 @@ class CGI # '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' @@ -787,7 +787,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. @@ -914,7 +914,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. @@ -1050,7 +1050,7 @@ class CGI (not /MSIE/ni.match(env_table['HTTP_USER_AGENT'])) filename = CGI::unescape(filename) end - + /Content-Type: ([^\s]*)/ni.match(head) content_type = ($1 or "") @@ -1169,7 +1169,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] @@ -1216,7 +1216,7 @@ class CGI # # # # # # - # + # # print CGI::pretty("", "\t") # # # # @@ -1301,7 +1301,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 @@ -1334,7 +1334,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. @@ -1414,10 +1414,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) @@ -1455,23 +1455,23 @@ class CGI # # foo # # bar # # baz - # + # # checkbox_group("name", ["foo"], ["bar", true], "baz") # # foo # # bar # # baz - # + # # checkbox_group("name", ["1", "Foo"], ["2", "Bar", true], "Baz") # # Foo # # Bar # # 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) @@ -1507,13 +1507,13 @@ class CGI # # file_field("name") # # - # + # # file_field("name", 40) # # - # + # # file_field("name", 40, 100) # # - # + # # file_field("NAME" => "name", "SIZE" => 40) # # def file_field(name = "", size = 20, maxlength = nil) @@ -1533,7 +1533,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. # @@ -1541,19 +1541,19 @@ class CGI # # form{ "string" } # #
string
- # + # # form("get") { "string" } # #
string
- # + # # form("get", "url") { "string" } # #
string
- # + # # form("METHOD" => "post", "ENCTYPE" => "enctype") { "string" } # #
string
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" @@ -1585,10 +1585,10 @@ class CGI # # hidden("name") # # - # + # # hidden("name", "value") # # - # + # # hidden("NAME" => "name", "VALUE" => "reset", "ID" => "foo") # # def hidden(name = "", value = nil) @@ -1611,36 +1611,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" } # # string - # + # # html("LANG" => "ja") { "string" } # # string - # + # # html("DOCTYPE" => false) { "string" } # # string - # + # # html("DOCTYPE" => '') { "string" } # # string - # + # # html("PRETTY" => " ") { "" } # # # # # # # # # # - # + # # html("PRETTY" => "\t") { "" } # # # # # # # # # # - # + # # html("PRETTY") { "" } # # = html("PRETTY" => " ") { "" } - # + # # html(if $VERBOSE then "PRETTY" end) { "HTML string" } # def html(attributes = {}) # :yield: @@ -1679,17 +1679,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") # # - # + # # image_button("url", "name", "string") # # - # + # # image_button("SRC" => "url", "ATL" => "string") # # def image_button(src = "", name = nil, alt = nil) @@ -1715,7 +1715,7 @@ class CGI # # img("src", "alt", 100, 50) # # alt - # + # # img("SRC" => "src", "ALT" => "alt", "WIDTH" => 100, "HEIGHT" => 50) # # alt def img(src = "", alt = "", width = nil, height = nil) @@ -1741,15 +1741,15 @@ class CGI # # multipart_form{ "string" } # #
string
- # + # # multipart_form("url") { "string" } # #
string
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" @@ -1777,13 +1777,13 @@ class CGI # # password_field("name") # # - # + # # password_field("name", "value") # # - # + # # password_field("password", "value", 80, 200) # # - # + # # password_field("NAME" => "name", "VALUE" => "value") # # def password_field(name = "", value = nil, size = 40, maxlength = nil) @@ -1819,21 +1819,21 @@ class CGI # # # # # # - # + # # popup_menu("name", ["foo"], ["bar", true], "baz") # # - # + # # popup_menu("name", ["1", "Foo"], ["2", "Bar", true], "Baz") # # - # + # # popup_menu("NAME" => "name", "SIZE" => 2, "MULTIPLE" => true, # "VALUES" => [["1", "Foo"], ["2", "Bar", true], "Baz"]) # # - # + # # radio_button("name", "value", true) # # - # + # # radio_button("NAME" => "name", "VALUE" => "value", "ID" => "foo") # # def radio_button(name = "", value = nil, checked = nil) @@ -1905,28 +1905,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") # # foo # # bar # # baz - # + # # radio_group("name", ["foo"], ["bar", true], "baz") # # foo # # bar # # baz - # + # # radio_group("name", ["1", "Foo"], ["2", "Bar", true], "Baz") # # Foo # # Bar # # 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) @@ -1958,10 +1958,10 @@ class CGI # # reset # # - # + # # reset("reset") # # - # + # # reset("VALUE" => "reset", "ID" => "foo") # # def reset(value = nil, name = nil) @@ -1985,13 +1985,13 @@ class CGI # # submit # # - # + # # submit("ok") # # - # + # # submit("ok", "button1") # # - # + # # submit("VALUE" => "ok", "NAME" => "button1", "ID" => "foo") # # def submit(value = nil, name = nil) @@ -2014,16 +2014,16 @@ class CGI # # text_field("name") # # - # + # # text_field("name", "value") # # - # + # # text_field("name", "value", 80) # # - # + # # text_field("name", "value", 80, 200) # # - # + # # text_field("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 2dea08cf75..0d7bfcbdae 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
tag in HTML 4 generation, which @@ -322,11 +322,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 @@ -358,7 +358,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 3d204d5dc0..7a9e68f6e5 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 (william@williamwebber.com) -# +# # == 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/complex.rb b/lib/complex.rb index 808cecc95d..b79e8262af 100644 --- a/lib/complex.rb +++ b/lib/complex.rb @@ -1,5 +1,5 @@ # -# complex.rb - +# complex.rb - # $Release Version: 0.5 $ # $Revision: 1.3 $ # $Date: 1998/07/08 10:05:28 $ @@ -14,7 +14,7 @@ # Complex numbers can be created in the following manner: # - Complex(a, b) # - Complex.polar(radius, theta) -# +# # Additionally, note the following: # - Complex::I (the mathematical constant i) # - Numeric#im (e.g. 5.im -> 0+5i) @@ -38,14 +38,14 @@ class Numeric def im Complex(0, self) end - + # # The real part of a complex number, i.e. self. # def real self end - + # # The imaginary part of a complex number, i.e. 0. # @@ -53,7 +53,7 @@ class Numeric 0 end alias imag image - + # # See Complex#arg. # @@ -61,14 +61,14 @@ class Numeric Math.atan2!(0, self) end alias angle arg - + # # See Complex#polar. # def polar return abs, arg end - + # # See Complex#conjugate (short answer: returns self). # @@ -145,7 +145,7 @@ class Complex < Numeric x + y end end - + # # Subtraction with real or complex number. # @@ -161,7 +161,7 @@ class Complex < Numeric x - y end end - + # # Multiplication with real or complex number. # @@ -177,7 +177,7 @@ class Complex < Numeric x * y end end - + # # Division by real or complex number. # @@ -191,7 +191,7 @@ class Complex < Numeric x/y end end - + def quo(other) Complex(@real.quo(1), @image.quo(1)) / other end @@ -240,7 +240,7 @@ class Complex < Numeric x**y end end - + # # Remainder after division by a real or complex number. # @@ -254,7 +254,7 @@ class Complex < Numeric x % y end end - + #-- # def divmod(other) # if other.kind_of?(Complex) @@ -269,7 +269,7 @@ class Complex < Numeric # end # end #++ - + # # Absolute value (aka modulus): distance from the zero point on the complex # plane. @@ -277,14 +277,14 @@ class Complex < Numeric def abs Math.hypot(@real, @image) end - + # # Square of the absolute value. # def abs2 @real*@real + @image*@image end - + # # Argument (angle from (1,0) on the complex plane). # @@ -292,14 +292,14 @@ class Complex < Numeric Math.atan2!(@image, @real) end alias angle arg - + # # Returns the absolute value _and_ the argument. # def polar return abs, arg end - + # # Complex conjugate (z + z.conjugate = 2 * z.real). # @@ -307,14 +307,14 @@ class Complex < Numeric Complex(@real, -@image) end alias conj conjugate - + # # Compares the absolute values of the two numbers. # def <=> (other) self.abs <=> other.abs end - + # # Test for numerical equality (a == a + 0i). # @@ -345,7 +345,7 @@ class Complex < Numeric def denominator @real.denominator.lcm(@image.denominator) end - + # # FIXME # @@ -354,7 +354,7 @@ class Complex < Numeric Complex(@real.numerator*(cd/@real.denominator), @image.numerator*(cd/@image.denominator)) end - + # # Standard string representation of the complex number. # @@ -381,14 +381,14 @@ class Complex < Numeric end end end - + # # Returns a hash code for the complex number. # def hash @real.hash ^ @image.hash end - + # # Returns "Complex(real, image)". # @@ -396,19 +396,19 @@ class Complex < Numeric sprintf("Complex(%s, %s)", @real.inspect, @image.inspect) end - + # # +I+ is the imaginary number. It exists at point (0,1) on the complex plane. # I = Complex(0,1) - + # The real part of a complex number. attr :real # The imaginary part of a complex number. attr :image alias imag image - + end class Integer @@ -457,7 +457,7 @@ module Math alias atan2! atan2 alias acosh! acosh alias asinh! asinh - alias atanh! atanh + alias atanh! atanh # Redefined to handle a Complex argument. def sqrt(z) @@ -477,7 +477,7 @@ module Math end end end - + # Redefined to handle a Complex argument. def exp(z) if Complex.generic?(z) @@ -486,7 +486,7 @@ module Math Complex(exp!(z.real) * cos!(z.image), exp!(z.real) * sin!(z.image)) end end - + # Redefined to handle a Complex argument. def cos(z) if Complex.generic?(z) @@ -496,7 +496,7 @@ module Math -sin!(z.real)*sinh!(z.image)) end end - + # Redefined to handle a Complex argument. def sin(z) if Complex.generic?(z) @@ -506,7 +506,7 @@ module Math cos!(z.real)*sinh!(z.image)) end end - + # Redefined to handle a Complex argument. def tan(z) if Complex.generic?(z) @@ -539,7 +539,7 @@ module Math sinh(z)/cosh(z) end end - + # Redefined to handle a Complex argument. def log(z) if Complex.generic?(z) and z >= 0 @@ -549,7 +549,7 @@ module Math Complex(log!(r.abs), theta) end end - + # Redefined to handle a Complex argument. def log10(z) if Complex.generic?(z) @@ -649,7 +649,7 @@ module Math module_function :asinh module_function :atanh! module_function :atanh - + end # Documentation comments: diff --git a/lib/csv.rb b/lib/csv.rb index f6c12fa285..66804b550e 100644 --- a/lib/csv.rb +++ b/lib/csv.rb @@ -1,13 +1,13 @@ # CSV -- module for generating/parsing CSV data. # Copyright (C) 2000-2004 NAKAMURA, Hiroshi . - + # $Id$ - + # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. - - + + class CSV class IllegalFormatError < RuntimeError; end @@ -97,7 +97,7 @@ class CSV def CSV.read(path, length = nil, offset = nil) CSV.parse(IO.read(path, length, offset)) end - + def CSV.readlines(path, rs = nil) reader = open_reader(path, 'r', ',', rs) begin @@ -181,7 +181,7 @@ class CSV end result_str end - + # Parse a line from string. Consider using CSV.parse_line instead. # To parse lines in CSV string, see EXAMPLE below. # @@ -239,7 +239,7 @@ class CSV end return parsed_cells, idx end - + # Convert a line from cells data to string. Consider using CSV.generate_line # instead. To generate multi-row CSV string, see EXAMPLE below. # @@ -299,7 +299,7 @@ class CSV end parsed_cells end - + # Private class methods. class << self private @@ -334,7 +334,7 @@ class CSV end nil else - writer = CSV::Writer.create(file, fs, rs) + writer = CSV::Writer.create(file, fs, rs) writer.close_on_terminate writer end @@ -480,7 +480,7 @@ class CSV last_idx = idx return :DT_EOS, idx, cell end - + def generate_body(cell, out_dev, fs, rs) if cell.nil? # empty @@ -498,7 +498,7 @@ class CSV end end end - + def generate_separator(type, out_dev, fs, rs) case type when :DT_COLSEP @@ -586,7 +586,7 @@ class CSV # Define if needed. end end - + class StringReader < Reader def initialize(string, fs = ',', rs = nil) @@ -800,7 +800,7 @@ private # returns char at idx if n == nil. # returns a partial string, from idx to (idx + n) if n != nil. at EOF, # the string size could not equal to arg n. - def [](idx, n = nil) + def [](idx, n = nil) if idx < 0 return nil end @@ -846,7 +846,7 @@ private end end alias get [] - + # drop a string from the stream. # returns dropped size. at EOF, dropped size might not equals to arg n. # Once you drop the head of the stream, access to the dropped part via [] @@ -878,11 +878,11 @@ private end size_dropped end - + def is_eos? return idx_is_eos?(0) end - + # WARN: Do not instantiate this class directly. Define your own class # which derives this class and define 'read' instance method. def initialize @@ -893,13 +893,13 @@ private add_buf @cur_buf = @buf_tail_idx end - + protected def terminate while (rel_buf); end end - + # protected method 'read' must be defined in derived classes. # CAUTION: Returning a string which size is not equal to 'size' means # EnfOfStream. When it is not at EOS, you must block the callee, try to @@ -907,9 +907,9 @@ private def read(size) # raise EOFError raise NotImplementedError.new('Method read must be defined in a derived class.') end - + private - + def buf_size(idx) @buf_list[idx].size end @@ -937,7 +937,7 @@ private true end end - + def rel_buf if (@cur_buf < 0) return false @@ -951,11 +951,11 @@ private return true end end - + def idx_is_eos?(idx) (@is_eos and ((@cur_buf < 0) or (@cur_buf == @buf_tail_idx))) end - + BufSize = 1024 * 8 end @@ -974,7 +974,7 @@ private @s = s super() end - + def close terminate end @@ -984,7 +984,7 @@ private def read(size) @s.read(size) end - + def terminate super() end diff --git a/lib/debug.rb b/lib/debug.rb index 9ae119f8fb..0c0b1d86d0 100644 --- a/lib/debug.rb +++ b/lib/debug.rb @@ -256,7 +256,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 @@ -335,7 +335,7 @@ class Context stdout.print "Breakpoints:\n" for b in break_points if b[0] and b[1] == 0 - stdout.printf " %d %s:%s\n", n, b[2], b[3] + stdout.printf " %d %s:%s\n", n, b[2], b[3] end n += 1 end @@ -751,7 +751,7 @@ EOHELP when 'end' @frames.shift - when 'raise' + when 'raise' excn_handle(file, line, id, binding) end @@ -921,7 +921,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 43549946c9..9a4f76f164 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 # @_sd_obj = obj # store obj for future use # end -# +# # def __getobj__ # @_sd_obj # return object we are delegating to, required # end -# +# # def __setobj__(obj) # @_sd_obj = obj # change delegation object, a feature we're providing # end -# +# # # ... # end @@ -159,10 +159,10 @@ class Delegator target.__send__(m, *args, &block) 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) diff --git a/lib/drb/drb.rb b/lib/drb/drb.rb index 795dc1ac4b..90a68d831e 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 !@loggers.has_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) families = Hash[*infos.collect { |af, *_| af }.uniq.zip([]).flatten] @@ -848,7 +848,7 @@ module DRb return TCPServer.open(port) 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 @@ -894,7 +894,7 @@ module DRb def peeraddr @socket.peeraddr end - + # Get the socket. def stream; @socket; end @@ -902,7 +902,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) @@ -932,14 +932,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 @@ -976,16 +976,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 @@ -1002,7 +1002,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]) @@ -1052,7 +1052,7 @@ module DRb end # Get the URI of the remote object. - def __drburi + def __drburi @uri end @@ -1080,7 +1080,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 @@ -1103,7 +1103,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 @@ -1115,7 +1115,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 @@ -1266,14 +1266,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, @@ -1363,7 +1363,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 @@ -1456,7 +1456,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. @@ -1464,14 +1464,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.to_s) desc = any_to_s(obj) raise NoMethodError, "private method `#{msg_id}' called for #{desc}" @@ -1483,7 +1483,7 @@ module DRb end end public :check_insecure_method - + class InvokeMethod # :nodoc: def initialize(drb_server, client) @drb_server = drb_server @@ -1505,7 +1505,7 @@ module DRb perform_with_block }.value else - @result = Thread.new { + @result = Thread.new { Thread.current['DRb'] = info $SAFE = @safe_level perform_without_block @@ -1520,7 +1520,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 @@ -1536,7 +1536,7 @@ module DRb @argv = argv @block = block end - + def check_insecure_method @drb_server.check_insecure_method(@obj, @msg_id) end @@ -1545,7 +1545,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 @@ -1633,7 +1633,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 @@ -1648,8 +1648,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 @@ -1695,7 +1695,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. @@ -1766,7 +1766,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 7da8130c2b..33edddd01b 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 be40aea9f5..46ffb331e5 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 412b2ab9b5..2bcd12f5f5 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 8d1aba2969..813aa564df 100644 --- a/lib/e2mmap.rb +++ b/lib/e2mmap.rb @@ -59,7 +59,7 @@ module Exception2MessageMapper super cl.bind(self) unless cl == E2MM end - + # backward compatibility def E2MM.extend_to(b) c = eval("self", b) @@ -91,7 +91,7 @@ module Exception2MessageMapper # backward compatibility alias fail! fail def fail(err = nil, *rest) - begin + begin E2MM.Fail(self, err, *rest) rescue E2MM::ErrNotRegisteredException super @@ -101,7 +101,7 @@ module Exception2MessageMapper public :fail end - + # def_e2message(c, m) # c: exception # m: message_form @@ -110,7 +110,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 @@ -137,7 +137,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 @@ -187,8 +187,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 3a474b9ea5..112cf1d55b 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 @@ -68,39 +68,39 @@ # %q{...} to avoid trouble with the backslash. # # require "erb" -# +# # # Create template. # template = %q{ # From: James Edward Gray II # 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 " # priorities = [ "Run Ruby Quiz", # "Document Modules", # "Answer Questions on Ruby Talk" ] -# +# # # Produce result. # email = message.result # puts email @@ -110,19 +110,19 @@ # From: James Edward Gray II # To: Community Spokesman # 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 @@ -132,7 +132,7 @@ # variables in the Product object can be resolved. # # require "erb" -# +# # # Build template data class. # class Product # def initialize( code, name, desc, cost ) @@ -140,37 +140,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 = %{ # # Ruby Toys -- <%= @name %> # -# +# #

<%= @name %> (<%= @code %>)

#

<%= @desc %>

-# +# #
    # <% @features.each do |f| %> #
  • <%= f %>
  • # <% end %> #
-# +# #

# <% if @cost < 10 %> # Only <%= @cost %>!!! @@ -178,13 +178,13 @@ # Call for a price, today! # <% end %> #

-# +# # # # }.gsub(/^ /, '') -# +# # rhtml = ERB.new(template) -# +# # # Set up template data. # toy = Product.new( "TZ-1002", # "Rubysapien", @@ -195,7 +195,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) # @@ -204,10 +204,10 @@ # # Ruby Toys -- Rubysapien # -# +# #

Rubysapien (TZ-1002)

#

Geek's Best Friend! Responds to Ruby commands...

-# +# #
    #
  • Listens for verbal commands in the Ruby language!
  • #
  • Ignores Perl, Java, and all C variants.
  • @@ -215,15 +215,15 @@ #
  • Matz signature on left leg.
  • #
  • Gem studded eyes... Rubies, of course!
  • #
-# +# #

# Call for a price, today! #

-# +# # # # -# +# # == Notes # # There are a variety of templating solutions available in various Ruby projects: @@ -300,7 +300,7 @@ class ERB end end attr_accessor :stag - + def scan(&block) @stag = nil if @percent @@ -407,7 +407,7 @@ class ERB end end end - + Scanner.regist_scanner(SimpleScanner, nil, false) begin @@ -466,13 +466,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| @@ -498,7 +498,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 @@ -598,19 +598,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 $SAFE set to the # provided level. - # + # # If _trim_mode_ is passed a String containing one or more of the following # modifiers, ERB will adjust its code generation as listed: - # + # # % enables Ruby code processing for lines beginning with % # <> omit newline for lines starting with <% and ending in %> # > omit newline for lines ending in %> - # + # # _eoutvar_ can be used to set the name of the variable ERB will build up # its output in. This is useful when you need to run multiple ERB # templates through the same binding and/or when you want to control where @@ -619,20 +619,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 @@ -646,21 +646,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) @@ -687,7 +687,7 @@ class ERB cmd = [] cmd.push "#{eoutvar} = ''" - + compiler.pre_cmd = cmd cmd = [] @@ -705,13 +705,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)'), 1) }.call @@ -775,14 +775,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) @@ -791,17 +791,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 5e5066ee3a..064baa6e25 100644 --- a/lib/fileutils.rb +++ b/lib/fileutils.rb @@ -1,17 +1,17 @@ -# +# # = fileutils.rb -# +# # Copyright (c) 2000-2006 Minero Aoki -# +# # This program is free software. # You can distribute/modify this program under the same terms of ruby. -# +# # == module FileUtils -# +# # Namespace for several file utility methods for copying, moving, removing, etc. -# +# # === Module Functions -# +# # cd(dir, options) # cd(dir, options) {|dir| .... } # pwd() @@ -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 :verbose flag to methods # in FileUtils. -# +# # == module FileUtils::NoWrite -# +# # This module has all methods of FileUtils module, but never changes # files/directories. This equates to passing the :noop flag to methods # in FileUtils. -# +# # == module FileUtils::DryRun -# +# # This module has all methods of FileUtils module, but never changes # files/directories. This equates to passing the :noop and # :verbose flags to methods in FileUtils. -# +# 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) @@ -277,19 +277,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' - # + # # ln(list, destdir, options = {}) - # + # # Creates several hard links in a directory, with each one pointing to the # item in +list+. If +destdir+ is not a directory, raises Errno::ENOTDIR. - # + # # include FileUtils # cd '/sbin' # FileUtils.ln %w(cp mv mkdir), '/bin' # Now /sbin/cp and /bin/cp are linked. - # + # 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] @@ -311,24 +311,24 @@ module FileUtils # Options: force noop verbose # # ln_s(old, new, options = {}) - # + # # Creates a symbolic link +new+ which points to +old+. If +new+ already # exists and it is a directory, creates a symbolic link +new/old+. If +new+ # already exists and it is not a directory, raises Errno::EEXIST. But if # :force option is set, overwrite +new+. - # + # # FileUtils.ln_s '/usr/bin/ruby', '/usr/local/bin/ruby' # FileUtils.ln_s 'verylongsourcefilename.c', 'c', :force => true - # + # # ln_s(list, destdir, options = {}) - # + # # Creates several symbolic links in a directory, with each one pointing to the # item in +list+. If +destdir+ is not a directory, raises Errno::ENOTDIR. # # If +destdir+ is not a directory, raises Errno::ENOTDIR. - # + # # FileUtils.ln_s Dir.glob('bin/*.rb'), '/home/aamine/bin' - # + # 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] @@ -348,10 +348,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 @@ -374,7 +374,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] @@ -393,17 +393,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 @@ -413,7 +413,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] @@ -477,17 +477,17 @@ module FileUtils # # Options: force noop verbose - # + # # Moves file(s) +src+ to +dest+. If +file+ and +dest+ exist on the different # disk partition, the copied file is created on the +dest+ and the original # file removed from +src+. - # + # # 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] @@ -532,14 +532,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) @@ -560,7 +560,7 @@ module FileUtils # # Options: noop verbose - # + # # Equivalent to # # #rm(list, :force => true) @@ -581,11 +581,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 # :-) # @@ -599,7 +599,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) @@ -620,14 +620,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 @@ -786,7 +786,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 # @@ -826,14 +826,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] @@ -854,14 +854,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) @@ -877,12 +877,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) @@ -906,16 +906,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) @@ -935,16 +935,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) @@ -1015,13 +1015,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) @@ -1520,11 +1520,11 @@ module FileUtils METHODS = singleton_methods() - %w( 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 :verbose flag to # methods in FileUtils. - # + # module Verbose include FileUtils @fileutils_output = $stderr @@ -1545,11 +1545,11 @@ module FileUtils end end - # + # # This module has all methods of FileUtils module, but never changes # files/directories. This equates to passing the :noop flag # to methods in FileUtils. - # + # module NoWrite include FileUtils @fileutils_output = $stderr @@ -1570,12 +1570,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 :noop and :verbose flag # to methods in FileUtils. - # + # module DryRun include FileUtils @fileutils_output = $stderr diff --git a/lib/finalize.rb b/lib/finalize.rb index 9b6b302cac..0451d2c9f0 100644 --- a/lib/finalize.rb +++ b/lib/finalize.rb @@ -1,5 +1,5 @@ #-- -# finalizer.rb - +# finalizer.rb - # $Release Version: 0.3$ # $Revision: 1.4 $ # $Date: 1998/02/27 05:34:33 $ diff --git a/lib/forwardable.rb b/lib/forwardable.rb index cc6e4ee418..b9a135bf4b 100644 --- a/lib/forwardable.rb +++ b/lib/forwardable.rb @@ -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 diff --git a/lib/ftools.rb b/lib/ftools.rb index 5f082331fb..09cd17c332 100644 --- a/lib/ftools.rb +++ b/lib/ftools.rb @@ -1,4 +1,4 @@ -# +# # = ftools.rb: Extra tools for the File class # # Author:: WATANABE, Hirofumi @@ -16,7 +16,7 @@ # creating a directory path. See the File class for details. # # FileUtils contains all or nearly all the same functionality and more, and -# is a recommended option over ftools +# is a recommended option over ftools # # When you # @@ -39,7 +39,7 @@ class << File # If +to+ is a valid directory, +from+ will be appended to +to+, adding # and escaping backslashes as necessary. Otherwise, +to+ will be returned. # Useful for appending +from+ to +to+ only if the filename was not specified - # in +to+. + # in +to+. # def catname(from, to) if directory? to diff --git a/lib/generator.rb b/lib/generator.rb index 8285c0c33e..0d682b5bf3 100644 --- a/lib/generator.rb +++ b/lib/generator.rb @@ -55,7 +55,7 @@ # while g.next? # puts g.next # end -# +# class Generator include Enumerable @@ -189,7 +189,7 @@ class Enumerator return g.next unless g.end? g.rewind - raise StopIteration, 'iteration reached at end' + raise StopIteration, 'iteration reached at end' end # :nodoc: diff --git a/lib/getoptlong.rb b/lib/getoptlong.rb index 4d004419b1..639e3ed106 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 --file as well +# GetoptLong allows for POSIX-style options like --file as well # as single letter options like -f # # The empty option -- (two minus symbols) is used to end option @@ -42,16 +42,16 @@ # # greet user by name, if name not supplied default is John # # # # DIR: The directory in which to issue the greeting. -# +# # require 'getoptlong' # require 'rdoc/usage' -# +# # opts = GetoptLong.new( # [ '--help', '-h', GetoptLong::NO_ARGUMENT ], # [ '--repeat', '-n', GetoptLong::REQUIRED_ARGUMENT ], # [ '--name', GetoptLong::OPTIONAL_ARGUMENT ] # ) -# +# # dir = nil # name = nil # repetitions = 1 @@ -69,14 +69,14 @@ # end # end # end -# +# # if ARGV.length != 1 # puts "Missing dir argument (try --help)" # exit 0 # end -# +# # dir = ARGV.shift -# +# # Dir.chdir(dir) # for i in (1..repetitions) # print "Hello" @@ -120,7 +120,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. @@ -200,23 +200,23 @@ class GetoptLong # the processing of options as follows: # # REQUIRE_ORDER : - # + # # Options are required to occur before non-options. # # Processing of options ends as soon as a word is encountered that has not # been preceded by an appropriate option flag. # # For example, if -a and -b are options which do not take arguments, - # parsing command line arguments of '-a one -b two' would result in - # 'one', '-b', 'two' being left in ARGV, and only ('-a', '') being + # parsing command line arguments of '-a one -b two' would result in + # 'one', '-b', 'two' being left in ARGV, and only ('-a', '') being # processed as an option/arg pair. # # This is the default ordering, if the environment variable # POSIXLY_CORRECT is set. (This is for compatibility with GNU getopt_long.) # # PERMUTE : - # - # Options can occur anywhere in the command line parsed. This is the + # + # 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 @@ -233,7 +233,7 @@ class GetoptLong # # RETURN_IN_ORDER : # - # 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). # @@ -279,7 +279,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 @@ -331,7 +331,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 @@ -463,7 +463,7 @@ class GetoptLong return nil end argument = ARGV.shift - elsif @ordering == REQUIRE_ORDER + elsif @ordering == REQUIRE_ORDER if (ARGV[0] !~ /^-./) terminate return nil @@ -600,7 +600,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/getopts.rb b/lib/getopts.rb index 7ff97c6ecd..593deb7535 100644 --- a/lib/getopts.rb +++ b/lib/getopts.rb @@ -1,5 +1,5 @@ # -# getopts.rb - +# getopts.rb - # $Release Version: $ # $Revision$ # $Date$ 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 # xmlrpc/httpserver.rb 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 0f5fc0654b..4398b5adc0 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 #=> # -# +# # p ipaddr1.to_s #=> "3ffe:505:2::1" -# +# # ipaddr2 = ipaddr1.mask(48) #=> # -# +# # p ipaddr2.to_s #=> "3ffe:505:2::" -# +# # ipaddr3 = IPAddr.new "192.168.2.0/24" -# +# # p ipaddr3 #=> # 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 address is generated from a packed in_addr value # and an address family. # diff --git a/lib/irb.rb b/lib/irb.rb index 71171a578e..ae3e2aab7a 100644 --- a/lib/irb.rb +++ b/lib/irb.rb @@ -93,7 +93,7 @@ module IRB end # - # irb interpriter main routine + # irb interpriter main routine # class Irb def initialize(workspace = nil, input_method = nil, output_method = nil) @@ -134,7 +134,7 @@ module IRB end end end - + @scanner.set_input(@context.io) do signal_status(:IN_INPUT) do if l = @context.io.gets @@ -166,11 +166,11 @@ module IRB if exc print exc.class, ": ", exc, "\n" if exc.backtrace[0] =~ /irb(2)?(\/.*|-.*|\.rb)?:/ && exc.class.to_s !~ /^IRB/ - irb_bug = true + irb_bug = true else irb_bug = false end - + messages = [] lasts = [] levels = 0 @@ -182,7 +182,7 @@ module IRB else lasts.push "\tfrom "+m if lasts.size > @context.back_trace_limit - lasts.shift + lasts.shift levels += 1 end end @@ -287,13 +287,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 88585b778b..7e83d0d1ed 100644 --- a/lib/irb/cmd/chws.rb +++ b/lib/irb/cmd/chws.rb @@ -1,5 +1,5 @@ # -# change-ws.rb - +# change-ws.rb - # $Release Version: 0.9.5$ # $Revision$ # $Date$ @@ -7,7 +7,7 @@ # # -- # -# +# # require "irb/cmd/nop.rb" diff --git a/lib/irb/cmd/fork.rb b/lib/irb/cmd/fork.rb index 2866b1373b..e3a7219715 100644 --- a/lib/irb/cmd/fork.rb +++ b/lib/irb/cmd/fork.rb @@ -1,5 +1,5 @@ # -# fork.rb - +# fork.rb - # $Release Version: 0.9.5 $ # $Revision$ # $Date$ @@ -7,7 +7,7 @@ # # -- # -# +# # @RCS_ID='-$Id$-' @@ -18,7 +18,7 @@ module IRB class Fork @size end - + alias real_inspect inspect def inspect diff --git a/lib/irb/ext/loader.rb b/lib/irb/ext/loader.rb index 837e2553ac..64b784e651 100644 --- a/lib/irb/ext/loader.rb +++ b/lib/irb/ext/loader.rb @@ -1,5 +1,5 @@ # -# loader.rb - +# loader.rb - # $Release Version: 0.9.5$ # $Revision$ # $Date$ @@ -7,7 +7,7 @@ # # -- # -# +# # @@ -45,7 +45,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 @@ -62,7 +62,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 @@ -71,7 +71,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 bd443b96ed..0c1ab0123f 100644 --- a/lib/irb/ext/math-mode.rb +++ b/lib/irb/ext/math-mode.rb @@ -1,5 +1,5 @@ # -# math-mode.rb - +# math-mode.rb - # $Release Version: 0.9.5$ # $Revision$ # $Date$ @@ -7,7 +7,7 @@ # # -- # -# +# # require "mathn" diff --git a/lib/irb/ext/multi-irb.rb b/lib/irb/ext/multi-irb.rb index 634abbabf9..a36227c3de 100644 --- a/lib/irb/ext/multi-irb.rb +++ b/lib/irb/ext/multi-irb.rb @@ -7,7 +7,7 @@ # # -- # -# +# # IRB.fail CantShiftToMultiIrbMode unless defined?(Thread) require "thread" @@ -67,7 +67,7 @@ module IRB IRB.fail IrbAlreadyDead unless th.alive? th.exit end - end + end def search(key) job = case key @@ -124,8 +124,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) @@ -144,14 +144,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 5ecc5f5027..e04466348e 100644 --- a/lib/irb/ext/save-history.rb +++ b/lib/irb/ext/save-history.rb @@ -1,6 +1,6 @@ #!/usr/local/bin/ruby # -# save-history.rb - +# save-history.rb - # $Release Version: 0.9.5$ # $Revision$ # $Date$ @@ -8,7 +8,7 @@ # # -- # -# +# # require "readline" diff --git a/lib/irb/ext/tracer.rb b/lib/irb/ext/tracer.rb index 805f630a4d..1a0edd511e 100644 --- a/lib/irb/ext/tracer.rb +++ b/lib/irb/ext/tracer.rb @@ -1,5 +1,5 @@ # -# irb/lib/tracer.rb - +# irb/lib/tracer.rb - # $Release Version: 0.9.5$ # $Revision$ # $Date$ @@ -7,7 +7,7 @@ # # -- # -# +# # require "tracer" @@ -44,7 +44,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 @@ -58,4 +58,4 @@ module IRB IRB.initialize_tracer end - + diff --git a/lib/irb/ext/use-loader.rb b/lib/irb/ext/use-loader.rb index 1b4d480fcd..1285846aeb 100644 --- a/lib/irb/ext/use-loader.rb +++ b/lib/irb/ext/use-loader.rb @@ -1,5 +1,5 @@ # -# use-loader.rb - +# use-loader.rb - # $Release Version: 0.9.5$ # $Revision$ # $Date$ @@ -7,7 +7,7 @@ # # -- # -# +# # require "irb/cmd/load" @@ -31,7 +31,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 79098570dc..09a7d4cade 100644 --- a/lib/irb/ext/workspaces.rb +++ b/lib/irb/ext/workspaces.rb @@ -1,5 +1,5 @@ # -# push-ws.rb - +# push-ws.rb - # $Release Version: 0.9.5$ # $Revision$ # $Date$ @@ -7,7 +7,7 @@ # # -- # -# +# # module IRB diff --git a/lib/irb/extend-command.rb b/lib/irb/extend-command.rb index de797ab78b..36214b3cd6 100644 --- a/lib/irb/extend-command.rb +++ b/lib/irb/extend-command.rb @@ -1,5 +1,5 @@ # -# irb/extend-command.rb - irb extend command +# irb/extend-command.rb - irb extend command # $Release Version: 0.9.5$ # $Revision$ # $Date$ @@ -7,7 +7,7 @@ # # -- # -# +# # module IRB # @@ -90,15 +90,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", @@ -162,9 +162,9 @@ module IRB (override == NO_OVERRIDE) && !respond_to?(to, true) target = self (class<(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 ae712697cb..d4dcd87529 100644 --- a/lib/irb/output-method.rb +++ b/lib/irb/output-method.rb @@ -1,5 +1,5 @@ # -# output-method.rb - output methods used by irb +# output-method.rb - output methods used by irb # $Release Version: 0.9.5$ # $Revision$ # $Date$ @@ -7,7 +7,7 @@ # # -- # -# +# # require "e2mmap" @@ -40,7 +40,7 @@ module IRB # <ºÇ¾®¥Õ¥£¡¼¥ë¥ÉÉý> (\*|\*[1-9][0-9]*\$|[1-9][0-9]*) # <ÀºÅÙ>.(\*|\*[1-9][0-9]*\$|[1-9][0-9]*|)? # #<Ťµ½¤ÀµÊ¸»ú>(hh|h|l|ll|L|q|j|z|t) - # <ÊÑ´¹½¤ÀµÊ¸»ú>[diouxXeEfgGcsb%] + # <ÊÑ´¹½¤ÀµÊ¸»ú>[diouxXeEfgGcsb%] def parse_printf_format(format, opts) return format, opts if $1.size % 2 == 1 end @@ -52,7 +52,7 @@ module IRB puts [f, p, pp, pos, new_pos, c].join("!") pos = new_pos if new_pos if c == "I" - inspects.push pos.to_i + inspects.push pos.to_i (f||"")+(p||"")+(pp||"")+(pos||"")+"s" else $& diff --git a/lib/irb/ruby-lex.rb b/lib/irb/ruby-lex.rb index 4849b9378e..795569aa04 100644 --- a/lib/irb/ruby-lex.rb +++ b/lib/irb/ruby-lex.rb @@ -7,7 +7,7 @@ # # -- # -# +# # require "e2mmap" @@ -21,12 +21,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 @@ -54,7 +54,7 @@ class RubyLex @lex_state = EXPR_BEG @space_seen = false @here_header = false - + @continue = false @line = "" @@ -92,7 +92,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, "Illegal 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 525d4df14c..1415c8d90a 100644 --- a/lib/irb/ruby-token.rb +++ b/lib/irb/ruby-token.rb @@ -1,5 +1,5 @@ # -# irb/ruby-token.rb - ruby tokens +# irb/ruby-token.rb - ruby tokens # $Release Version: 0.9.5$ # $Revision$ # $Date$ @@ -7,7 +7,7 @@ # # -- # -# +# # module RubyToken EXPR_BEG = :EXPR_BEG @@ -22,7 +22,7 @@ module RubyToken if !defined?(Symbol) Symbol = Integer end - + class Token def initialize(seek, line_no, char_no) @seek = seek @@ -87,7 +87,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 @@ -96,8 +96,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 @@ -197,7 +197,7 @@ module RubyToken [:TkASSOC, TkOp, "=>"], [:TkQUESTION, TkOp, "?"], #? [:TkCOLON, TkOp, ":"], #: - + [:TkfLPAREN], # func( # [:TkfLBRACK], # func[ # [:TkfLBRACE], # func{ # @@ -253,7 +253,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 f7e3a3b2b2..3cc5c49560 100644 --- a/lib/irb/slex.rb +++ b/lib/irb/slex.rb @@ -7,7 +7,7 @@ # # -- # -# +# # require "e2mmap" @@ -25,20 +25,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 @@ -47,18 +47,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 @@ -66,7 +66,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 @@ -79,14 +79,14 @@ module IRB D_DETAIL.exec_if{D_DEATIL.printf "match end: %s:%s\n", ret, token.inspect} ret end - + def inspect format("", @head.inspect) end #---------------------------------------------------------------------- # - # class Node - + # class Node - # #---------------------------------------------------------------------- class Node @@ -100,7 +100,7 @@ module IRB attr_accessor :preproc attr_accessor :postproc - + def search(chrs, opt = nil) return self if chrs.empty? ch = chrs.shift @@ -115,7 +115,7 @@ module IRB end end end - + def create_subnode(chrs, preproc = nil, postproc = nil) if chrs.empty? if @postproc @@ -128,7 +128,7 @@ module IRB end return self end - + ch = chrs.shift if node = @Tree[ch] if chrs.empty? @@ -162,7 +162,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" @@ -257,14 +257,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" @@ -272,7 +272,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 28b079740a..721a6e1af0 100644 --- a/lib/irb/version.rb +++ b/lib/irb/version.rb @@ -7,7 +7,7 @@ # # -- # -# +# # module IRB diff --git a/lib/irb/workspace.rb b/lib/irb/workspace.rb index 7d1794cd7b..924ed46ca3 100644 --- a/lib/irb/workspace.rb +++ b/lib/irb/workspace.rb @@ -1,5 +1,5 @@ # -# irb/workspace-binding.rb - +# irb/workspace-binding.rb - # $Release Version: 0.9.5$ # $Revision$ # $Date$ @@ -7,7 +7,7 @@ # # -- # -# +# # module IRB class WorkSpace @@ -22,7 +22,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 @@ -38,7 +38,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 @@ -50,7 +50,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 @@ -64,7 +64,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 @@ -80,7 +80,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] @@ -96,7 +96,7 @@ EOF return nil if bt =~ /irb\/.*\.rb/ when 3 return nil if bt =~ /irb\/.*\.rb/ - bt.sub!(/:\s*in `irb_binding'/){""} + bt.sub!(/:\s*in `irb_binding'/){""} end bt end diff --git a/lib/irb/ws-for-case-2.rb b/lib/irb/ws-for-case-2.rb index afd49d23e1..4603861f73 100644 --- a/lib/irb/ws-for-case-2.rb +++ b/lib/irb/ws-for-case-2.rb @@ -1,5 +1,5 @@ # -# irb/ws-for-case-2.rb - +# irb/ws-for-case-2.rb - # $Release Version: 0.9.5$ # $Revision$ # $Date$ @@ -7,7 +7,7 @@ # # -- # -# +# # while true diff --git a/lib/irb/xmp.rb b/lib/irb/xmp.rb index 4bcc2ca22f..4ab0b0e98e 100644 --- a/lib/irb/xmp.rb +++ b/lib/irb/xmp.rb @@ -7,7 +7,7 @@ # # -- # -# +# # require "irb" diff --git a/lib/mailread.rb b/lib/mailread.rb index 08b33c92a4..7e1e5594ec 100644 --- a/lib/mailread.rb +++ b/lib/mailread.rb @@ -1,5 +1,5 @@ # The Mail class represents an internet mail message (as per RFC822, RFC2822) -# with headers and a body. +# with headers and a body. class Mail # Create a new Mail where +f+ is either a stream which responds to gets(), @@ -31,7 +31,7 @@ class Mail @header[attr] += "\n" + line end end - + return unless line while line = f.gets() @@ -53,7 +53,7 @@ class Mail return @body end - # Return the header corresponding to +field+. + # Return the header corresponding to +field+. # # Matching is case-insensitive. def [](field) diff --git a/lib/mathn.rb b/lib/mathn.rb index 7d16923670..04b7b6f3e6 100644 --- a/lib/mathn.rb +++ b/lib/mathn.rb @@ -1,5 +1,5 @@ # -# mathn.rb - +# mathn.rb - # $Release Version: 0.5 $ # $Revision: 1.1.1.1.4.1 $ # $Date: 1998/01/16 12:36:05 $ @@ -7,7 +7,7 @@ # # -- # -# +# # require "complex.rb" @@ -20,10 +20,10 @@ class Integer a = self.abs b = int.abs a, b = b, a if a < b - + pd_a = a.prime_division pd_b = b.prime_division - + gcd = 1 for pair in pd_a as = pd_b.assoc(pair[0]) @@ -33,7 +33,7 @@ class Integer end return gcd end - + def Integer.from_prime_division(pd) value = 1 for prime, index in pd @@ -41,7 +41,7 @@ class Integer end value end - + def prime_division raise ZeroDivisionError if self == 0 ps = Prime.new @@ -65,7 +65,7 @@ class Integer return pv end end - + class Prime include Enumerable @@ -74,7 +74,7 @@ class Prime @primes = [] @counts = [] end - + def succ i = -1 size = @primes.size @@ -155,14 +155,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 @@ -170,7 +170,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 @@ -178,12 +178,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 @@ -215,7 +215,7 @@ class Rational elsif self == 1 return Rational(1,1) end - + dem = nil x = self.denominator.to_f.to_i neard = self.denominator.to_f ** (1.0/other.denominator.to_f) @@ -227,7 +227,7 @@ class Rational end nearn = self.numerator.to_f ** (1.0/other.denominator.to_f) Rational(num,den) - + elsif other.kind_of?(Integer) if other > 0 num = numerator ** other @@ -261,7 +261,7 @@ module Math # if !(x.kind_of?(Rational) and y.kind_of?(Rational)) # return a**Rational(1,2) # end - if a.image >= 0 + if a.image >= 0 Complex(x, y) else Complex(x, -y) @@ -272,7 +272,7 @@ module Math Complex(0,rsqrt(-a)) end end - + def rsqrt(a) if a.kind_of?(Float) sqrt!(a) @@ -286,7 +286,7 @@ module Math while (src >= max) and (src >>= 32) byte_a.unshift src & 0xffffffff end - + answer = 0 main = 0 side = 0 @@ -296,13 +296,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 93ae3a9909..2f0f1b9d68 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.11 $ # $Date: 1999/10/06 11:01:53 $ @@ -14,9 +14,9 @@ # An implementation of Matrix and Vector classes. # # Author:: Keiju ISHITSUKA -# Documentation:: Gavin Sinclair (sourced from Ruby in a Nutshell (Matsumoto, O'Reilly)) +# Documentation:: Gavin Sinclair (sourced from Ruby in a Nutshell (Matsumoto, O'Reilly)) # -# See classes Matrix and Vector for documentation. +# See classes Matrix and Vector for documentation. # @@ -26,7 +26,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") @@ -60,7 +60,7 @@ end # * Matrix.row_vector(row) # * Matrix.column_vector(column) # -# To access Matrix elements/columns/rows/submatrices/properties: +# To access Matrix elements/columns/rows/submatrices/properties: # * [](i, j) # * #row_size # * #column_size @@ -105,13 +105,13 @@ end # class Matrix @RCS_ID='-$Id: matrix.rb,v 1.11 1999/10/06 11:01:53 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] ] @@ -121,7 +121,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 # of the matrix. If the optional argument +copy+ is false, use the given @@ -133,7 +133,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]]) @@ -148,7 +148,7 @@ class Matrix } Matrix.rows(rows, false) end - + # # Creates a matrix where the diagonal elements are composed of +values+. # Matrix.diagonal(9, 5, -3) @@ -165,7 +165,7 @@ class Matrix } rows(rows, false) end - + # # Creates an +n+ by +n+ diagonal matrix where each diagonal element is # +value+. @@ -186,11 +186,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) @@ -200,7 +200,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+. @@ -217,7 +217,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+. @@ -244,7 +244,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} @@ -254,7 +254,7 @@ class Matrix self end private :init_rows - + # # Returns element (+i+,+j+) of the matrix. That is: row +i+, column +j+. # @@ -268,7 +268,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 @@ -308,7 +308,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. @@ -321,7 +321,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 @@ -345,14 +345,14 @@ 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 -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #++ @@ -363,7 +363,7 @@ class Matrix def regular? square? and rank == column_size end - + # # Returns +true+ is this is a singular (i.e. non-regular) matrix. # @@ -378,7 +378,7 @@ class Matrix def square? column_size == row_size end - + #-- # OBJECT METHODS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #++ @@ -388,15 +388,15 @@ 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. # @@ -408,7 +408,7 @@ class Matrix end true end - + # # Returns a clone of the matrix, so that the contents of each do not reference # identical objects. @@ -416,18 +416,18 @@ class Matrix def clone Matrix.rows(@rows) end - + # # Returns a hash-code for the matrix. # def hash @rows.hash end - + #-- # ARITHMETIC -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #++ - + # # Matrix multiplication. # Matrix[[2,4], [6,8]] * Matrix.identity(2) @@ -465,7 +465,7 @@ class Matrix return x * y end end - + # # Matrix addition. # Matrix.scalar(2,5) + Matrix[[1,0], [-4,7]] @@ -483,7 +483,7 @@ 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).collect {|i| @@ -511,7 +511,7 @@ 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).collect {|i| @@ -521,7 +521,7 @@ class Matrix } Matrix.rows(rows, false) end - + # # Matrix division (multiplication by the inverse). # Matrix[[7,6], [3,9]] / Matrix[[2,9], [3,1]] @@ -606,7 +606,7 @@ class Matrix self end #alias reciprocal inverse - + # # Matrix exponentiation. Defined for integer powers only. Equivalent to # multiplying the matrix by itself N times. @@ -640,11 +640,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. @@ -656,7 +656,7 @@ class Matrix size = row_size a = to_a - + det = 1 size.times do |k| if (akk = a[k][k]) == 0 @@ -741,7 +741,7 @@ class Matrix end end alias tr trace - + # # Returns the transpose of the matrix. # Matrix[[1,2], [3,4], [5,6]] @@ -756,11 +756,11 @@ class Matrix Matrix.columns(@rows) end alias t transpose - + #-- # CONVERTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #++ - + # # FIXME: describe #coerce. # @@ -781,7 +781,7 @@ class Matrix row(i) } end - + # # Returns an array of the column vectors of the matrix. See Vector. # @@ -790,18 +790,18 @@ class Matrix column(i) } end - + # # Returns an array of arrays that describe the rows of the matrix. # def to_a @rows.collect{|row| row.dup} end - + #-- # PRINTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #++ - + # # Overrides Object#to_s # @@ -811,23 +811,23 @@ class Matrix "[" + row.collect{|e| e.to_s}.join(", ") + "]" }.join(", ")+"]" end - + # # Overrides Object#inspect # def inspect "Matrix"+@rows.inspect end - + # Private CLASS - + class Scalar < Numeric # :nodoc: include ExceptionForMatrix - + def initialize(value) @value = value end - + # ARITHMETIC def +(other) case other @@ -842,7 +842,7 @@ class Matrix x + y end end - + def -(other) case other when Numeric @@ -856,7 +856,7 @@ class Matrix x - y end end - + def *(other) case other when Numeric @@ -868,7 +868,7 @@ class Matrix x * y end end - + def / (other) case other when Numeric @@ -882,7 +882,7 @@ class Matrix x / y end end - + def ** (other) case other when Numeric @@ -941,9 +941,9 @@ end # class Vector include ExceptionForMatrix - + #INSTANCE CREATION - + private_class_method :new # @@ -953,7 +953,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. @@ -961,14 +961,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. # @@ -979,23 +979,23 @@ class Vector @elements = array end end - + # ACCESSING - + # # Returns element number +i+ (starting at zero) of the vector. # def [](i) @elements[i] end - + # # Returns the number of elements in the vector. # def size @elements.size end - + #-- # ENUMERATIONS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #++ @@ -1009,7 +1009,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. @@ -1030,40 +1030,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. # @@ -1119,18 +1119,18 @@ 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| @@ -1138,7 +1138,7 @@ class Vector } p end - + # # Like Array#collect. # @@ -1147,7 +1147,7 @@ class Vector Vector.elements(els, false) end alias map collect - + # # Like Vector#collect2, but returns a Vector instead of an Array. # @@ -1155,7 +1155,7 @@ class Vector els = collect2(v, &block) Vector.elements(els, false) end - + # # Returns the modulus (Pythagorean distance) of the vector. # Vector[5,8,2].r => 9.643650761 @@ -1163,7 +1163,7 @@ class Vector def r Math.sqrt(@elements.inject(0) {|v, e| v + e*e}) end - + #-- # CONVERTING #++ @@ -1174,14 +1174,14 @@ class Vector def covector Matrix.row_vector(self) end - + # # Returns the elements of the vector in an array. # def to_a @elements.dup end - + # # FIXME: describe Vector#coerce. # @@ -1193,18 +1193,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/monitor.rb b/lib/monitor.rb index 9158f9fb32..004e0557cb 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 @@ -41,18 +41,18 @@ reads a line from ARGF and push it to buf, then call empty_cond.signal. =end - + # # Adds monitor functionality to an arbitrary object by mixing the module with # +include+. For example: # # require 'monitor.rb' -# +# # buf = [] # buf.extend(MonitorMixin) # empty_cond = buf.new_cond -# +# # # consumer # Thread.start do # loop do @@ -62,7 +62,7 @@ empty_cond.signal. # end # end # end -# +# # # producer # while line = ARGF.gets # buf.synchronize do @@ -70,7 +70,7 @@ empty_cond.signal. # 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 @@ -85,15 +85,15 @@ module MonitorMixin # class ConditionVariable class Timeout < Exception; end - + # Create a new timer with the argument timeout, and add the # current thread to the list of waiters. Then the thread is - # stopped. It will be resumed when a corresponding #signal + # stopped. It will be resumed when a corresponding #signal # occurs. def wait(timeout = nil) @monitor.instance_eval {mon_check_owner()} timer = create_timer(timeout) - + Thread.critical = true count = @monitor.instance_eval {mon_exit_for_cond()} @waiters.push(Thread.current) @@ -118,7 +118,7 @@ module MonitorMixin end end end - + # call #wait while the supplied block returns +true+. def wait_while @@ -126,14 +126,14 @@ module MonitorMixin wait end end - + # call #wait until the supplied block returns +true+. def wait_until until yield wait end end - + # Wake up and run the next waiter def signal @monitor.instance_eval {mon_check_owner()} @@ -143,7 +143,7 @@ module MonitorMixin Thread.critical = false Thread.pass end - + # Wake up all the waiters. def broadcast @monitor.instance_eval {mon_check_owner()} @@ -155,11 +155,11 @@ module MonitorMixin Thread.critical = false Thread.pass end - + def count_waiters return @waiters.length end - + private def initialize(monitor) @@ -181,12 +181,12 @@ module MonitorMixin end end end - + def self.extend_object(obj) super(obj) obj.instance_eval {mon_initialize()} end - + # # Attempts to enter exclusive section. Returns +false+ if lock fails. # @@ -216,7 +216,7 @@ module MonitorMixin ensure Thread.critical = false end - + # # Leaves exclusive section. # @@ -245,10 +245,10 @@ module MonitorMixin end end alias synchronize mon_synchronize - + # # FIXME: This isn't documented in Nutshell. - # + # # Create a new condition variable for this monitor. # This facilitates control of the monitor with #signal and #wait. # @@ -316,7 +316,7 @@ end # Monitors provide means of mutual exclusion for Thread programming. # A critical region is created by means of the synchronize method, # which takes a block. -# The condition variables (created with #new_cond) may be used +# The condition variables (created with #new_cond) may be used # to control the execution of a monitor with #signal and #wait. # # the Monitor class wraps MonitorMixin, and provides aliases diff --git a/lib/mutex_m.rb b/lib/mutex_m.rb index 8e0d42bc8d..b00756cb21 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 $ # $Date: 1998/02/27 04:28:57 $ @@ -25,7 +25,7 @@ # include Mutex_m # # ... # end -# +# # obj = Foo.new module Mutex_m @@ -37,13 +37,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 @@ -59,8 +59,8 @@ module Mutex_m end mu_initialize end - - # locking + + # locking def mu_synchronize begin mu_lock @@ -69,11 +69,11 @@ module Mutex_m mu_unlock end end - + def mu_locked? @mu_locked end - + def mu_try_lock result = false Thread.critical = true @@ -84,7 +84,7 @@ module Mutex_m Thread.critical = false result end - + def mu_lock while (Thread.critical = true; @mu_locked) @mu_waiting.push Thread.current @@ -94,7 +94,7 @@ module Mutex_m Thread.critical = false self end - + def mu_unlock return unless @mu_locked Thread.critical = true @@ -107,9 +107,9 @@ module Mutex_m end self end - + private - + def mu_initialize @mu_waiting = [] @mu_locked = false; diff --git a/lib/net/ftp.rb b/lib/net/ftp.rb index c611e09ee3..1b2399dc84 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 . # # 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_accessor :binary @@ -101,7 +101,7 @@ module Net # The server's last response. attr_reader :last_response - + # # A synonym for FTP.new, 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, @@ -160,7 +160,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 @@ -197,7 +197,7 @@ module Net end end private :sanitize - + def putline(line) if @debug_mode print "put: ", sanitize(line), "\n" @@ -206,7 +206,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, "") @@ -216,7 +216,7 @@ module Net return line end private :getline - + def getmultiline line = getline buff = line @@ -230,7 +230,7 @@ module Net return buff << "\n" end private :getmultiline - + def getresp @last_response = getmultiline @last_response_code = @last_response[0, 3] @@ -246,7 +246,7 @@ module Net end end private :getresp - + def voidresp resp = getresp if resp[0] != ?2 @@ -254,7 +254,7 @@ module Net end end private :voidresp - + # # Sends a command and returns the response. # @@ -264,7 +264,7 @@ module Net return getresp end end - + # # Sends a command and expect a response beginning with '2'. # @@ -274,7 +274,7 @@ module Net voidresp end end - + def sendport(host, port) af = (@sock.peeraddr)[0] if af == "AF_INET" @@ -287,7 +287,7 @@ module Net voidcmd(cmd) end private :sendport - + def makeport sock = TCPServer.open(@sock.addr[3], 0) port = sock.addr[1] @@ -296,7 +296,7 @@ module Net return sock end private :makeport - + def makepasv if @sock.peeraddr[0] == "AF_INET" host, port = parse227(sendcmd("PASV")) @@ -307,13 +307,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 @@ -327,7 +327,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 @@ -344,7 +344,7 @@ module Net return conn end private :transfercmd - + def getaddress thishost = Socket.gethostname rescue "" if not thishost.index(".") @@ -360,7 +360,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 @@ -373,7 +373,7 @@ module Net if user == "anonymous" and passwd == nil passwd = getaddress end - + resp = "" synchronize do resp = sendcmd('USER ' + user) @@ -391,7 +391,7 @@ module Net end @welcome = resp end - + # # Puts the connection into binary (image) mode, issues the given command, # and fetches the data returned, passing it to the associated block in @@ -411,7 +411,7 @@ module Net voidresp 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 @@ -436,7 +436,7 @@ module Net voidresp 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 @@ -460,7 +460,7 @@ module Net voidresp end 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 @@ -509,7 +509,7 @@ module Net f.close end end - + # # Retrieves +remotefile+ in ASCII (text) mode, storing the result in # +localfile+. If a block is supplied, it is passed the retrieved data one @@ -539,7 +539,7 @@ module Net getbinaryfile(remotefile, localfile, blocksize, &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 @@ -568,7 +568,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, @@ -603,7 +603,7 @@ module Net cmd = "ACCT " + account voidcmd(cmd) end - + # # Returns an array of filenames in the remote directory. # @@ -618,7 +618,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. @@ -640,7 +640,7 @@ module Net end alias ls list alias dir list - + # # Renames a file on the server. # @@ -651,7 +651,7 @@ module Net end voidcmd("RNTO " + toname) end - + # # Deletes a file on the server. # @@ -665,7 +665,7 @@ module Net raise FTPReplyError, resp end end - + # # Changes the (remote) directory. # @@ -683,21 +683,21 @@ module Net cmd = "CWD " + dirname voidcmd(cmd) end - + # # Returns the size of the given (remote) filename. # def size(filename) voidcmd("TYPE I") 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 - + 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. @@ -707,7 +707,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. # @@ -715,14 +715,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. # @@ -731,7 +731,7 @@ module Net return parse257(resp) end alias getdir pwd - + # # Returns system information. # @@ -742,7 +742,7 @@ module Net end return resp[4 .. -1] end - + # # Aborts the previous command (ABOR command). # @@ -756,7 +756,7 @@ module Net end return resp end - + # # Returns the status (STAT command). # @@ -766,7 +766,7 @@ module Net @sock.send(line, Socket::MSG_OOB) return getresp end - + # # Issues the MDTM command. TODO: more info. # @@ -776,7 +776,7 @@ module Net return resp[3 .. -1].strip end end - + # # Issues the HELP command. # @@ -787,7 +787,7 @@ module Net end sendcmd(cmd) end - + # # Exits the FTP session. # @@ -809,7 +809,7 @@ module Net cmd = "SITE " + arg voidcmd(cmd) end - + # # Closes the connection. Further operations are impossible until you open # a new connection with #connect. @@ -817,14 +817,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 @@ -843,7 +843,7 @@ module Net return host, port end private :parse227 - + def parse228(resp) if resp[0, 3] != "228" raise FTPReplyError, resp @@ -871,11 +871,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 @@ -894,7 +894,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 142248d3dc..e30f9c22eb 100644 --- a/lib/net/http.rb +++ b/lib/net/http.rb @@ -4,26 +4,26 @@ # Copyright (c) 1999-2006 Yukihiro Matsumoto # Copyright (c) 1999-2006 Minero Aoki # Copyright (c) 2001 GOTOU Yuuzou -# +# # Written and maintained by Minero Aoki . # HTTPS support added by GOTOU Yuuzou . # # 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/?cmd=view;name=net%2Fhttp.rb -# +# #-- # $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' # @@ -106,15 +106,15 @@ module Net #:nodoc: # else # res.error! # end - # + # # === Accessing via Proxy - # + # # Net::HTTP.Proxy creates http proxy class. It has same # methods of Net::HTTP but its instances always connect to # proxy, instead of given host. - # + # # require 'net/http' - # + # # proxy_addr = 'your.proxy.host' # proxy_port = 8080 # : @@ -122,20 +122,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']) @@ -148,16 +148,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 @@ -166,25 +166,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. @@ -257,22 +257,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 @@ -325,7 +325,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') # @@ -345,7 +345,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: @@ -359,7 +359,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 # @@ -429,9 +429,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 @@ -527,7 +527,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. @@ -627,9 +627,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) # : @@ -637,7 +637,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 @@ -748,7 +748,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". # @@ -759,7 +759,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| @@ -783,21 +783,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 @@ -805,11 +805,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 @@ -817,18 +817,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| @@ -921,21 +921,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'] @@ -952,9 +952,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'] # @@ -964,21 +964,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 @@ -1006,7 +1006,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') @@ -1020,14 +1020,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+ @@ -1340,7 +1340,7 @@ module Net #:nodoc: raise HTTPHeaderSyntaxError, 'wrong Content-Length format' len.to_i end - + def content_length=(len) unless len @header.delete 'content-length' @@ -1350,7 +1350,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? @@ -1391,7 +1391,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"). @@ -1581,14 +1581,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. @@ -1728,17 +1728,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 @@ -1747,7 +1747,7 @@ module Net #:nodoc: # 204 HTTPNoContent # 205 HTTPResetContent # 206 HTTPPartialContent - # + # # 3xx HTTPRedirection # 300 HTTPMultipleChoice # 301 HTTPMovedPermanently @@ -1756,7 +1756,7 @@ module Net #:nodoc: # 304 HTTPNotModified # 305 HTTPUseProxy # 307 HTTPTemporaryRedirect - # + # # 4xx HTTPClientError # 400 HTTPBadRequest # 401 HTTPUnauthorized @@ -1776,7 +1776,7 @@ module Net #:nodoc: # 415 HTTPUnsupportedMediaType # 416 HTTPRequestedRangeNotSatisfiable # 417 HTTPExpectationFailed - # + # # 5xx HTTPServerError # 500 HTTPInternalServerError # 501 HTTPNotImplemented @@ -1784,7 +1784,7 @@ module Net #:nodoc: # 503 HTTPServiceUnavailable # 504 HTTPGatewayTimeOut # 505 HTTPVersionNotSupported - # + # # xxx HTTPUnknownResponse # class HTTPResponse @@ -2057,7 +2057,7 @@ module Net #:nodoc: # next is to fix bug in RDoc, where the private inside class << self # spills out. - public + public include HTTPHeader @@ -2090,7 +2090,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 df72469e2f..00fe1bbbd9 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 79ed4b4981..663be7fc84 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. # @@ -44,12 +44,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 @@ -57,7 +57,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 @@ -90,11 +90,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") @@ -102,7 +102,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 @@ -112,9 +112,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 @@ -146,8 +146,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 @@ -283,7 +283,7 @@ 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 and + # the server. See Net::IMAP::LoginAuthenticator and # Net::IMAP::CramMD5Authenticator for examples. # # If +auth_type+ refers to an existing authenticator, it will be @@ -317,7 +317,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 @@ -343,7 +343,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 @@ -391,7 +391,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], @@ -442,7 +442,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+. @@ -489,8 +489,8 @@ module Net # imap.create("foo/bar") # imap.create("foo/baz") # p imap.list("", "foo/%") - # #=> [#, \\ - # #, \\ + # #=> [#, \\ + # #, \\ # #] def list(refname, mailbox) synchronize do @@ -543,7 +543,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) @@ -562,7 +562,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) @@ -585,7 +585,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) @@ -596,9 +596,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: # @@ -606,7 +606,7 @@ module Net # Subject: hello # From: shugo@ruby-lang.org # To: shugo@ruby-lang.org - # + # # hello world # EOF # @@ -625,7 +625,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") @@ -649,8 +649,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. # @@ -674,7 +674,7 @@ module Net # # OR :: "or" two search keys together. # - # ON :: messages with an internal date exactly equal to , + # ON :: messages with an internal date exactly equal to , # which has a format similar to 8-Aug-2002. # # SINCE :: messages with an internal date on or after . @@ -682,7 +682,7 @@ module Net # SUBJECT :: messages with in their subject. # # TO :: messages with in their TO field. - # + # # For example: # # p imap.search(["SUBJECT", "hello", "NOT", "NEW"]) @@ -705,8 +705,8 @@ module Net # The return value is an array of Net::IMAP::FetchData. For example: # # p imap.fetch(6..8, "UID") - # #=> [#98}>, \\ - # #99}>, \\ + # #=> [#98}>, \\ + # #99}>, \\ # #100}>] # p imap.fetch(6, "BODY[HEADER.FIELDS (SUBJECT)]") # #=> [#"Subject: test\r\n\r\n"}>] @@ -729,9 +729,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. @@ -739,8 +739,8 @@ module Net # The return value is an array of Net::IMAP::FetchData. For example: # # p imap.store(6..8, "+FLAGS", [:Deleted]) - # #=> [#[:Seen, :Deleted]}>, \\ - # #[:Seen, :Deleted]}>, \\ + # #=> [#[:Seen, :Deleted]}>, \\ + # #[:Seen, :Deleted]}>, \\ # #[:Seen, :Deleted]}>] def store(set, attr, flags) return store_internal("STORE", set, attr, flags) @@ -782,9 +782,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. # @@ -820,7 +820,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) @@ -871,7 +871,7 @@ module Net @@max_flag_count = 10000 # Creates a new Net::IMAP object and connects it to the specified - # +port+ (143 by default) on the named +host+. If +usessl+ is true, + # +port+ (143 by default) on the named +host+. If +usessl+ is true, # then an attempt will # be made to use SSL (now TLS) to connect to the server. For this # to work OpenSSL [OSSL] and the Ruby OpenSSL [RSSL] @@ -887,7 +887,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 = PORT, usessl = false, certs = nil, verify = false) super() @@ -909,7 +909,7 @@ module Net context.ca_path = certs if certs && FileTest::directory?(certs) context.verify_mode = VERIFY_PEER if verify if defined?(VerifyCallbackProc) - context.verify_callback = VerifyCallbackProc + context.verify_callback = VerifyCallbackProc end @sock = SSLSocket.new(@sock, context) @sock.connect # start ssl session. @@ -1055,7 +1055,7 @@ module Net @tagno += 1 return format("%s%04d", @tag_prefix, @tagno) end - + def put_string(str) @sock.print(str) if @@debug @@ -1104,7 +1104,7 @@ module Net put_string(str) end end - + def send_quoted_string(str) put_string('"' + str.gsub(/["\\]/n, "\\\\\\&") + '"') end @@ -1447,109 +1447,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 (()) 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* - # + # # 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 (()). - # + # # 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 (()). - # + # # 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*] - # + # # ==== 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) @@ -1558,78 +1558,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[
]<>] @@ -1656,67 +1656,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: @@ -1729,37 +1729,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, @@ -1770,7 +1770,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") @@ -1780,13 +1780,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, @@ -1798,7 +1798,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") @@ -1808,13 +1808,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, @@ -1828,7 +1828,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") @@ -1837,29 +1837,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, @@ -1869,7 +1869,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") @@ -2678,35 +2678,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 @@ -3246,7 +3246,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 @@ -3336,7 +3336,7 @@ EOF exit(1) end $port ||= $ssl ? 993 : 143 - + imap = Net::IMAP.new($host, $port, $ssl) begin password = get_password diff --git a/lib/net/pop.rb b/lib/net/pop.rb index 4374550ae9..574ed4520f 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 . # # 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. # @@ -931,7 +931,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 dc23c14dfa..e1af0b8e0b 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 @@ -232,7 +232,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 e6a4a8699d..2c0d48d982 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 . # # 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 = < # To: Destination Address # Subject: test message # Date: Sat, 23 Jun 2001 16:26:43 +0900 # Message-Id: - # + # # This is a test message. # END_OF_MESSAGE - # + # # require 'net/smtp' # Net::SMTP.start('your.smtp.server', 25) do |smtp| # smtp.send_message msgstr, # 'your@mail.address', # 'his_address@example.com' # 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, 'from@example.com', ['dest@example.com'] - # 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: john@example.com # To: betty@example.com # Subject: I found a bug - # + # # Check vm.c:58879. # EndMessage # diff --git a/lib/net/telnet.rb b/lib/net/telnet.rb index 91628a8e84..a61579c6ef 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 -# 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 + 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 + 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 + 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) @@ -491,9 +491,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. # @@ -507,7 +507,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 @@ -524,7 +524,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"] @@ -619,7 +619,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) @@ -654,7 +654,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. # @@ -701,7 +701,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 64c7d81351..3692bbca3d 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 @@ -123,7 +123,7 @@ module Observable def add_observer(observer) @observer_peers = [] unless defined? @observer_peers unless observer.respond_to? :update - raise NoMethodError, "observer needs to respond to `update'" + raise NoMethodError, "observer needs to respond to `update'" end @observer_peers.push observer end diff --git a/lib/open3.rb b/lib/open3.rb index 268f86f61c..2e032c2ca9 100644 --- a/lib/open3.rb +++ b/lib/open3.rb @@ -14,7 +14,7 @@ # # require "open3" # include Open3 -# +# # stdin, stdout, stderr = popen3('nroff -man') # # Open3.popen3 can also take a block which will receive stdin, stdout and @@ -27,10 +27,10 @@ # module Open3 - # + # # Open stdin, stdout, and stderr streams and start external executable. # Non-block form: - # + # # require 'open3' # # stdin, stdout, stderr = Open3.popen3(cmd) diff --git a/lib/optparse.rb b/lib/optparse.rb index bece659ec5..364abe2330 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 @@ -575,7 +575,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. @@ -591,7 +591,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 45ebb8083e..01057972df 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 # -> # - # 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/parsearg.rb b/lib/parsearg.rb index 8133858b93..2a713678ed 100644 --- a/lib/parsearg.rb +++ b/lib/parsearg.rb @@ -7,7 +7,7 @@ # # -- # -# +# # warn "Warning:#{caller[0].sub(/:in `.*'\z/, '')}: parsearg is deprecated after Ruby 1.8.1; use optparse instead" diff --git a/lib/ping.rb b/lib/ping.rb index c2966b619c..920f15c23e 100644 --- a/lib/ping.rb +++ b/lib/ping.rb @@ -3,7 +3,7 @@ # # Author:: Yukihiro Matsumoto # Documentation:: Konrad Meyer -# +# # Performs the function of the basic network testing tool, ping. # See: Ping. # @@ -11,7 +11,7 @@ require 'timeout' require "socket" -# +# # Ping contains routines to test for the reachability of remote hosts. # Currently the only routine implemented is pingecho(). # @@ -23,14 +23,14 @@ require "socket" # slow. Requiring 'resolv-replace' allows non-blocking name resolution. # # Usage: -# +# # require 'ping' # # puts "'jimmy' is alive and kicking" if Ping.pingecho('jimmy', 10) # module Ping - # + # # Return true if we can open a connection to the hostname or IP address # +host+ on port +service+ (which defaults to the "echo" port) waiting up # to +timeout+ seconds. diff --git a/lib/pp.rb b/lib/pp.rb index 14fe62ee95..1a4ebe16d3 100644 --- a/lib/pp.rb +++ b/lib/pp.rb @@ -1,10 +1,10 @@ # == Pretty-printer for Ruby objects. -# +# # = Which seems better? -# +# # non-pretty-printed output by #p is: # #, @group_queue=#], []]>, @buffer=[], @newline="\n", @group_stack=[#], @buffer_width=0, @indent=0, @maxwidth=79, @output_width=2, @output=#> -# +# # pretty-printed output by #pp is: # #, # @output_width=2> -# +# # I like the latter. If you do too, this library is for you. -# +# # = Usage -# +# # pp(obj) # # output +obj+ to +$>+ in pretty printed format. -# +# # It returns +nil+. -# +# # = Output Customization # To define your customized pretty printing function for your classes, # redefine a method #pretty_print(+pp+) in the class. @@ -67,10 +67,10 @@ end class PP < PrettyPrint # Outputs +obj+ to +out+ in pretty printed format of # +width+ columns in width. - # + # # If +out+ is omitted, +$>+ is assumed. # If +width+ is omitted, 79 is assumed. - # + # # PP.pp returns +out+. def PP.pp(obj, out=$>, width=79) q = PP.new(out, width) @@ -82,7 +82,7 @@ class PP < PrettyPrint # Outputs +obj+ to +out+ like PP.pp but with no indent and # newline. - # + # # PP.singleline_pp returns +out+. def PP.singleline_pp(obj, out=$>) q = SingleLine.new(out) @@ -124,7 +124,7 @@ class PP < PrettyPrint # Adds +obj+ to the pretty printing buffer # using Object#pretty_print or Object#pretty_print_cycle. - # + # # Object#pretty_print_cycle is used when +obj+ is already # printed, a.k.a the object reference chain has a cycle. def pp(obj) @@ -144,7 +144,7 @@ class PP < PrettyPrint end # A convenience method which is same as follows: - # + # # group(1, '#<' + obj.class.name, '>') { ... } def object_group(obj, &block) # :yield: group(1, '#<' + obj.class.name, '>', &block) @@ -157,7 +157,7 @@ class PP < PrettyPrint end # A convenience method which is same as follows: - # + # # text ',' # breakable def comma_breakable @@ -167,23 +167,23 @@ class PP < PrettyPrint # Adds a separated list. # The list is separated by comma with breakable space, by default. - # + # # #seplist iterates the +list+ using +iter_method+. # It yields each object to the block given for #seplist. # The procedure +separator_proc+ is called between each yields. - # + # # If the iteration is zero times, +separator_proc+ is not called at all. - # + # # If +separator_proc+ is nil or not given, # +lambda { comma_breakable }+ is used. # If +iter_method+ is not given, :each is used. - # + # # For example, following 3 code fragments has similar effect. - # + # # q.seplist([1,2,3]) {|v| xxx v } - # + # # q.seplist([1,2,3], lambda { comma_breakable }, :each) {|v| xxx v } - # + # # xxx 1 # q.comma_breakable # xxx 2 @@ -247,11 +247,11 @@ class PP < PrettyPrint # A default pretty printing method for general objects. # It calls #pretty_print_instance_variables to list instance variables. - # + # # If +self+ has a customized (redefined) #inspect method, # the result of self.inspect is used but it obviously has no # line break hints. - # + # # This module provides predefined #pretty_print methods for some of # the most commonly used built-in classes for convenience. def pretty_print(q) @@ -274,7 +274,7 @@ class PP < PrettyPrint end # Returns a sorted array of instance variable names. - # + # # This method should return an array of names of instance variables as symbols or strings as: # +[:@a, :@b]+. def pretty_print_instance_variables @@ -283,7 +283,7 @@ class PP < PrettyPrint # Is #inspect implementation using #pretty_print. # If you implement #pretty_print, it can be used as follows. - # + # # alias inspect pretty_print_inspect # # However, doing this requires that every class that #inspect is called on @@ -583,7 +583,7 @@ if __FILE__ == $0 result = PP.pp(a, '') assert_equal("#{a.inspect}\n", result) end - + def test_to_s_without_iv a = Object.new def a.to_s() "aaa" end diff --git a/lib/prettyprint.rb b/lib/prettyprint.rb index 315c422e9e..48f2ebf1e4 100644 --- a/lib/prettyprint.rb +++ b/lib/prettyprint.rb @@ -2,7 +2,7 @@ # This class implements a pretty printing algorithm. It finds line breaks and # nice indentations for grouped structure. -# +# # By default, the class assumes that primitive elements are strings and each # byte in the strings have single column in width. But it can be used for # other situations by giving suitable arguments for some methods: @@ -18,28 +18,28 @@ # == Bugs # * Box based formatting? # * Other (better) model/algorithm? -# +# # == References # Christian Lindig, Strictly Pretty, March 2000, # http://www.st.cs.uni-sb.de/~lindig/papers/#pretty -# +# # Philip Wadler, A prettier printer, March 1998, # http://homepages.inf.ed.ac.uk/wadler/topics/language-design.html#prettier -# +# # == Author # Tanaka Akira -# +# class PrettyPrint # This is a convenience method which is same as follows: - # + # # begin # q = PrettyPrint.new(output, maxwidth, newline, &genspace) # ... # q.flush # output # end - # + # def PrettyPrint.format(output='', maxwidth=79, newline="\n", genspace=lambda {|n| ' ' * n}) q = PrettyPrint.new(output, maxwidth, newline, &genspace) yield q diff --git a/lib/pstore.rb b/lib/pstore.rb index ab495d9ed7..e6e9a12485 100644 --- a/lib/pstore.rb +++ b/lib/pstore.rb @@ -13,49 +13,49 @@ require "digest/md5" # # 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 @@ -66,9 +66,9 @@ require "digest/md5" # # 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| @@ -87,10 +87,10 @@ class PStore class Error < StandardError end - # - # 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. - # + # def initialize(file) dir = File::dirname(file) unless File::directory? dir @@ -108,10 +108,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 @@ -119,9 +119,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. # @@ -130,12 +130,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. # @@ -154,11 +154,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... @@ -166,7 +166,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. # @@ -176,7 +176,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. # @@ -187,7 +187,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. # @@ -197,7 +197,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. # @@ -213,22 +213,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. # @@ -240,21 +240,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. # @@ -266,19 +266,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) # :yields: pstore diff --git a/lib/rdoc/code_objects.rb b/lib/rdoc/code_objects.rb index d6c4f1bdb9..16481b9ff9 100644 --- a/lib/rdoc/code_objects.rb +++ b/lib/rdoc/code_objects.rb @@ -107,7 +107,7 @@ module RDoc end - # A Context is something that can hold modules, classes, methods, + # A Context is something that can hold modules, classes, methods, # attributes, aliases, requires, and includes. Classes, modules, and # files are all Contexts. @@ -133,7 +133,7 @@ module RDoc # Set the comment for this section from the original comment block # If the first line contains :section:, strip it and use the rest. Otherwise - # remove lines up to the line containing :section:, and look for + # remove lines up to the line containing :section:, and look for # those lines again at the end and remove them. This lets us write # # # --------------------- @@ -349,7 +349,7 @@ module RDoc @method_list.each {|m| yield m} end - def each_attribute + def each_attribute @attributes.each {|a| yield a} end @@ -418,12 +418,12 @@ module RDoc end result end - + def find_local_symbol(symbol) res = find_method_named(symbol) || find_constant_named(symbol) || find_attribute_named(symbol) || - find_module_named(symbol) + find_module_named(symbol) end # Handle sections @@ -454,7 +454,7 @@ module RDoc def find_attribute_named(name) @attributes.find {|m| m.name == name} end - + end @@ -465,7 +465,7 @@ module RDoc attr_accessor :file_relative_name attr_accessor :file_absolute_name attr_accessor :diagram - + @@all_classes = {} @@all_modules = {} @@ -521,7 +521,7 @@ module RDoc def TopLevel.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 @@ -582,7 +582,7 @@ module RDoc # to_s is simply for debugging def to_s - res = self.class.name + ": " + @name + res = self.class.name + ": " + @name res << @comment.to_s res << super res @@ -689,7 +689,7 @@ $stderr.puts p # with a particular context class Alias < CodeObject attr_accessor :text, :old_name, :new_name, :comment - + def initialize(text, old_name, new_name, comment) super() @text = text diff --git a/lib/rdoc/diagram.rb b/lib/rdoc/diagram.rb index 9fdc49c02e..904c2decde 100644 --- a/lib/rdoc/diagram.rb +++ b/lib/rdoc/diagram.rb @@ -43,7 +43,7 @@ module RDoc # Draw the diagrams. We traverse the files, drawing a diagram for # each. We also traverse each top-level class and module in that - # file drawing a diagram for these too. + # file drawing a diagram for these too. def draw unless @options.quiet @@ -60,21 +60,21 @@ module RDoc 'fontsize' => '8', 'bgcolor' => 'lightcyan1', 'compound' => 'true') - + # it's a little hack %) i'm too lazy to create a separate class # for default node graph << DOT::DOTNode.new('name' => 'node', 'fontname' => FONT, 'color' => 'black', 'fontsize' => 8) - + i.modules.each do |mod| draw_module(mod, graph, true, i.file_relative_name) end add_classes(i, graph, i.file_relative_name) i.diagram = convert_to_png("f_#{file_count}", graph) - + # now go through and document each top level class and # module independently i.modules.each_with_index do |mod, count| @@ -93,8 +93,8 @@ module RDoc 'color' => 'black', 'fontsize' => 8) draw_module(mod, graph, true) - mod.diagram = convert_to_png("m_#{file_count}_#{count}", - graph) + mod.diagram = convert_to_png("m_#{file_count}_#{count}", + graph) end end $stderr.puts unless @options.quiet @@ -130,11 +130,11 @@ module RDoc m = DOT::DOTSubgraph.new('name' => "cluster_#{mod.full_name.gsub( /:/,'_' )}", 'label' => mod.name, 'fontname' => FONT, - 'color' => 'blue', - 'style' => 'filled', + 'color' => 'blue', + 'style' => 'filled', 'URL' => %{"#{url}"}, 'fillcolor' => toplevel ? 'palegreen1' : 'palegreen3') - + @done_modules[mod.full_name] = m add_classes(mod, m, file) graph << m @@ -175,8 +175,8 @@ module RDoc if container.full_name graph << DOT::DOTNode.new('name' => "#{container.full_name.gsub( /:/,'_' )}", 'label' => "", - 'width' => (container.classes.empty? and - container.modules.empty?) ? + 'width' => (container.classes.empty? and + container.modules.empty?) ? '0.75' : '0.01', 'height' => '0.01', 'shape' => 'plaintext') @@ -197,16 +197,16 @@ module RDoc next if cl.name == 'Object' || cl.name[0,2] == "<<" url = cl.http_url("classes") - + label = cl.name.dup if use_fileboxes && cl.in_files.length > 1 - label << '\n[' + + label << '\n[' + cl.in_files.collect {|i| - i.file_relative_name + i.file_relative_name }.sort.join( '\n' ) + ']' - end - + end + attrs = { 'name' => "#{cl.full_name.gsub( /:/, '_' )}", 'fontcolor' => 'black', @@ -218,20 +218,20 @@ module RDoc } c = DOT::DOTNode.new(attrs) - + if use_fileboxes - files[last_file].push c + files[last_file].push c else graph << c end end - + if use_fileboxes files.each_value do |val| graph << val end end - + unless container.classes.empty? container.classes.each_with_index do |cl, cl_index| cl.includes.each do |m| @@ -275,7 +275,7 @@ module RDoc container.modules.each do |submod| draw_module(submod, graph) end - + end def convert_to_png(file_base, graph) @@ -294,7 +294,7 @@ module RDoc File.open(src, 'w+' ) do |f| f << str << "\n" end - + system "dot", "-T#{op_type}", src, "-o", dot # Now construct the imagemap wrapper around @@ -318,7 +318,7 @@ module RDoc $stderr.puts "Unexpected output from dot:\n#{area}" return nil end - + xs, ys = [$1.to_i, $3.to_i], [$2.to_i, $4.to_i] url, area_name = $5, $6 diff --git a/lib/rdoc/generators/chm_generator.rb b/lib/rdoc/generators/chm_generator.rb index 51eeda8dd1..ca58045f59 100644 --- a/lib/rdoc/generators/chm_generator.rb +++ b/lib/rdoc/generators/chm_generator.rb @@ -11,7 +11,7 @@ module Generators CHMGenerator.new(options) end - + def initialize(*args) super @op_name = @options.op_name || "rdoc" @@ -28,7 +28,7 @@ module Generators "\n\nYou can download a copy for free from:\n\n" << " http://msdn.microsoft.com/library/default.asp?" << "url=/library/en-us/htmlhelp/html/hwMicrosoftHTMLHelpDownloads.asp\n\n" - + exit 99 end @@ -60,7 +60,7 @@ module Generators end values['all_html_files'] = files - + File.open(@project_name, "w") do |f| template.write_html_on(f, values) end @@ -98,7 +98,7 @@ module Generators template = TemplatePage.new(RDoc::Page::CHM_INDEX) File.open("index.hhk", "w") do |f| template.write_html_on(f, values) - end + end end # Invoke the windows help compiler to compiler the project diff --git a/lib/rdoc/generators/html_generator.rb b/lib/rdoc/generators/html_generator.rb index 1f9b808e8d..8e5bac5390 100644 --- a/lib/rdoc/generators/html_generator.rb +++ b/lib/rdoc/generators/html_generator.rb @@ -9,8 +9,8 @@ # [classes] an html file for each class or module encountered. # These classes are not grouped by file: if a file # contains four classes, we'll generate an html -# file for the file itself, and four html files -# for the individual classes. +# file for the file itself, and four html files +# for the individual classes. # # [indices] we generate three indices for files, classes, # and methods. These are displayed in a browser @@ -49,19 +49,19 @@ module Generators FILE_DIR = "files" CLASS_DIR = "classes" CSS_NAME = "rdoc-style.css" - + ## # Build a hash of all items that can be cross-referenced. - # This is used when we output required and included names: + # This is used when we output required and included names: # if the names appear in this hash, we can generate # an html cross reference to the appropriate description. - # We also use this when parsing comment blocks: any decorated + # We also use this when parsing comment blocks: any decorated # words matching an entry in this list are hyperlinked. class AllReferences @@refs = {} - + def AllReferences::reset @@refs = {} end @@ -155,7 +155,7 @@ module Generators end end - if (type == "http" || type == "link") && + if (type == "http" || type == "link") && url =~ /\.(gif|png|jpg|jpeg|bmp)$/ "" @@ -179,11 +179,11 @@ module Generators # HEre's a hypedlink where the label is different to the URL #