diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 696789a10..6f0d15bb0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,6 +18,14 @@ env: # the vendored Ruby half of prism in Src/StdLib belongs to; release.yml builds from the same # one. Move both together with Src/Prism/Generated when following prism. PRISM_REF: 30a255539e81842b2b7f12b4fd3c62a7b4d64165 + # The DLR revision Build/dlr-patches applies to; release.yml builds from the same one, so a + # release can be rebuilt and an upstream change only arrives when this is moved on purpose. + # Move both together, after checking the patches still apply. + DLR_REF: 922753f8ccbf5186c15899116d5a407b6b1723fb + # ruby/spec and mspec for the spec job, pinned so a result moves only with IronRuby's own + # changes, not with whatever lands upstream on the day. + SPEC_REF: dda28d049100033a8b7050eacbb35957a2eb0c00 + MSPEC_REF: b79c65ed28b00f0869ad82b0e3dceef0d943cd58 jobs: build-and-test: @@ -71,6 +79,7 @@ jobs: uses: actions/checkout@v7 with: repository: IronLanguages/dlr + ref: ${{ env.DLR_REF }} path: dlr # Pinned to the revision Src/Prism/Generated was generated from (Src/Prism/README.md), as @@ -373,6 +382,7 @@ jobs: - uses: actions/checkout@v7 with: repository: IronLanguages/dlr + ref: ${{ env.DLR_REF }} path: dlr - uses: actions/checkout@v7 with: @@ -382,10 +392,12 @@ jobs: - uses: actions/checkout@v7 with: repository: ruby/spec + ref: ${{ env.SPEC_REF }} path: ironruby/spec - uses: actions/checkout@v7 with: repository: ruby/mspec + ref: ${{ env.MSPEC_REF }} path: ironruby/mspec - name: Patch the DLR diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f3adc0eb5..eb2fb1ebd 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -32,6 +32,10 @@ env: # The prism revision Src/Prism/Generated was generated from (Src/Prism/README.md), the one # the vendored Ruby half of prism in Src/StdLib belongs to; ci.yml builds from the same one. PRISM_REF: 30a255539e81842b2b7f12b4fd3c62a7b4d64165 + # The DLR revision Build/dlr-patches applies to; ci.yml builds from the same one, so a + # release can be rebuilt and an upstream change only arrives when this is moved on purpose. + # Move both together, after checking the patches still apply. + DLR_REF: 922753f8ccbf5186c15899116d5a407b6b1723fb jobs: package: @@ -63,6 +67,7 @@ jobs: - uses: actions/checkout@v7 with: repository: IronLanguages/dlr + ref: ${{ env.DLR_REF }} path: dlr - uses: actions/checkout@v7 @@ -159,7 +164,7 @@ jobs: steps: - uses: actions/checkout@v7 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@v6 with: node-version: 22 diff --git a/Build/CustomTasks/CustomTasks.dll b/Build/CustomTasks/CustomTasks.dll deleted file mode 100644 index 6a38eb0fe..000000000 Binary files a/Build/CustomTasks/CustomTasks.dll and /dev/null differ diff --git a/Build/dlr-patches/README.md b/Build/dlr-patches/README.md index 52a104959..43391456f 100644 --- a/Build/dlr-patches/README.md +++ b/Build/dlr-patches/README.md @@ -2,14 +2,16 @@ IronRuby builds against the DLR sources from a sibling `dlr` checkout (`IronLanguages/dlr`). A few changes this tree needs are not upstream yet, so CI -checks out upstream `main` and applies the patches in this directory, in name +checks out the upstream revision pinned as `DLR_REF` in `.github/workflows/ci.yml` and +`release.yml` and applies the patches in this directory, in name order, with `git apply`: ```sh for p in ironruby/Build/dlr-patches/*.patch; do git -C dlr apply "$p"; done ``` -Delete a patch once it lands upstream. If one stops applying, CI fails loudly at +To follow upstream, move `DLR_REF` in both workflows together and check the patches still +apply. Delete a patch once it lands upstream. If one stops applying, CI fails loudly at the apply step instead of with a confusing CS1061 deep inside IronRuby. | Patch | Why IronRuby needs it | diff --git a/README.md b/README.md index 6afe144ed..bf14c0654 100644 --- a/README.md +++ b/README.md @@ -468,6 +468,8 @@ Requires the .NET SDK, plus Ruby and a C compiler to build prism. ```console $ git clone https://github.com/IronLanguages/dlr ../dlr # modern DLR, referenced as source +$ git -C ../dlr checkout +$ for p in Build/dlr-patches/*.patch; do git -C ../dlr apply "$PWD/$p"; done $ git clone https://github.com/ruby/prism ../prism $ (cd ../prism && ruby templates/template.rb && make shared) # libprism.so $ (cd Src/Prism && ruby generate.rb) # C# nodes + loader diff --git a/Src/Libraries/IronRuby.Libraries.csproj b/Src/Libraries/IronRuby.Libraries.csproj index 3081c6003..f9ffbbbfd 100644 --- a/Src/Libraries/IronRuby.Libraries.csproj +++ b/Src/Libraries/IronRuby.Libraries.csproj @@ -17,9 +17,10 @@ - - + + "200 OK" - # "PARTIAL_CONTENT" --> "206 Partial Content" - # "MULTIPLE_CHOICES" --> "300 Multiple Choices" - # "MOVED" --> "301 Moved Permanently" - # "REDIRECT" --> "302 Found" - # "NOT_MODIFIED" --> "304 Not Modified" - # "BAD_REQUEST" --> "400 Bad Request" - # "AUTH_REQUIRED" --> "401 Authorization Required" - # "FORBIDDEN" --> "403 Forbidden" - # "NOT_FOUND" --> "404 Not Found" - # "METHOD_NOT_ALLOWED" --> "405 Method Not Allowed" - # "NOT_ACCEPTABLE" --> "406 Not Acceptable" - # "LENGTH_REQUIRED" --> "411 Length Required" - # "PRECONDITION_FAILED" --> "412 Precondition Failed" - # "SERVER_ERROR" --> "500 Internal Server Error" - # "NOT_IMPLEMENTED" --> "501 Method Not Implemented" - # "BAD_GATEWAY" --> "502 Bad Gateway" - # "VARIANT_ALSO_VARIES" --> "506 Variant Also Negotiates" - # - # This method does not perform charset conversion. - def header(options='text/html') - if options.is_a?(String) - content_type = options - buf = _header_for_string(content_type) - elsif options.is_a?(Hash) - if options.size == 1 && options.has_key?('type') - content_type = options['type'] - buf = _header_for_string(content_type) - else - buf = _header_for_hash(options.dup) - end - else - raise ArgumentError.new("expected String or Hash but got #{options.class}") - end - if defined?(MOD_RUBY) - _header_for_modruby(buf) - return '' - else - buf << EOL # empty line of separator - return buf - end - end # header() - - def _header_for_string(content_type) #:nodoc: - buf = '' - if nph?() - buf << "#{$CGI_ENV['SERVER_PROTOCOL'] || 'HTTP/1.0'} 200 OK#{EOL}" - buf << "Date: #{CGI.rfc1123_date(Time.now)}#{EOL}" - buf << "Server: #{$CGI_ENV['SERVER_SOFTWARE']}#{EOL}" - buf << "Connection: close#{EOL}" - end - buf << "Content-Type: #{content_type}#{EOL}" - if @output_cookies - @output_cookies.each {|cookie| buf << "Set-Cookie: #{cookie}#{EOL}" } - end - return buf - end # _header_for_string - private :_header_for_string - - def _header_for_hash(options) #:nodoc: - buf = '' - ## add charset to option['type'] - options['type'] ||= 'text/html' - charset = options.delete('charset') - options['type'] += "; charset=#{charset}" if charset - ## NPH - options.delete('nph') if defined?(MOD_RUBY) - if options.delete('nph') || nph?() - protocol = $CGI_ENV['SERVER_PROTOCOL'] || 'HTTP/1.0' - status = options.delete('status') - status = HTTP_STATUS[status] || status || '200 OK' - buf << "#{protocol} #{status}#{EOL}" - buf << "Date: #{CGI.rfc1123_date(Time.now)}#{EOL}" - options['server'] ||= $CGI_ENV['SERVER_SOFTWARE'] || '' - options['connection'] ||= 'close' - end - ## common headers - status = options.delete('status') - buf << "Status: #{HTTP_STATUS[status] || status}#{EOL}" if status - server = options.delete('server') - buf << "Server: #{server}#{EOL}" if server - connection = options.delete('connection') - buf << "Connection: #{connection}#{EOL}" if connection - type = options.delete('type') - buf << "Content-Type: #{type}#{EOL}" #if type - length = options.delete('length') - buf << "Content-Length: #{length}#{EOL}" if length - language = options.delete('language') - buf << "Content-Language: #{language}#{EOL}" if language - expires = options.delete('expires') - buf << "Expires: #{CGI.rfc1123_date(expires)}#{EOL}" if expires - ## cookie - if cookie = options.delete('cookie') - case cookie - when String, Cookie - buf << "Set-Cookie: #{cookie}#{EOL}" - when Array - arr = cookie - arr.each {|c| buf << "Set-Cookie: #{c}#{EOL}" } - when Hash - hash = cookie - hash.each {|name, c| buf << "Set-Cookie: #{c}#{EOL}" } - end - end - if @output_cookies - @output_cookies.each {|c| buf << "Set-Cookie: #{c}#{EOL}" } - end - ## other headers - options.each do |key, value| - buf << "#{key}: #{value}#{EOL}" - end - return buf - end # _header_for_hash - private :_header_for_hash - - def nph? #:nodoc: - return /IIS\/(\d+)/.match($CGI_ENV['SERVER_SOFTWARE']) && $1.to_i < 5 - end - - def _header_for_modruby(buf) #:nodoc: - request = Apache::request - buf.scan(/([^:]+): (.+)#{EOL}/o) do |name, value| - warn sprintf("name:%s value:%s\n", name, value) if $DEBUG - case name - when 'Set-Cookie' - request.headers_out.add(name, value) - when /^status$/i - request.status_line = value - request.status = value.to_i - when /^content-type$/i - request.content_type = value - when /^content-encoding$/i - request.content_encoding = value - when /^location$/i - request.status = 302 if request.status == 200 - request.headers_out[name] = value - else - request.headers_out[name] = value - end - end - request.send_http_header - return '' - end - private :_header_for_modruby - # - - # Print an HTTP header and body to $DEFAULT_OUTPUT ($>) - # - # The header is provided by +options+, as for #header(). - # The body of the document is that returned by the passed- - # in block. This block takes no arguments. It is required. - # - # cgi = CGI.new - # cgi.out{ "string" } - # # Content-Type: text/html - # # Content-Length: 6 - # # - # # string - # - # cgi.out("text/plain") { "string" } - # # Content-Type: text/plain - # # Content-Length: 6 - # # - # # string - # - # cgi.out("nph" => true, - # "status" => "OK", # == "200 OK" - # "server" => ENV['SERVER_SOFTWARE'], - # "connection" => "close", - # "type" => "text/html", - # "charset" => "iso-2022-jp", - # # Content-Type: text/html; charset=iso-2022-jp - # "language" => "ja", - # "expires" => Time.now + (3600 * 24 * 30), - # "cookie" => [cookie1, cookie2], - # "my_header1" => "my_value", - # "my_header2" => "my_value") { "string" } - # - # Content-Length is automatically calculated from the size of - # the String returned by the content block. - # - # If ENV['REQUEST_METHOD'] == "HEAD", then only the header - # is outputted (the content block is still required, but it - # is ignored). - # - # If the charset is "iso-2022-jp" or "euc-jp" or "shift_jis" then - # the content is converted to this charset, and the language is set - # to "ja". - def out(options = "text/html") # :yield: - - options = { "type" => options } if options.kind_of?(String) - content = yield - options["length"] = content.bytesize.to_s - output = stdoutput - output.binmode if defined? output.binmode - output.print header(options) - output.print content unless "HEAD" == env_table['REQUEST_METHOD'] - end - - - # Print an argument or list of arguments to the default output stream - # - # cgi = CGI.new - # cgi.print # default: cgi.print == $DEFAULT_OUTPUT.print - def print(*options) - stdoutput.print(*options) - end - - # Parse an HTTP query string into a hash of key=>value pairs. - # - # params = CGI::parse("query_string") - # # {"name1" => ["value1", "value2", ...], - # # "name2" => ["value1", "value2", ...], ... } - # - def CGI::parse(query) - params = {} - query.split(/[&;]/).each do |pairs| - key, value = pairs.split('=',2).collect{|v| CGI::unescape(v) } - if key && value - params.has_key?(key) ? params[key].push(value) : params[key] = [value] - elsif key - params[key]=[] - end - end - params.default=[].freeze - params - end - - # Maximum content length of post data - ##MAX_CONTENT_LENGTH = 2 * 1024 * 1024 - - # Maximum content length of multipart data - MAX_MULTIPART_LENGTH = 128 * 1024 * 1024 - - # Maximum number of request parameters when multipart - MAX_MULTIPART_COUNT = 128 - - # Mixin module. It provides the follow functionality groups: - # - # 1. Access to CGI environment variables as methods. See - # documentation to the CGI class for a list of these variables. - # - # 2. Access to cookies, including the cookies attribute. - # - # 3. Access to parameters, including the params attribute, and overloading - # [] to perform parameter value lookup by key. - # - # 4. The initialize_query method, for initialising the above - # mechanisms, handling multipart forms, and allowing the - # class to be used in "offline" mode. - # - module QueryExtension - - %w[ CONTENT_LENGTH SERVER_PORT ].each do |env| - define_method(env.sub(/^HTTP_/, '').downcase) do - (val = env_table[env]) && Integer(val) - end - end - - %w[ AUTH_TYPE CONTENT_TYPE GATEWAY_INTERFACE PATH_INFO - PATH_TRANSLATED QUERY_STRING REMOTE_ADDR REMOTE_HOST - REMOTE_IDENT REMOTE_USER REQUEST_METHOD SCRIPT_NAME - SERVER_NAME SERVER_PROTOCOL SERVER_SOFTWARE - - HTTP_ACCEPT HTTP_ACCEPT_CHARSET HTTP_ACCEPT_ENCODING - HTTP_ACCEPT_LANGUAGE HTTP_CACHE_CONTROL HTTP_FROM HTTP_HOST - HTTP_NEGOTIATE HTTP_PRAGMA HTTP_REFERER HTTP_USER_AGENT ].each do |env| - define_method(env.sub(/^HTTP_/, '').downcase) do - env_table[env] - end - end - - # Get the raw cookies as a string. - def raw_cookie - env_table["HTTP_COOKIE"] - end - - # Get the raw RFC2965 cookies as a string. - def raw_cookie2 - env_table["HTTP_COOKIE2"] - end - - # Get the cookies as a hash of cookie-name=>Cookie pairs. - attr_accessor :cookies - - # Get the parameters as a hash of name=>values pairs, where - # values is an Array. - attr_reader :params - - # Get the uploaded files as a hash of name=>values pairs - attr_reader :files - - # Set all the parameters. - def params=(hash) - @params.clear - @params.update(hash) - end - - def read_multipart(boundary, content_length) - ## read first boundary - stdin = $stdin - first_line = "--#{boundary}#{EOL}" - content_length -= first_line.bytesize - status = stdin.read(first_line.bytesize) - raise EOFError.new("no content body") unless status - raise EOFError.new("bad content body") unless first_line == status - ## parse and set params - params = {} - @files = {} - boundary_rexp = /--#{Regexp.quote(boundary)}(#{EOL}|--)/ - boundary_size = "#{EOL}--#{boundary}#{EOL}".bytesize - boundary_end = nil - buf = '' - bufsize = 10 * 1024 - max_count = MAX_MULTIPART_COUNT - n = 0 - while true - (n += 1) < max_count or raise StandardError.new("too many parameters.") - ## create body (StringIO or Tempfile) - body = create_body(bufsize < content_length) - class << body - if method_defined?(:path) - alias local_path path - else - def local_path - nil - end - end - attr_reader :original_filename, :content_type - end - ## find head and boundary - head = nil - separator = EOL * 2 - until head && matched = boundary_rexp.match(buf) - if !head && pos = buf.index(separator) - len = pos + EOL.bytesize - head = buf[0, len] - buf = buf[(pos+separator.bytesize)..-1] - else - if head && buf.size > boundary_size - len = buf.size - boundary_size - body.print(buf[0, len]) - buf[0, len] = '' - end - c = stdin.read(bufsize < content_length ? bufsize : content_length) - raise EOFError.new("bad content body") if c.nil? || c.empty? - buf << c - content_length -= c.bytesize - end - end - ## read to end of boundary - m = matched - len = m.begin(0) - s = buf[0, len] - if s =~ /(\r?\n)\z/ - s = buf[0, len - $1.bytesize] - end - body.print(s) - buf = buf[m.end(0)..-1] - boundary_end = m[1] - content_length = -1 if boundary_end == '--' - ## reset file cursor position - body.rewind - ## original filename - /Content-Disposition:.* filename=(?:"(.*?)"|([^;\r\n]*))/i.match(head) - filename = $1 || $2 || '' - filename = CGI.unescape(filename) if unescape_filename?() - body.instance_variable_set('@original_filename', filename) - ## content type - /Content-Type: (.*)/i.match(head) - (content_type = $1 || '').chomp! - body.instance_variable_set('@content_type', content_type) - ## query parameter name - /Content-Disposition:.* name=(?:"(.*?)"|([^;\r\n]*))/i.match(head) - name = $1 || $2 || '' - if body.original_filename.empty? - value=body.read.dup.force_encoding(@accept_charset) - (params[name] ||= []) << value - unless value.valid_encoding? - if @accept_charset_error_block - @accept_charset_error_block.call(name,value) - else - raise InvalidEncoding,"Accept-Charset encoding error" - end - end - class << params[name].last;self;end.class_eval do - define_method(:read){self} - define_method(:original_filename){""} - define_method(:content_type){""} - end - else - (params[name] ||= []) << body - @files[name]=body - end - ## break loop - break if buf.size == 0 - break if content_length == -1 - end - raise EOFError, "bad boundary end of body part" unless boundary_end =~ /--/ - params.default = [] - params - end # read_multipart - private :read_multipart - def create_body(is_large) #:nodoc: - if is_large - require 'tempfile' - body = Tempfile.new('CGI', encoding: "ascii-8bit") - else - begin - require 'stringio' - body = StringIO.new("".force_encoding("ascii-8bit")) - rescue LoadError - require 'tempfile' - body = Tempfile.new('CGI', encoding: "ascii-8bit") - end - end - body.binmode if defined? body.binmode - return body - end - def unescape_filename? #:nodoc: - user_agent = $CGI_ENV['HTTP_USER_AGENT'] - return /Mac/i.match(user_agent) && /Mozilla/i.match(user_agent) && !/MSIE/i.match(user_agent) - end - - # offline mode. read name=value pairs on standard input. - def read_from_cmdline - require "shellwords" - - string = unless ARGV.empty? - ARGV.join(' ') - else - if STDIN.tty? - STDERR.print( - %|(offline mode: enter name=value pairs on standard input)\n| - ) - end - array = readlines rescue nil - if not array.nil? - array.join(' ').gsub(/\n/n, '') - else - "" - end - end.gsub(/\\=/n, '%3D').gsub(/\\&/n, '%26') - - words = Shellwords.shellwords(string) - - if words.find{|x| /=/n.match(x) } - words.join('&') - else - words.join('+') - end - end - private :read_from_cmdline - - # A wrapper class to use a StringIO object as the body and switch - # to a TempFile when the passed threshold is passed. - # Initialize the data from the query. - # - # Handles multipart forms (in particular, forms that involve file uploads). - # Reads query parameters in the @params field, and cookies into @cookies. - def initialize_query() - if ("POST" == env_table['REQUEST_METHOD']) and - %r|\Amultipart/form-data.*boundary=\"?([^\";,]+)\"?|.match(env_table['CONTENT_TYPE']) - raise StandardError.new("too large multipart data.") if env_table['CONTENT_LENGTH'].to_i > MAX_MULTIPART_LENGTH - boundary = $1.dup - @multipart = true - @params = read_multipart(boundary, Integer(env_table['CONTENT_LENGTH'])) - else - @multipart = false - @params = CGI::parse( - case env_table['REQUEST_METHOD'] - when "GET", "HEAD" - if defined?(MOD_RUBY) - Apache::request.args or "" - else - env_table['QUERY_STRING'] or "" - end - when "POST" - stdinput.binmode if defined? stdinput.binmode - stdinput.read(Integer(env_table['CONTENT_LENGTH'])) or '' - else - read_from_cmdline - end.dup.force_encoding(@accept_charset) - ) - unless Encoding.find(@accept_charset) == Encoding::ASCII_8BIT - @params.each do |key,values| - values.each do |value| - unless value.valid_encoding? - if @accept_charset_error_block - @accept_charset_error_block.call(key,value) - else - raise InvalidEncoding,"Accept-Charset encoding error" - end - end - end - end - end - end - - @cookies = CGI::Cookie::parse((env_table['HTTP_COOKIE'] or env_table['COOKIE'])) - end - private :initialize_query - - def multipart? - @multipart - end - - # Get the value for the parameter with a given key. - # - # If the parameter has multiple values, only the first will be - # retrieved; use #params() to get the array of values. - def [](key) - params = @params[key] - return '' unless params - value = params[0] - if @multipart - if value - return value - elsif defined? StringIO - StringIO.new("".force_encoding("ascii-8bit")) - else - Tempfile.new("CGI",encoding:"ascii-8bit") - end - else - str = if value then value.dup else "" end - str - end - end - - # Return all parameter keys as an array. - def keys(*args) - @params.keys(*args) - end - - # Returns true if a given parameter key exists in the query. - def has_key?(*args) - @params.has_key?(*args) - end - alias key? has_key? - alias include? has_key? - - end # QueryExtension - - # InvalidEncoding Exception class - class InvalidEncoding < Exception; end - - # @@accept_charset is default accept character set. - # This default value default is "UTF-8" - # If you want to change the default accept character set - # when create a new CGI instance, set this: - # - # CGI.accept_charset = "EUC-JP" - # - - @@accept_charset="UTF-8" - - def self.accept_charset - @@accept_charset - end - - def self.accept_charset=(accept_charset) - @@accept_charset=accept_charset - end - - # Create a new CGI instance. - # - # CGI accept constructor parameters either in a hash, string as a block. - # But string is as same as using :tag_maker of hash. - # - # CGI.new("html3") #=> CGI.new(:tag_maker=>"html3") - # - # And, if you specify string, @accept_charset cannot be changed. - # Instead, please use hash parameter. - # - # == accept_charset - # - # :accept_charset specifies encoding of received query string. - # ( Default value is @@accept_charset. ) - # If not valid, raise CGI::InvalidEncoding - # - # Example. Suppose @@accept_charset # => "UTF-8" - # - # when not specified: - # - # cgi=CGI.new # @accept_charset # => "UTF-8" - # - # when specified "EUC-JP": - # - # cgi=CGI.new(:accept_charset => "EUC-JP") # => "EUC-JP" - # - # == block - # - # When you use a block, you can write a process - # that query encoding is invalid. Example: - # - # encoding_error={} - # cgi=CGI.new(:accept_charset=>"EUC-JP") do |name,value| - # encoding_error[key] = value - # end - # - # == tag_maker - # - # :tag_maker specifies which version of HTML to load the HTML generation - # methods for. The following versions of HTML are supported: - # - # html3:: HTML 3.x - # html4:: HTML 4.0 - # html4Tr:: HTML 4.0 Transitional - # html4Fr:: HTML 4.0 with Framesets - # - # If not specified, no HTML generation methods will be loaded. - # - # If the CGI object is not created in a standard CGI call environment - # (that is, it can't locate REQUEST_METHOD in its environment), then - # it will run in "offline" mode. In this mode, it reads its parameters - # from the command line or (failing that) from standard input. Otherwise, - # cookies and other parameters are parsed automatically from the standard - # CGI locations, which varies according to the REQUEST_METHOD. It works this: - # - # CGI.new(:tag_maker=>"html3") - # - # This will be obsolete: - # - # CGI.new("html3") - # - attr_reader :accept_charset - def initialize(options = {},&block) - @accept_charset_error_block=block if block_given? - @options={:accept_charset=>@@accept_charset} - case options - when Hash - @options.merge!(options) - when String - @options[:tag_maker]=options - end - @accept_charset=@options[:accept_charset] - if defined?(MOD_RUBY) && !ENV.key?("GATEWAY_INTERFACE") - Apache.request.setup_cgi_env - end - - extend QueryExtension - @multipart = false - - initialize_query() # set @params, @cookies - @output_cookies = nil - @output_hidden = nil - - case @options[:tag_maker] - when "html3" - require 'cgi/html' - extend Html3 - element_init() - extend HtmlExtension - when "html4" - require 'cgi/html' - extend Html4 - element_init() - extend HtmlExtension - when "html4Tr" - require 'cgi/html' - extend Html4Tr - element_init() - extend HtmlExtension - when "html4Fr" - require 'cgi/html' - extend Html4Tr - element_init() - extend Html4Fr - element_init() - extend HtmlExtension - end - end - -end # class CGI - - diff --git a/Src/StdLib/ruby/1.9.1/cgi/html.rb b/Src/StdLib/ruby/1.9.1/cgi/html.rb deleted file mode 100644 index a068b9556..000000000 --- a/Src/StdLib/ruby/1.9.1/cgi/html.rb +++ /dev/null @@ -1,1021 +0,0 @@ - # Base module for HTML-generation mixins. - # - # Provides methods for code generation for tags following - # the various DTD element types. -class CGI - module TagMaker # :nodoc: - - # Generate code for an element with required start and end tags. - # - # - - - def nn_element_def(element) - nOE_element_def(element, <<-END) - if block_given? - yield.to_s - else - "" - end + - "" - END - end - - # Generate code for an empty element. - # - # - O EMPTY - def nOE_element_def(element, append = nil) - s = <<-END - attributes={attributes=>nil} if attributes.kind_of?(String) - "<#{element.upcase}" + attributes.collect{|name, value| - next unless value - " " + CGI::escapeHTML(name.to_s) + - if true == value - "" - else - '="' + CGI::escapeHTML(value.to_s) + '"' - end - }.join + ">" - END - s.sub!(/\Z/, " +") << append if append - s - end - - # Generate code for an element for which the end (and possibly the - # start) tag is optional. - # - # O O or - O - def nO_element_def(element) - nOE_element_def(element, <<-END) - if block_given? - yield.to_s + "" - else - "" - end - END - end - - end # TagMaker - - - # - # Mixin module providing HTML generation methods. - # - # For example, - # cgi.a("http://www.example.com") { "Example" } - # # => "Example" - # - # Modules Http3, Http4, etc., contain more basic HTML-generation methods - # (:title, :center, etc.). - # - # See class CGI for a detailed example. - # - module HtmlExtension - - - # Generate an Anchor element as a string. - # - # +href+ can either be a string, giving the URL - # for the HREF attribute, or it can be a hash of - # the element's attributes. - # - # The body of the element is the string returned by the no-argument - # block passed in. - # - # a("http://www.example.com") { "Example" } - # # => "Example" - # - # a("HREF" => "http://www.example.com", "TARGET" => "_top") { "Example" } - # # => "Example" - # - def a(href = "") # :yield: - attributes = if href.kind_of?(String) - { "HREF" => href } - else - href - end - if block_given? - super(attributes){ yield } - else - super(attributes) - end - end - - # Generate a Document Base URI element as a String. - # - # +href+ can either by a string, giving the base URL for the HREF - # attribute, or it can be a has of the element's attributes. - # - # The passed-in no-argument block is ignored. - # - # base("http://www.example.com/cgi") - # # => "" - def base(href = "") # :yield: - attributes = if href.kind_of?(String) - { "HREF" => href } - else - href - end - if block_given? - super(attributes){ yield } - else - super(attributes) - end - end - - # Generate a BlockQuote element as a string. - # - # +cite+ can either be a string, give the URI for the source of - # the quoted text, or a hash, giving all attributes of the element, - # or it can be omitted, in which case the element has no attributes. - # - # The body is provided by the passed-in no-argument block - # - # blockquote("http://www.example.com/quotes/foo.html") { "Foo!" } - # #=> "
Foo!
- def blockquote(cite = {}) # :yield: - attributes = if cite.kind_of?(String) - { "CITE" => cite } - else - cite - end - if block_given? - super(attributes){ yield } - else - super(attributes) - end - end - - - # Generate a Table Caption element as a string. - # - # +align+ can be a string, giving the alignment of the caption - # (one of top, bottom, left, or right). It can be a hash of - # all the attributes of the element. Or it can be omitted. - # - # The body of the element is provided by the passed-in no-argument block. - # - # caption("left") { "Capital Cities" } - # # => Capital Cities - def caption(align = {}) # :yield: - attributes = if align.kind_of?(String) - { "ALIGN" => align } - else - align - end - if block_given? - super(attributes){ yield } - else - super(attributes) - end - end - - - # Generate a Checkbox Input element as a string. - # - # The attributes of the element can be specified as three arguments, - # +name+, +value+, and +checked+. +checked+ is a boolean value; - # if true, the CHECKED attribute will be included in the element. - # - # Alternatively, the attributes can be specified as a hash. - # - # checkbox("name") - # # = checkbox("NAME" => "name") - # - # checkbox("name", "value") - # # = checkbox("NAME" => "name", "VALUE" => "value") - # - # checkbox("name", "value", true) - # # = checkbox("NAME" => "name", "VALUE" => "value", "CHECKED" => true) - def checkbox(name = "", value = nil, checked = nil) - attributes = if name.kind_of?(String) - { "TYPE" => "checkbox", "NAME" => name, - "VALUE" => value, "CHECKED" => checked } - else - name["TYPE"] = "checkbox" - name - end - input(attributes) - end - - # Generate a sequence of checkbox elements, as a String. - # - # The checkboxes will all have the same +name+ attribute. - # Each checkbox is followed by a label. - # There will be one checkbox for each value. Each value - # can be specified as a String, which will be used both - # as the value of the VALUE attribute and as the label - # for that checkbox. A single-element array has the - # same effect. - # - # Each value can also be specified as a three-element array. - # The first element is the VALUE attribute; the second is the - # label; and the third is a boolean specifying whether this - # checkbox is CHECKED. - # - # Each value can also be specified as a two-element - # array, by omitting either the value element (defaults - # to the same as the label), or the boolean checked element - # (defaults to false). - # - # checkbox_group("name", "foo", "bar", "baz") - # # 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) - if name.kind_of?(Hash) - values = name["VALUES"] - name = name["NAME"] - end - values.collect{|value| - if value.kind_of?(String) - checkbox(name, value) + value - else - if value[-1] == true || value[-1] == false - checkbox(name, value[0], value[-1]) + - value[-2] - else - checkbox(name, value[0]) + - value[-1] - end - end - }.join - end - - - # Generate an File Upload Input element as a string. - # - # The attributes of the element can be specified as three arguments, - # +name+, +size+, and +maxlength+. +maxlength+ is the maximum length - # of the file's _name_, not of the file's _contents_. - # - # Alternatively, the attributes can be specified as a hash. - # - # See #multipart_form() for forms that include file uploads. - # - # file_field("name") - # # - # - # file_field("name", 40) - # # - # - # file_field("name", 40, 100) - # # - # - # file_field("NAME" => "name", "SIZE" => 40) - # # - def file_field(name = "", size = 20, maxlength = nil) - attributes = if name.kind_of?(String) - { "TYPE" => "file", "NAME" => name, - "SIZE" => size.to_s } - else - name["TYPE"] = "file" - name - end - attributes["MAXLENGTH"] = maxlength.to_s if maxlength - input(attributes) - end - - - # Generate a Form element as a string. - # - # +method+ should be either "get" or "post", and defaults to the latter. - # +action+ defaults to the current CGI script name. +enctype+ - # defaults to "application/x-www-form-urlencoded". - # - # Alternatively, the attributes can be specified as a hash. - # - # See also #multipart_form() for forms that include file uploads. - # - # form{ "string" } - # #
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 } - else - unless method.has_key?("METHOD") - method["METHOD"] = "post" - end - unless method.has_key?("ENCTYPE") - method["ENCTYPE"] = enctype - end - method - end - if block_given? - body = yield - else - body = "" - end - if @output_hidden - body += @output_hidden.collect{|k,v| - "" - }.join - end - super(attributes){body} - end - - # Generate a Hidden Input element as a string. - # - # The attributes of the element can be specified as two arguments, - # +name+ and +value+. - # - # Alternatively, the attributes can be specified as a hash. - # - # hidden("name") - # # - # - # hidden("name", "value") - # # - # - # hidden("NAME" => "name", "VALUE" => "reset", "ID" => "foo") - # # - def hidden(name = "", value = nil) - attributes = if name.kind_of?(String) - { "TYPE" => "hidden", "NAME" => name, "VALUE" => value } - else - name["TYPE"] = "hidden" - name - end - input(attributes) - end - - # Generate a top-level HTML element as a string. - # - # The attributes of the element are specified as a hash. The - # pseudo-attribute "PRETTY" can be used to specify that the generated - # HTML string should be indented. "PRETTY" can also be specified as - # a string as the sole argument to this method. The pseudo-attribute - # "DOCTYPE", if given, is used as the leading DOCTYPE SGML tag; it - # should include the entire text of this tag, including angle brackets. - # - # The body of the html element is supplied as a block. - # - # html{ "string" } - # # 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: - if nil == attributes - attributes = {} - elsif "PRETTY" == attributes - attributes = { "PRETTY" => true } - end - pretty = attributes.delete("PRETTY") - pretty = " " if true == pretty - buf = "" - - if attributes.has_key?("DOCTYPE") - if attributes["DOCTYPE"] - buf += attributes.delete("DOCTYPE") - else - attributes.delete("DOCTYPE") - end - else - buf += doctype - end - - if block_given? - buf += super(attributes){ yield } - else - buf += super(attributes) - end - - if pretty - CGI::pretty(buf, pretty) - else - buf - end - - end - - # Generate an Image Button Input element as a string. - # - # +src+ is the URL of the image to use for the button. +name+ - # is the input name. +alt+ is the alternative text for the image. - # - # Alternatively, the attributes can be specified as a hash. - # - # image_button("url") - # # - # - # image_button("url", "name", "string") - # # - # - # image_button("SRC" => "url", "ALT" => "string") - # # - def image_button(src = "", name = nil, alt = nil) - attributes = if src.kind_of?(String) - { "TYPE" => "image", "SRC" => src, "NAME" => name, - "ALT" => alt } - else - src["TYPE"] = "image" - src["SRC"] ||= "" - src - end - input(attributes) - end - - - # Generate an Image element as a string. - # - # +src+ is the URL of the image. +alt+ is the alternative text for - # the image. +width+ is the width of the image, and +height+ is - # its height. - # - # Alternatively, the attributes can be specified as a hash. - # - # img("src", "alt", 100, 50) - # # alt - # - # img("SRC" => "src", "ALT" => "alt", "WIDTH" => 100, "HEIGHT" => 50) - # # alt - def img(src = "", alt = "", width = nil, height = nil) - attributes = if src.kind_of?(String) - { "SRC" => src, "ALT" => alt } - else - src - end - attributes["WIDTH"] = width.to_s if width - attributes["HEIGHT"] = height.to_s if height - super(attributes) - end - - - # Generate a Form element with multipart encoding as a String. - # - # Multipart encoding is used for forms that include file uploads. - # - # +action+ is the action to perform. +enctype+ is the encoding - # type, which defaults to "multipart/form-data". - # - # Alternatively, the attributes can be specified as a hash. - # - # multipart_form{ "string" } - # #
string
- # - # multipart_form("url") { "string" } - # #
string
- def multipart_form(action = nil, enctype = "multipart/form-data") - attributes = if action == nil - { "METHOD" => "post", "ENCTYPE" => enctype } - elsif action.kind_of?(String) - { "METHOD" => "post", "ACTION" => action, - "ENCTYPE" => enctype } - else - unless action.has_key?("METHOD") - action["METHOD"] = "post" - end - unless action.has_key?("ENCTYPE") - action["ENCTYPE"] = enctype - end - action - end - if block_given? - form(attributes){ yield } - else - form(attributes) - end - end - - - # Generate a Password Input element as a string. - # - # +name+ is the name of the input field. +value+ is its default - # value. +size+ is the size of the input field display. +maxlength+ - # is the maximum length of the inputted password. - # - # Alternatively, attributes can be specified as a hash. - # - # password_field("name") - # # - # - # 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) - attributes = if name.kind_of?(String) - { "TYPE" => "password", "NAME" => name, - "VALUE" => value, "SIZE" => size.to_s } - else - name["TYPE"] = "password" - name - end - attributes["MAXLENGTH"] = maxlength.to_s if maxlength - input(attributes) - end - - # Generate a Select element as a string. - # - # +name+ is the name of the element. The +values+ are the options that - # can be selected from the Select menu. Each value can be a String or - # a one, two, or three-element Array. If a String or a one-element - # Array, this is both the value of that option and the text displayed for - # it. If a three-element Array, the elements are the option value, displayed - # text, and a boolean value specifying whether this option starts as selected. - # The two-element version omits either the option value (defaults to the same - # as the display text) or the boolean selected specifier (defaults to false). - # - # The attributes and options can also be specified as a hash. In this - # case, options are specified as an array of values as described above, - # with the hash key of "VALUES". - # - # popup_menu("name", "foo", "bar", "baz") - # # - # - # 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"]) - # # - def popup_menu(name = "", *values) - - if name.kind_of?(Hash) - values = name["VALUES"] - size = name["SIZE"].to_s if name["SIZE"] - multiple = name["MULTIPLE"] - name = name["NAME"] - else - size = nil - multiple = nil - end - - select({ "NAME" => name, "SIZE" => size, - "MULTIPLE" => multiple }){ - values.collect{|value| - if value.kind_of?(String) - option({ "VALUE" => value }){ value } - else - if value[value.size - 1] == true - option({ "VALUE" => value[0], "SELECTED" => true }){ - value[value.size - 2] - } - else - option({ "VALUE" => value[0] }){ - value[value.size - 1] - } - end - end - }.join - } - - end - - # Generates a radio-button Input element. - # - # +name+ is the name of the input field. +value+ is the value of - # the field if checked. +checked+ specifies whether the field - # starts off checked. - # - # Alternatively, the attributes can be specified as a hash. - # - # radio_button("name", "value") - # # - # - # radio_button("name", "value", true) - # # - # - # radio_button("NAME" => "name", "VALUE" => "value", "ID" => "foo") - # # - def radio_button(name = "", value = nil, checked = nil) - attributes = if name.kind_of?(String) - { "TYPE" => "radio", "NAME" => name, - "VALUE" => value, "CHECKED" => checked } - else - name["TYPE"] = "radio" - name - end - input(attributes) - end - - # Generate a sequence of radio button Input elements, as a String. - # - # This works the same as #checkbox_group(). However, it is not valid - # to have more than one radiobutton in a group checked. - # - # radio_group("name", "foo", "bar", "baz") - # # 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) - if name.kind_of?(Hash) - values = name["VALUES"] - name = name["NAME"] - end - values.collect{|value| - if value.kind_of?(String) - radio_button(name, value) + value - else - if value[-1] == true || value[-1] == false - radio_button(name, value[0], value[-1]) + - value[-2] - else - radio_button(name, value[0]) + - value[-1] - end - end - }.join - end - - # Generate a reset button Input element, as a String. - # - # This resets the values on a form to their initial values. +value+ - # is the text displayed on the button. +name+ is the name of this button. - # - # Alternatively, the attributes can be specified as a hash. - # - # reset - # # - # - # reset("reset") - # # - # - # reset("VALUE" => "reset", "ID" => "foo") - # # - def reset(value = nil, name = nil) - attributes = if (not value) or value.kind_of?(String) - { "TYPE" => "reset", "VALUE" => value, "NAME" => name } - else - value["TYPE"] = "reset" - value - end - input(attributes) - end - - alias scrolling_list popup_menu - - # Generate a submit button Input element, as a String. - # - # +value+ is the text to display on the button. +name+ is the name - # of the input. - # - # Alternatively, the attributes can be specified as a hash. - # - # submit - # # - # - # submit("ok") - # # - # - # submit("ok", "button1") - # # - # - # submit("VALUE" => "ok", "NAME" => "button1", "ID" => "foo") - # # - def submit(value = nil, name = nil) - attributes = if (not value) or value.kind_of?(String) - { "TYPE" => "submit", "VALUE" => value, "NAME" => name } - else - value["TYPE"] = "submit" - value - end - input(attributes) - end - - # Generate a text field Input element, as a String. - # - # +name+ is the name of the input field. +value+ is its initial - # value. +size+ is the size of the input area. +maxlength+ - # is the maximum length of input accepted. - # - # Alternatively, the attributes can be specified as a hash. - # - # text_field("name") - # # - # - # 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) - attributes = if name.kind_of?(String) - { "TYPE" => "text", "NAME" => name, "VALUE" => value, - "SIZE" => size.to_s } - else - name["TYPE"] = "text" - name - end - attributes["MAXLENGTH"] = maxlength.to_s if maxlength - input(attributes) - end - - # Generate a TextArea element, as a String. - # - # +name+ is the name of the textarea. +cols+ is the number of - # columns and +rows+ is the number of rows in the display. - # - # Alternatively, the attributes can be specified as a hash. - # - # The body is provided by the passed-in no-argument block - # - # textarea("name") - # # = textarea("NAME" => "name", "COLS" => 70, "ROWS" => 10) - # - # textarea("name", 40, 5) - # # = textarea("NAME" => "name", "COLS" => 40, "ROWS" => 5) - def textarea(name = "", cols = 70, rows = 10) # :yield: - attributes = if name.kind_of?(String) - { "NAME" => name, "COLS" => cols.to_s, - "ROWS" => rows.to_s } - else - name - end - if block_given? - super(attributes){ yield } - else - super(attributes) - end - end - - end # HtmlExtension - - - # Mixin module for HTML version 3 generation methods. - module Html3 # :nodoc: - - # The DOCTYPE declaration for this version of HTML - def doctype - %|| - end - - # Initialise the HTML generation methods for this version. - def element_init - extend TagMaker - methods = "" - # - - - for element in %w[ A TT I B U STRIKE BIG SMALL SUB SUP EM STRONG - DFN CODE SAMP KBD VAR CITE FONT ADDRESS DIV center MAP - APPLET PRE XMP LISTING DL OL UL DIR MENU SELECT table TITLE - STYLE SCRIPT H1 H2 H3 H4 H5 H6 TEXTAREA FORM BLOCKQUOTE - CAPTION ] - methods += <<-BEGIN + nn_element_def(element) + <<-END - def #{element.downcase}(attributes = {}) - BEGIN - end - END - end - - # - O EMPTY - for element in %w[ IMG BASE BASEFONT BR AREA LINK PARAM HR INPUT - ISINDEX META ] - methods += <<-BEGIN + nOE_element_def(element) + <<-END - def #{element.downcase}(attributes = {}) - BEGIN - end - END - end - - # O O or - O - for element in %w[ HTML HEAD BODY P PLAINTEXT DT DD LI OPTION tr - th td ] - methods += <<-BEGIN + nO_element_def(element) + <<-END - def #{element.downcase}(attributes = {}) - BEGIN - end - END - end - eval(methods) - end - - end # Html3 - - - # Mixin module for HTML version 4 generation methods. - module Html4 # :nodoc: - - # The DOCTYPE declaration for this version of HTML - def doctype - %|| - end - - # Initialise the HTML generation methods for this version. - def element_init - extend TagMaker - methods = "" - # - - - for element in %w[ TT I B BIG SMALL EM STRONG DFN CODE SAMP KBD - VAR CITE ABBR ACRONYM SUB SUP SPAN BDO ADDRESS DIV MAP OBJECT - H1 H2 H3 H4 H5 H6 PRE Q INS DEL DL OL UL LABEL SELECT OPTGROUP - FIELDSET LEGEND BUTTON TABLE TITLE STYLE SCRIPT NOSCRIPT - TEXTAREA FORM A BLOCKQUOTE CAPTION ] - methods += <<-BEGIN + nn_element_def(element) + <<-END - def #{element.downcase}(attributes = {}) - BEGIN - end - END - end - - # - O EMPTY - for element in %w[ IMG BASE BR AREA LINK PARAM HR INPUT COL META ] - methods += <<-BEGIN + nOE_element_def(element) + <<-END - def #{element.downcase}(attributes = {}) - BEGIN - end - END - end - - # O O or - O - for element in %w[ HTML BODY P DT DD LI OPTION THEAD TFOOT TBODY - COLGROUP TR TH TD HEAD] - methods += <<-BEGIN + nO_element_def(element) + <<-END - def #{element.downcase}(attributes = {}) - BEGIN - end - END - end - eval(methods) - end - - end # Html4 - - - # Mixin module for HTML version 4 transitional generation methods. - module Html4Tr # :nodoc: - - # The DOCTYPE declaration for this version of HTML - def doctype - %|| - end - - # Initialise the HTML generation methods for this version. - def element_init - extend TagMaker - methods = "" - # - - - for element in %w[ TT I B U S STRIKE BIG SMALL EM STRONG DFN - CODE SAMP KBD VAR CITE ABBR ACRONYM FONT SUB SUP SPAN BDO - ADDRESS DIV CENTER MAP OBJECT APPLET H1 H2 H3 H4 H5 H6 PRE Q - INS DEL DL OL UL DIR MENU LABEL SELECT OPTGROUP FIELDSET - LEGEND BUTTON TABLE IFRAME NOFRAMES TITLE STYLE SCRIPT - NOSCRIPT TEXTAREA FORM A BLOCKQUOTE CAPTION ] - methods += <<-BEGIN + nn_element_def(element) + <<-END - def #{element.downcase}(attributes = {}) - BEGIN - end - END - end - - # - O EMPTY - for element in %w[ IMG BASE BASEFONT BR AREA LINK PARAM HR INPUT - COL ISINDEX META ] - methods += <<-BEGIN + nOE_element_def(element) + <<-END - def #{element.downcase}(attributes = {}) - BEGIN - end - END - end - - # O O or - O - for element in %w[ HTML BODY P DT DD LI OPTION THEAD TFOOT TBODY - COLGROUP TR TH TD HEAD ] - methods += <<-BEGIN + nO_element_def(element) + <<-END - def #{element.downcase}(attributes = {}) - BEGIN - end - END - end - eval(methods) - end - - end # Html4Tr - - - # Mixin module for generating HTML version 4 with framesets. - module Html4Fr # :nodoc: - - # The DOCTYPE declaration for this version of HTML - def doctype - %|| - end - - # Initialise the HTML generation methods for this version. - def element_init - methods = "" - # - - - for element in %w[ FRAMESET ] - methods += <<-BEGIN + nn_element_def(element) + <<-END - def #{element.downcase}(attributes = {}) - BEGIN - end - END - end - - # - O EMPTY - for element in %w[ FRAME ] - methods += <<-BEGIN + nOE_element_def(element) + <<-END - def #{element.downcase}(attributes = {}) - BEGIN - end - END - end - eval(methods) - end - - end # Html4Fr -end - - diff --git a/Src/StdLib/ruby/1.9.1/cgi/session.rb b/Src/StdLib/ruby/1.9.1/cgi/session.rb deleted file mode 100644 index 720c96363..000000000 --- a/Src/StdLib/ruby/1.9.1/cgi/session.rb +++ /dev/null @@ -1,537 +0,0 @@ -# -# cgi/session.rb - session support for cgi scripts -# -# Copyright (C) 2001 Yukihiro "Matz" Matsumoto -# Copyright (C) 2000 Network Applied Communication Laboratory, Inc. -# Copyright (C) 2000 Information-technology Promotion Agency, Japan -# -# Author: Yukihiro "Matz" Matsumoto -# -# Documentation: William Webber (william@williamwebber.com) -# -# == Overview -# -# This file provides the +CGI::Session+ class, which provides session -# support for CGI scripts. A session is a sequence of HTTP requests -# and responses linked together and associated with a single client. -# Information associated with the session is stored -# on the server between requests. A session id is passed between client -# and server with every request and response, transparently -# to the user. This adds state information to the otherwise stateless -# HTTP request/response protocol. -# -# See the documentation to the +CGI::Session+ class for more details -# and examples of usage. See cgi.rb for the +CGI+ class itself. - -require 'cgi' -require 'tmpdir' - -class CGI - - # Class representing an HTTP session. See documentation for the file - # cgi/session.rb for an introduction to HTTP sessions. - # - # == Lifecycle - # - # A CGI::Session instance is created from a CGI object. By default, - # this CGI::Session instance will start a new session if none currently - # exists, or continue the current session for this client if one does - # exist. The +new_session+ option can be used to either always or - # never create a new session. See #new() for more details. - # - # #delete() deletes a session from session storage. It - # does not however remove the session id from the client. If the client - # makes another request with the same id, the effect will be to start - # a new session with the old session's id. - # - # == Setting and retrieving session data. - # - # The Session class associates data with a session as key-value pairs. - # This data can be set and retrieved by indexing the Session instance - # using '[]', much the same as hashes (although other hash methods - # are not supported). - # - # When session processing has been completed for a request, the - # session should be closed using the close() method. This will - # store the session's state to persistent storage. If you want - # to store the session's state to persistent storage without - # finishing session processing for this request, call the update() - # method. - # - # == Storing session state - # - # The caller can specify what form of storage to use for the session's - # data with the +database_manager+ option to CGI::Session::new. The - # following storage classes are provided as part of the standard library: - # - # CGI::Session::FileStore:: stores data as plain text in a flat file. Only - # works with String data. This is the default - # storage type. - # CGI::Session::MemoryStore:: stores data in an in-memory hash. The data - # only persists for as long as the current ruby - # interpreter instance does. - # CGI::Session::PStore:: stores data in Marshalled format. Provided by - # cgi/session/pstore.rb. Supports data of any type, - # and provides file-locking and transaction support. - # - # Custom storage types can also be created by defining a class with - # the following methods: - # - # new(session, options) - # restore # returns hash of session data. - # update - # close - # delete - # - # Changing storage type mid-session does not work. Note in particular - # that by default the FileStore and PStore session data files have the - # same name. If your application switches from one to the other without - # making sure that filenames will be different - # and clients still have old sessions lying around in cookies, then - # things will break nastily! - # - # == Maintaining the session id. - # - # Most session state is maintained on the server. However, a session - # id must be passed backwards and forwards between client and server - # to maintain a reference to this session state. - # - # The simplest way to do this is via cookies. The CGI::Session class - # provides transparent support for session id communication via cookies - # if the client has cookies enabled. - # - # If the client has cookies disabled, the session id must be included - # as a parameter of all requests sent by the client to the server. The - # CGI::Session class in conjunction with the CGI class will transparently - # add the session id as a hidden input field to all forms generated - # using the CGI#form() HTML generation method. No built-in support is - # provided for other mechanisms, such as URL re-writing. The caller is - # responsible for extracting the session id from the session_id - # attribute and manually encoding it in URLs and adding it as a hidden - # input to HTML forms created by other mechanisms. Also, session expiry - # is not automatically handled. - # - # == Examples of use - # - # === Setting the user's name - # - # require 'cgi' - # require 'cgi/session' - # require 'cgi/session/pstore' # provides CGI::Session::PStore - # - # cgi = CGI.new("html4") - # - # session = CGI::Session.new(cgi, - # 'database_manager' => CGI::Session::PStore, # use PStore - # 'session_key' => '_rb_sess_id', # custom session key - # 'session_expires' => Time.now + 30 * 60, # 30 minute timeout - # 'prefix' => 'pstore_sid_') # PStore option - # if cgi.has_key?('user_name') and cgi['user_name'] != '' - # # coerce to String: cgi[] returns the - # # string-like CGI::QueryExtension::Value - # session['user_name'] = cgi['user_name'].to_s - # elsif !session['user_name'] - # session['user_name'] = "guest" - # end - # session.close - # - # === Creating a new session safely - # - # require 'cgi' - # require 'cgi/session' - # - # cgi = CGI.new("html4") - # - # # We make sure to delete an old session if one exists, - # # not just to free resources, but to prevent the session - # # from being maliciously hijacked later on. - # begin - # session = CGI::Session.new(cgi, 'new_session' => false) - # session.delete - # rescue ArgumentError # if no old session - # end - # session = CGI::Session.new(cgi, 'new_session' => true) - # session.close - # - class Session - - class NoSession < RuntimeError #:nodoc: - end - - # The id of this session. - attr_reader :session_id, :new_session - - def Session::callback(dbman) #:nodoc: - Proc.new{ - dbman[0].close unless dbman.empty? - } - end - - # Create a new session id. - # - # 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. - def create_new_id - require 'securerandom' - begin - session_id = SecureRandom.hex(16) - rescue NotImplementedError - require 'digest/md5' - md5 = Digest::MD5::new - now = Time::now - md5.update(now.to_s) - md5.update(String(now.usec)) - md5.update(String(rand(0))) - md5.update(String($$)) - md5.update('foobar') - session_id = md5.hexdigest - end - session_id - end - private :create_new_id - - # Create a new CGI::Session object for +request+. - # - # +request+ is an instance of the +CGI+ class (see cgi.rb). - # +option+ is a hash of options for initialising this - # CGI::Session instance. The following options are - # recognised: - # - # session_key:: the parameter name used for the session id. - # Defaults to '_session_id'. - # session_id:: the session id to use. If not provided, then - # it is retrieved from the +session_key+ parameter - # of the request, or automatically generated for - # a new session. - # new_session:: if true, force creation of a new session. If not set, - # a new session is only created if none currently - # exists. If false, a new session is never created, - # and if none currently exists and the +session_id+ - # option is not set, an ArgumentError is raised. - # database_manager:: the name of the class providing storage facilities - # for session state persistence. Built-in support - # is provided for +FileStore+ (the default), - # +MemoryStore+, and +PStore+ (from - # cgi/session/pstore.rb). See the documentation for - # these classes for more details. - # - # The following options are also recognised, but only apply if the - # session id is stored in a cookie. - # - # session_expires:: the time the current session expires, as a - # +Time+ object. If not set, the session will terminate - # when the user's browser is closed. - # session_domain:: the hostname domain for which this session is valid. - # If not set, defaults to the hostname of the server. - # session_secure:: if +true+, this session will only work over HTTPS. - # session_path:: the path for which this session applies. Defaults - # to the directory of the CGI script. - # - # +option+ is also passed on to the session storage class 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. - # - # *WARNING* the +output_hidden+ - # fields are surrounded by a
tag in HTML 4 generation, which - # is _not_ invisible on many browsers; you may wish to disable the - # use of fieldsets with code similar to the following - # (see http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-list/37805) - # - # cgi = CGI.new("html4") - # class << cgi - # undef_method :fieldset - # end - # - def initialize(request, option={}) - @new_session = false - session_key = option['session_key'] || '_session_id' - session_id = option['session_id'] - unless session_id - if option['new_session'] - session_id = create_new_id - @new_session = true - end - end - unless session_id - if request.key?(session_key) - session_id = request[session_key] - session_id = session_id.read if session_id.respond_to?(:read) - end - unless session_id - session_id, = request.cookies[session_key] - end - unless session_id - unless option.fetch('new_session', true) - raise ArgumentError, "session_key `%s' should be supplied"%session_key - end - session_id = create_new_id - @new_session = true - end - end - @session_id = session_id - dbman = option['database_manager'] || FileStore - begin - @dbman = dbman::new(self, option) - rescue NoSession - unless option.fetch('new_session', true) - raise ArgumentError, "invalid session_id `%s'"%session_id - end - session_id = @session_id = create_new_id unless session_id - @new_session=true - retry - end - request.instance_eval do - @output_hidden = {session_key => session_id} unless option['no_hidden'] - @output_cookies = [ - Cookie::new("name" => session_key, - "value" => session_id, - "expires" => option['session_expires'], - "domain" => option['session_domain'], - "secure" => option['session_secure'], - "path" => - if option['session_path'] - option['session_path'] - elsif ENV["SCRIPT_NAME"] - File::dirname(ENV["SCRIPT_NAME"]) - else - "" - end) - ] unless option['no_cookies'] - end - @dbprot = [@dbman] - ObjectSpace::define_finalizer(self, Session::callback(@dbprot)) - end - - # Retrieve the session data for key +key+. - def [](key) - @data ||= @dbman.restore - @data[key] - end - - # Set the session date for key +key+. - def []=(key, val) - @write_lock ||= true - @data ||= @dbman.restore - @data[key] = val - end - - # Store session data on the server. For some session storage types, - # this is a no-op. - def update - @dbman.update - end - - # 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 - @dbprot.clear - end - - # Delete the session from storage. Also closes the storage. - # - # Note that the session's data is _not_ automatically deleted - # upon the session expiring. - def delete - @dbman.delete - @dbprot.clear - end - - # File-based session storage class. - # - # Implements session storage as a flat file of 'key=value' values. - # This storage type only works directly with String values; the - # user is responsible for converting other types to Strings when - # storing and from Strings when retrieving. - class FileStore - # Create a new FileStore instance. - # - # This constructor is used internally by CGI::Session. The - # user does not generally need to call it directly. - # - # +session+ is the session for which this instance is being - # created. The session id must only contain alphanumeric - # characters; automatically generated session ids observe - # this requirement. - # - # +option+ is a hash of options for the initializer. The - # following options are recognised: - # - # tmpdir:: the directory to use for storing the FileStore - # file. Defaults to Dir::tmpdir (generally "/tmp" - # on Unix systems). - # prefix:: the prefix to add to the session id when generating - # the filename for this session's FileStore file. - # Defaults to "cgi_sid_". - # suffix:: the prefix to add to the session id when generating - # the filename for this session's FileStore file. - # Defaults to the empty string. - # - # This session's FileStore file will be created if it does - # not exist, or opened if it does. - def initialize(session, option={}) - dir = option['tmpdir'] || Dir::tmpdir - prefix = option['prefix'] || 'cgi_sid_' - suffix = option['suffix'] || '' - id = session.session_id - require 'digest/md5' - md5 = Digest::MD5.hexdigest(id)[0,16] - @path = dir+"/"+prefix+md5+suffix - if File::exist? @path - @hash = nil - else - unless session.new_session - raise CGI::Session::NoSession, "uninitialized session" - end - @hash = {} - end - end - - # Restore session state from the session's FileStore file. - # - # Returns the session state as a hash. - def restore - unless @hash - @hash = {} - begin - lockf = File.open(@path+".lock", "r") - lockf.flock File::LOCK_SH - f = File.open(@path, 'r') - for line in f - line.chomp! - k, v = line.split('=',2) - @hash[CGI::unescape(k)] = Marshal.restore(CGI::unescape(v)) - end - ensure - f.close unless f.nil? - lockf.close if lockf - end - end - @hash - end - - # Save session state to the session's FileStore file. - def update - return unless @hash - begin - lockf = File.open(@path+".lock", File::CREAT|File::RDWR, 0600) - lockf.flock File::LOCK_EX - f = File.open(@path+".new", File::CREAT|File::TRUNC|File::WRONLY, 0600) - for k,v in @hash - f.printf "%s=%s\n", CGI::escape(k), CGI::escape(String(Marshal.dump(v))) - end - f.close - File.rename @path+".new", @path - ensure - f.close if f and !f.closed? - lockf.close if lockf - end - end - - # Update and close the session's FileStore file. - def close - update - end - - # Close and delete the session's FileStore file. - def delete - File::unlink @path+".lock" rescue nil - File::unlink @path+".new" rescue nil - File::unlink @path rescue Errno::ENOENT - end - end - - # In-memory session storage class. - # - # Implements session storage as a global in-memory hash. Session - # data will only persist for as long as the ruby interpreter - # instance does. - class MemoryStore - GLOBAL_HASH_TABLE = {} #:nodoc: - - # Create a new MemoryStore instance. - # - # +session+ is the session this instance is associated with. - # +option+ is a list of initialisation options. None are - # currently recognised. - def initialize(session, option=nil) - @session_id = session.session_id - unless GLOBAL_HASH_TABLE.key?(@session_id) - unless session.new_session - raise CGI::Session::NoSession, "uninitialized session" - end - GLOBAL_HASH_TABLE[@session_id] = {} - end - end - - # Restore session state. - # - # Returns session data as a hash. - def restore - GLOBAL_HASH_TABLE[@session_id] - end - - # Update session state. - # - # A no-op. - def update - # don't need to update; hash is shared - end - - # Close session storage. - # - # A no-op. - def close - # don't need to close - end - - # Delete the session state. - def delete - GLOBAL_HASH_TABLE.delete(@session_id) - end - end - - # Dummy session storage class. - # - # Implements session storage place holder. No actual storage - # will be done. - class NullStore - # Create a new NullStore instance. - # - # +session+ is the session this instance is associated with. - # +option+ is a list of initialisation options. None are - # currently recognised. - def initialize(session, option=nil) - end - - # Restore (empty) session state. - def restore - {} - end - - # Update session state. - # - # A no-op. - def update - end - - # Close session storage. - # - # A no-op. - def close - end - - # Delete the session state. - # - # A no-op. - def delete - end - end - end -end diff --git a/Src/StdLib/ruby/1.9.1/cgi/session/pstore.rb b/Src/StdLib/ruby/1.9.1/cgi/session/pstore.rb deleted file mode 100644 index 25f2c38f9..000000000 --- a/Src/StdLib/ruby/1.9.1/cgi/session/pstore.rb +++ /dev/null @@ -1,110 +0,0 @@ -# -# cgi/session/pstore.rb - persistent storage of marshalled session data -# -# Documentation: William Webber (william@williamwebber.com) -# -# == Overview -# -# This file provides the CGI::Session::PStore class, which builds -# persistent of session data on top of the pstore library. See -# cgi/session.rb for more details on session storage managers. - -require 'cgi/session' -require 'pstore' - -class CGI - class Session - # PStore-based session storage class. - # - # This builds upon the top-level PStore class provided by the - # library file pstore.rb. Session data is marshalled and stored - # in a file. File locking and transaction services are provided. - class PStore - # Create a new CGI::Session::PStore instance - # - # This constructor is used internally by CGI::Session. The - # user does not generally need to call it directly. - # - # +session+ is the session for which this instance is being - # created. The session id must only contain alphanumeric - # characters; automatically generated session ids observe - # this requirement. - # - # +option+ is a hash of options for the initializer. The - # following options are recognised: - # - # tmpdir:: the directory to use for storing the PStore - # file. Defaults to Dir::tmpdir (generally "/tmp" - # on Unix systems). - # prefix:: the prefix to add to the session id when generating - # the filename for this session's PStore file. - # Defaults to the empty string. - # - # This session's PStore file will be created if it does - # not exist, or opened if it does. - def initialize(session, option={}) - dir = option['tmpdir'] || Dir::tmpdir - prefix = option['prefix'] || '' - id = session.session_id - require 'digest/md5' - md5 = Digest::MD5.hexdigest(id)[0,16] - path = dir+"/"+prefix+md5 - if File::exist?(path) - @hash = nil - else - unless session.new_session - raise CGI::Session::NoSession, "uninitialized session" - end - @hash = {} - end - @p = ::PStore.new(path) - @p.transaction do |p| - File.chmod(0600, p.path) - end - end - - # Restore session state from the session's PStore file. - # - # Returns the session state as a hash. - def restore - unless @hash - @p.transaction do - @hash = @p['hash'] || {} - end - end - @hash - end - - # Save session state to the session's PStore file. - def update - @p.transaction do - @p['hash'] = @hash - end - end - - # Update and close the session's PStore file. - def close - update - end - - # Close and delete the session's PStore file. - def delete - path = @p.path - File::unlink path - end - - end - end -end - -if $0 == __FILE__ - # :enddoc: - STDIN.reopen("/dev/null") - cgi = CGI.new - session = CGI::Session.new(cgi, 'database_manager' => CGI::Session::PStore) - session['key'] = {'k' => 'v'} - puts session['key'].class - fail unless Hash === session['key'] - puts session['key'].inspect - fail unless session['key'].inspect == '{"k"=>"v"}' -end diff --git a/Src/StdLib/ruby/1.9.1/cmath.rb b/Src/StdLib/ruby/1.9.1/cmath.rb deleted file mode 100644 index 6909b20b7..000000000 --- a/Src/StdLib/ruby/1.9.1/cmath.rb +++ /dev/null @@ -1,254 +0,0 @@ -module CMath - - include Math - - alias exp! exp - alias log! log - alias log2! log2 - alias log10! log10 - alias sqrt! sqrt - alias cbrt! cbrt - - alias sin! sin - alias cos! cos - alias tan! tan - - alias sinh! sinh - alias cosh! cosh - alias tanh! tanh - - alias asin! asin - alias acos! acos - alias atan! atan - alias atan2! atan2 - - alias asinh! asinh - alias acosh! acosh - alias atanh! atanh - - def exp(z) - if z.real? - exp!(z) - else - ere = exp!(z.real) - Complex(ere * cos!(z.imag), - ere * sin!(z.imag)) - end - end - - def log(*args) - z, b = args - if z.real? and z >= 0 and (b.nil? or b >= 0) - log!(*args) - else - a = Complex(log!(z.abs), z.arg) - if b - a /= log(b) - end - a - end - end - - def log2(z) - if z.real? and z >= 0 - log2!(z) - else - log(z) / log!(2) - end - end - - def log10(z) - if z.real? and z >= 0 - log10!(z) - else - log(z) / log!(10) - end - end - - def sqrt(z) - if z.real? - if z < 0 - Complex(0, sqrt!(-z)) - else - sqrt!(z) - end - else - if z.imag < 0 || - (z.imag == 0 && z.imag.to_s[0] == '-') - sqrt(z.conjugate).conjugate - else - r = z.abs - x = z.real - Complex(sqrt!((r + x) / 2), sqrt!((r - x) / 2)) - end - end - end - - def cbrt(z) - if z.real? - cbrt!(z) - else - Complex(z) ** (1.0/3) - end - end - - def sin(z) - if z.real? - sin!(z) - else - Complex(sin!(z.real) * cosh!(z.imag), - cos!(z.real) * sinh!(z.imag)) - end - end - - def cos(z) - if z.real? - cos!(z) - else - Complex(cos!(z.real) * cosh!(z.imag), - -sin!(z.real) * sinh!(z.imag)) - end - end - - def tan(z) - if z.real? - tan!(z) - else - sin(z) / cos(z) - end - end - - def sinh(z) - if z.real? - sinh!(z) - else - Complex(sinh!(z.real) * cos!(z.imag), - cosh!(z.real) * sin!(z.imag)) - end - end - - def cosh(z) - if z.real? - cosh!(z) - else - Complex(cosh!(z.real) * cos!(z.imag), - sinh!(z.real) * sin!(z.imag)) - end - end - - def tanh(z) - if z.real? - tanh!(z) - else - sinh(z) / cosh(z) - end - end - - def asin(z) - if z.real? and z >= -1 and z <= 1 - asin!(z) - else - (-1.0).i * log(1.0.i * z + sqrt(1.0 - z * z)) - end - end - - def acos(z) - if z.real? and z >= -1 and z <= 1 - acos!(z) - else - (-1.0).i * log(z + 1.0.i * sqrt(1.0 - z * z)) - end - end - - def atan(z) - if z.real? - atan!(z) - else - 1.0.i * log((1.0.i + z) / (1.0.i - z)) / 2.0 - end - end - - def atan2(y,x) - if y.real? and x.real? - atan2!(y,x) - else - (-1.0).i * log((x + 1.0.i * y) / sqrt(x * x + y * y)) - end - end - - def asinh(z) - if z.real? - asinh!(z) - else - log(z + sqrt(1.0 + z * z)) - end - end - - def acosh(z) - if z.real? and z >= 1 - acosh!(z) - else - log(z + sqrt(z * z - 1.0)) - end - end - - def atanh(z) - if z.real? and z >= -1 and z <= 1 - atanh!(z) - else - log((1.0 + z) / (1.0 - z)) / 2.0 - end - end - - module_function :exp! - module_function :exp - module_function :log! - module_function :log - module_function :log2! - module_function :log2 - module_function :log10! - module_function :log10 - module_function :sqrt! - module_function :sqrt - module_function :cbrt! - module_function :cbrt - - module_function :sin! - module_function :sin - module_function :cos! - module_function :cos - module_function :tan! - module_function :tan - - module_function :sinh! - module_function :sinh - module_function :cosh! - module_function :cosh - module_function :tanh! - module_function :tanh - - module_function :asin! - module_function :asin - module_function :acos! - module_function :acos - module_function :atan! - module_function :atan - module_function :atan2! - module_function :atan2 - - module_function :asinh! - module_function :asinh - module_function :acosh! - module_function :acosh - module_function :atanh! - module_function :atanh - - module_function :frexp - module_function :ldexp - module_function :hypot - module_function :erf - module_function :erfc - module_function :gamma - module_function :lgamma - -end diff --git a/Src/StdLib/ruby/1.9.1/complex.rb b/Src/StdLib/ruby/1.9.1/complex.rb deleted file mode 100644 index f5dcb0e49..000000000 --- a/Src/StdLib/ruby/1.9.1/complex.rb +++ /dev/null @@ -1,28 +0,0 @@ -# :enddoc: - -warn('lib/complex.rb is deprecated') if $VERBOSE - -require 'cmath' - -unless defined?(Math.exp!) - Object.instance_eval{remove_const :Math} - Math = CMath -end - -def Complex.generic? (other) - other.kind_of?(Integer) || - other.kind_of?(Float) || - other.kind_of?(Rational) -end - -class Complex - - alias image imag - -end - -class Numeric - - def im() Complex(0, self) end - -end diff --git a/Src/StdLib/ruby/1.9.1/debug.rb b/Src/StdLib/ruby/1.9.1/debug.rb deleted file mode 100644 index 4ca027d7d..000000000 --- a/Src/StdLib/ruby/1.9.1/debug.rb +++ /dev/null @@ -1,907 +0,0 @@ -# Copyright (C) 2000 Network Applied Communication Laboratory, Inc. -# Copyright (C) 2000 Information-technology Promotion Agency, Japan -# Copyright (C) 2000-2003 NAKAMURA, Hiroshi - -require 'continuation' - -if $SAFE > 0 - STDERR.print "-r debug.rb is not available in safe mode\n" - exit 1 -end - -require 'tracer' -require 'pp' - -class Tracer - def Tracer.trace_func(*vars) - Single.trace_func(*vars) - end -end - -SCRIPT_LINES__ = {} unless defined? SCRIPT_LINES__ - -class DEBUGGER__ -MUTEX = Mutex.new - -class Context - DEBUG_LAST_CMD = [] - - begin - require 'readline' - def readline(prompt, hist) - Readline::readline(prompt, hist) - end - rescue LoadError - def readline(prompt, hist) - STDOUT.print prompt - STDOUT.flush - line = STDIN.gets - exit unless line - line.chomp! - line - end - USE_READLINE = false - end - - def initialize - if Thread.current == Thread.main - @stop_next = 1 - else - @stop_next = 0 - end - @last_file = nil - @file = nil - @line = nil - @no_step = nil - @frames = [] - @finish_pos = 0 - @trace = false - @catch = "StandardError" - @suspend_next = false - end - - def stop_next(n=1) - @stop_next = n - end - - def set_suspend - @suspend_next = true - end - - def clear_suspend - @suspend_next = false - end - - def suspend_all - DEBUGGER__.suspend - end - - def resume_all - DEBUGGER__.resume - end - - def check_suspend - while MUTEX.synchronize { - if @suspend_next - DEBUGGER__.waiting.push Thread.current - @suspend_next = false - true - end - } - end - end - - def trace? - @trace - end - - def set_trace(arg) - @trace = arg - end - - def stdout - DEBUGGER__.stdout - end - - def break_points - DEBUGGER__.break_points - end - - def display - DEBUGGER__.display - end - - def context(th) - DEBUGGER__.context(th) - end - - def set_trace_all(arg) - DEBUGGER__.set_trace(arg) - end - - def set_last_thread(th) - DEBUGGER__.set_last_thread(th) - end - - def debug_eval(str, binding) - begin - val = eval(str, binding) - rescue StandardError, ScriptError => e - at = eval("caller(1)", binding) - stdout.printf "%s:%s\n", at.shift, e.to_s.sub(/\(eval\):1:(in `.*?':)?/, '') - for i in at - stdout.printf "\tfrom %s\n", i - end - throw :debug_error - end - end - - def debug_silent_eval(str, binding) - begin - eval(str, binding) - rescue StandardError, ScriptError - nil - end - end - - def var_list(ary, binding) - ary.sort! - for v in ary - stdout.printf " %s => %s\n", v, eval(v, binding).inspect - end - end - - def debug_variable_info(input, binding) - case input - when /^\s*g(?:lobal)?\s*$/ - var_list(global_variables, binding) - - when /^\s*l(?:ocal)?\s*$/ - var_list(eval("local_variables", binding), binding) - - when /^\s*i(?:nstance)?\s+/ - obj = debug_eval($', binding) - var_list(obj.instance_variables, obj.instance_eval{binding()}) - - when /^\s*c(?:onst(?:ant)?)?\s+/ - obj = debug_eval($', binding) - unless obj.kind_of? Module - stdout.print "Should be Class/Module: ", $', "\n" - else - var_list(obj.constants, obj.module_eval{binding()}) - end - end - end - - def debug_method_info(input, binding) - case input - when /^i(:?nstance)?\s+/ - obj = debug_eval($', binding) - - len = 0 - for v in obj.methods.sort - len += v.size + 1 - if len > 70 - len = v.size + 1 - stdout.print "\n" - end - stdout.print v, " " - end - stdout.print "\n" - - else - obj = debug_eval(input, binding) - unless obj.kind_of? Module - stdout.print "Should be Class/Module: ", input, "\n" - else - len = 0 - for v in obj.instance_methods(false).sort - len += v.size + 1 - if len > 70 - len = v.size + 1 - stdout.print "\n" - end - stdout.print v, " " - end - stdout.print "\n" - end - end - end - - def thnum - num = DEBUGGER__.instance_eval{@thread_list[Thread.current]} - unless num - DEBUGGER__.make_thread_list - num = DEBUGGER__.instance_eval{@thread_list[Thread.current]} - end - num - end - - def debug_command(file, line, id, binding) - MUTEX.lock - unless defined?($debugger_restart) and $debugger_restart - callcc{|c| $debugger_restart = c} - end - set_last_thread(Thread.current) - frame_pos = 0 - binding_file = file - binding_line = line - previous_line = nil - if ENV['EMACS'] - stdout.printf "\032\032%s:%d:\n", binding_file, binding_line - else - stdout.printf "%s:%d:%s", binding_file, binding_line, - line_at(binding_file, binding_line) - end - @frames[0] = [binding, file, line, id] - display_expressions(binding) - prompt = true - while prompt and input = readline("(rdb:%d) "%thnum(), true) - catch(:debug_error) do - if input == "" - next unless DEBUG_LAST_CMD[0] - input = DEBUG_LAST_CMD[0] - stdout.print input, "\n" - else - DEBUG_LAST_CMD[0] = input - end - - case input - when /^\s*tr(?:ace)?(?:\s+(on|off))?(?:\s+(all))?$/ - if defined?( $2 ) - if $1 == 'on' - set_trace_all true - else - set_trace_all false - end - elsif defined?( $1 ) - if $1 == 'on' - set_trace true - else - set_trace false - end - end - if trace? - stdout.print "Trace on.\n" - else - stdout.print "Trace off.\n" - end - - when /^\s*b(?:reak)?\s+(?:(.+):)?([^.:]+)$/ - pos = $2 - if $1 - klass = debug_silent_eval($1, binding) - file = $1 - end - if pos =~ /^\d+$/ - pname = pos - pos = pos.to_i - else - pname = pos = pos.intern.id2name - end - break_points.push [true, 0, klass || file, pos] - stdout.printf "Set breakpoint %d at %s:%s\n", break_points.size, klass || file, pname - - when /^\s*b(?:reak)?\s+(.+)[#.]([^.:]+)$/ - pos = $2.intern.id2name - klass = debug_eval($1, binding) - break_points.push [true, 0, klass, pos] - stdout.printf "Set breakpoint %d at %s.%s\n", break_points.size, klass, pos - - when /^\s*wat(?:ch)?\s+(.+)$/ - exp = $1 - break_points.push [true, 1, exp] - stdout.printf "Set watchpoint %d:%s\n", break_points.size, exp - - when /^\s*b(?:reak)?$/ - if break_points.find{|b| b[1] == 0} - n = 1 - stdout.print "Breakpoints:\n" - break_points.each do |b| - if b[0] and b[1] == 0 - stdout.printf " %d %s:%s\n", n, b[2], b[3] - end - n += 1 - end - end - if break_points.find{|b| b[1] == 1} - n = 1 - stdout.print "\n" - stdout.print "Watchpoints:\n" - for b in break_points - if b[0] and b[1] == 1 - stdout.printf " %d %s\n", n, b[2] - end - n += 1 - end - end - if break_points.size == 0 - stdout.print "No breakpoints\n" - else - stdout.print "\n" - end - - when /^\s*del(?:ete)?(?:\s+(\d+))?$/ - pos = $1 - unless pos - input = readline("Clear all breakpoints? (y/n) ", false) - if input == "y" - for b in break_points - b[0] = false - end - end - else - pos = pos.to_i - if break_points[pos-1] - break_points[pos-1][0] = false - else - stdout.printf "Breakpoint %d is not defined\n", pos - end - end - - when /^\s*disp(?:lay)?\s+(.+)$/ - exp = $1 - display.push [true, exp] - stdout.printf "%d: ", display.size - display_expression(exp, binding) - - when /^\s*disp(?:lay)?$/ - display_expressions(binding) - - when /^\s*undisp(?:lay)?(?:\s+(\d+))?$/ - pos = $1 - unless pos - input = readline("Clear all expressions? (y/n) ", false) - if input == "y" - for d in display - d[0] = false - end - end - else - pos = pos.to_i - if display[pos-1] - display[pos-1][0] = false - else - stdout.printf "Display expression %d is not defined\n", pos - end - end - - when /^\s*c(?:ont)?$/ - prompt = false - - when /^\s*s(?:tep)?(?:\s+(\d+))?$/ - if $1 - lev = $1.to_i - else - lev = 1 - end - @stop_next = lev - prompt = false - - when /^\s*n(?:ext)?(?:\s+(\d+))?$/ - if $1 - lev = $1.to_i - else - lev = 1 - end - @stop_next = lev - @no_step = @frames.size - frame_pos - prompt = false - - when /^\s*w(?:here)?$/, /^\s*f(?:rame)?$/ - display_frames(frame_pos) - - when /^\s*l(?:ist)?(?:\s+(.+))?$/ - if not $1 - b = previous_line ? previous_line + 10 : binding_line - 5 - e = b + 9 - elsif $1 == '-' - b = previous_line ? previous_line - 10 : binding_line - 5 - e = b + 9 - else - b, e = $1.split(/[-,]/) - if e - b = b.to_i - e = e.to_i - else - b = b.to_i - 5 - e = b + 9 - end - end - previous_line = b - display_list(b, e, binding_file, binding_line) - - when /^\s*up(?:\s+(\d+))?$/ - previous_line = nil - if $1 - lev = $1.to_i - else - lev = 1 - end - frame_pos += lev - if frame_pos >= @frames.size - frame_pos = @frames.size - 1 - stdout.print "At toplevel\n" - end - binding, binding_file, binding_line = @frames[frame_pos] - stdout.print format_frame(frame_pos) - - when /^\s*down(?:\s+(\d+))?$/ - previous_line = nil - if $1 - lev = $1.to_i - else - lev = 1 - end - frame_pos -= lev - if frame_pos < 0 - frame_pos = 0 - stdout.print "At stack bottom\n" - end - binding, binding_file, binding_line = @frames[frame_pos] - stdout.print format_frame(frame_pos) - - when /^\s*fin(?:ish)?$/ - if frame_pos == @frames.size - stdout.print "\"finish\" not meaningful in the outermost frame.\n" - else - @finish_pos = @frames.size - frame_pos - frame_pos = 0 - prompt = false - end - - when /^\s*cat(?:ch)?(?:\s+(.+))?$/ - if $1 - excn = $1 - if excn == 'off' - @catch = nil - stdout.print "Clear catchpoint.\n" - else - @catch = excn - stdout.printf "Set catchpoint %s.\n", @catch - end - else - if @catch - stdout.printf "Catchpoint %s.\n", @catch - else - stdout.print "No catchpoint.\n" - end - end - - when /^\s*q(?:uit)?$/ - input = readline("Really quit? (y/n) ", false) - if input == "y" - exit! # exit -> exit!: No graceful way to stop threads... - end - - when /^\s*v(?:ar)?\s+/ - debug_variable_info($', binding) - - when /^\s*m(?:ethod)?\s+/ - debug_method_info($', binding) - - when /^\s*th(?:read)?\s+/ - if DEBUGGER__.debug_thread_info($', binding) == :cont - prompt = false - end - - when /^\s*pp\s+/ - PP.pp(debug_eval($', binding), stdout) - - when /^\s*p\s+/ - stdout.printf "%s\n", debug_eval($', binding).inspect - - when /^\s*r(?:estart)?$/ - $debugger_restart.call - - when /^\s*h(?:elp)?$/ - debug_print_help() - - else - v = debug_eval(input, binding) - stdout.printf "%s\n", v.inspect - end - end - end - MUTEX.unlock - resume_all - end - - def debug_print_help - stdout.print < - b[reak] [class.] - set breakpoint to some position - wat[ch] set watchpoint to some expression - cat[ch] (|off) set catchpoint to an exception - b[reak] list breakpoints - cat[ch] show catchpoint - del[ete][ nnn] delete some or all breakpoints - disp[lay] add expression into display expression list - undisp[lay][ nnn] delete one particular or all display expressions - c[ont] run until program ends or hit breakpoint - s[tep][ nnn] step (into methods) one line or till line nnn - n[ext][ nnn] go over one line or till line nnn - w[here] display frames - f[rame] alias for where - l[ist][ (-|nn-mm)] list program, - lists backwards - nn-mm lists given lines - up[ nn] move to higher frame - down[ nn] move to lower frame - fin[ish] return to outer frame - tr[ace] (on|off) set trace mode of current thread - tr[ace] (on|off) all set trace mode of all threads - q[uit] exit from debugger - v[ar] g[lobal] show global variables - v[ar] l[ocal] show local variables - v[ar] i[nstance] show instance variables of object - v[ar] c[onst] show constants of object - m[ethod] i[nstance] show methods of object - m[ethod] show instance methods of class or module - th[read] l[ist] list all threads - th[read] c[ur[rent]] show current thread - th[read] [sw[itch]] switch thread context to nnn - th[read] stop stop thread nnn - th[read] resume resume thread nnn - p expression evaluate expression and print its value - h[elp] print this help - evaluate -EOHELP - end - - def display_expressions(binding) - n = 1 - for d in display - if d[0] - stdout.printf "%d: ", n - display_expression(d[1], binding) - end - n += 1 - end - end - - def display_expression(exp, binding) - stdout.printf "%s = %s\n", exp, debug_silent_eval(exp, binding).to_s - end - - def frame_set_pos(file, line) - if @frames[0] - @frames[0][1] = file - @frames[0][2] = line - end - end - - def display_frames(pos) - 0.upto(@frames.size - 1) do |n| - if n == pos - stdout.print "--> " - else - stdout.print " " - end - stdout.print format_frame(n) - end - end - - def format_frame(pos) - bind, file, line, id = @frames[pos] - sprintf "#%d %s:%s%s\n", pos + 1, file, line, - (id ? ":in `#{id.id2name}'" : "") - end - - def display_list(b, e, file, line) - stdout.printf "[%d, %d] in %s\n", b, e, file - if lines = SCRIPT_LINES__[file] and lines != true - b.upto(e) do |n| - if n > 0 && lines[n-1] - if n == line - stdout.printf "=> %d %s\n", n, lines[n-1].chomp - else - stdout.printf " %d %s\n", n, lines[n-1].chomp - end - end - end - else - stdout.printf "No sourcefile available for %s\n", file - end - end - - def line_at(file, line) - lines = SCRIPT_LINES__[file] - if lines - return "\n" if lines == true - line = lines[line-1] - return "\n" unless line - return line - end - return "\n" - end - - def debug_funcname(id) - if id.nil? - "toplevel" - else - id.id2name - end - end - - def check_break_points(file, klass, pos, binding, id) - return false if break_points.empty? - n = 1 - for b in break_points - if b[0] # valid - if b[1] == 0 # breakpoint - if (b[2] == file and b[3] == pos) or - (klass and b[2] == klass and b[3] == pos) - stdout.printf "Breakpoint %d, %s at %s:%s\n", n, debug_funcname(id), file, pos - return true - end - elsif b[1] == 1 # watchpoint - if debug_silent_eval(b[2], binding) - stdout.printf "Watchpoint %d, %s at %s:%s\n", n, debug_funcname(id), file, pos - return true - end - end - end - n += 1 - end - return false - end - - def excn_handle(file, line, id, binding) - if $!.class <= SystemExit - set_trace_func nil - exit - end - - if @catch and ($!.class.ancestors.find { |e| e.to_s == @catch }) - stdout.printf "%s:%d: `%s' (%s)\n", file, line, $!, $!.class - fs = @frames.size - tb = caller(0)[-fs..-1] - if tb - for i in tb - stdout.printf "\tfrom %s\n", i - end - end - suspend_all - debug_command(file, line, id, binding) - end - end - - def trace_func(event, file, line, id, binding, klass) - Tracer.trace_func(event, file, line, id, binding, klass) if trace? - context(Thread.current).check_suspend - @file = file - @line = line - case event - when 'line' - frame_set_pos(file, line) - if !@no_step or @frames.size == @no_step - @stop_next -= 1 - @stop_next = -1 if @stop_next < 0 - elsif @frames.size < @no_step - @stop_next = 0 # break here before leaving... - else - # nothing to do. skipped. - end - if @stop_next == 0 or check_break_points(file, nil, line, binding, id) - @no_step = nil - suspend_all - debug_command(file, line, id, binding) - end - - when 'call' - @frames.unshift [binding, file, line, id] - if check_break_points(file, klass, id.id2name, binding, id) - suspend_all - debug_command(file, line, id, binding) - end - - when 'c-call' - frame_set_pos(file, line) - - when 'class' - @frames.unshift [binding, file, line, id] - - when 'return', 'end' - if @frames.size == @finish_pos - @stop_next = 1 - @finish_pos = 0 - end - @frames.shift - - when 'raise' - excn_handle(file, line, id, binding) - - end - @last_file = file - end -end - -trap("INT") { DEBUGGER__.interrupt } -@last_thread = Thread::main -@max_thread = 1 -@thread_list = {Thread::main => 1} -@break_points = [] -@display = [] -@waiting = [] -@stdout = STDOUT - -class << DEBUGGER__ - def stdout - @stdout - end - - def stdout=(s) - @stdout = s - end - - def display - @display - end - - def break_points - @break_points - end - - def waiting - @waiting - end - - def set_trace( arg ) - MUTEX.synchronize do - make_thread_list - for th, in @thread_list - context(th).set_trace arg - end - end - arg - end - - def set_last_thread(th) - @last_thread = th - end - - def suspend - MUTEX.synchronize do - make_thread_list - for th, in @thread_list - next if th == Thread.current - context(th).set_suspend - end - end - # Schedule other threads to suspend as soon as possible. - Thread.pass - end - - def resume - MUTEX.synchronize do - make_thread_list - @thread_list.each do |th,| - next if th == Thread.current - context(th).clear_suspend - end - waiting.each do |th| - th.run - end - waiting.clear - end - # Schedule other threads to restart as soon as possible. - Thread.pass - end - - def context(thread=Thread.current) - c = thread[:__debugger_data__] - unless c - thread[:__debugger_data__] = c = Context.new - end - c - end - - def interrupt - context(@last_thread).stop_next - end - - def get_thread(num) - th = @thread_list.key(num) - unless th - @stdout.print "No thread ##{num}\n" - throw :debug_error - end - th - end - - def thread_list(num) - th = get_thread(num) - if th == Thread.current - @stdout.print "+" - else - @stdout.print " " - end - @stdout.printf "%d ", num - @stdout.print th.inspect, "\t" - file = context(th).instance_eval{@file} - if file - @stdout.print file,":",context(th).instance_eval{@line} - end - @stdout.print "\n" - end - - def thread_list_all - for th in @thread_list.values.sort - thread_list(th) - end - end - - def make_thread_list - hash = {} - for th in Thread::list - if @thread_list.key? th - hash[th] = @thread_list[th] - else - @max_thread += 1 - hash[th] = @max_thread - end - end - @thread_list = hash - end - - def debug_thread_info(input, binding) - case input - when /^l(?:ist)?/ - make_thread_list - thread_list_all - - when /^c(?:ur(?:rent)?)?$/ - make_thread_list - thread_list(@thread_list[Thread.current]) - - when /^(?:sw(?:itch)?\s+)?(\d+)/ - make_thread_list - th = get_thread($1.to_i) - if th == Thread.current - @stdout.print "It's the current thread.\n" - else - thread_list(@thread_list[th]) - context(th).stop_next - th.run - return :cont - end - - when /^stop\s+(\d+)/ - make_thread_list - th = get_thread($1.to_i) - if th == Thread.current - @stdout.print "It's the current thread.\n" - elsif th.stop? - @stdout.print "Already stopped.\n" - else - thread_list(@thread_list[th]) - context(th).suspend - end - - when /^resume\s+(\d+)/ - make_thread_list - th = get_thread($1.to_i) - if th == Thread.current - @stdout.print "It's the current thread.\n" - elsif !th.stop? - @stdout.print "Already running." - else - thread_list(@thread_list[th]) - th.run - end - end - end -end - -stdout.printf "Debug.rb\n" -stdout.printf "Emacs support available.\n\n" -RubyVM::InstructionSequence.compile_option = { - trace_instruction: true -} -set_trace_func proc { |event, file, line, id, binding, klass, *rest| - DEBUGGER__.context.trace_func event, file, line, id, binding, klass -} -end diff --git a/Src/StdLib/ruby/1.9.1/dl.rb b/Src/StdLib/ruby/1.9.1/dl.rb deleted file mode 100644 index d22fe8173..000000000 --- a/Src/StdLib/ruby/1.9.1/dl.rb +++ /dev/null @@ -1,12 +0,0 @@ -require 'dl.so' - -begin - require 'fiddle' unless Object.const_defined?(:Fiddle) -rescue LoadError -end - -module DL - def self.fiddle? - Object.const_defined?(:Fiddle) - end -end diff --git a/Src/StdLib/ruby/1.9.1/dl/callback.rb b/Src/StdLib/ruby/1.9.1/dl/callback.rb deleted file mode 100644 index aa7ae0327..000000000 --- a/Src/StdLib/ruby/1.9.1/dl/callback.rb +++ /dev/null @@ -1,96 +0,0 @@ -require 'dl' -require 'thread' - -module DL - SEM = Mutex.new - - if DL.fiddle? - CdeclCallbackProcs = {} - CdeclCallbackAddrs = {} - StdcallCallbackProcs = {} - StdcallCallbackAddrs = {} - end - - def set_callback_internal(proc_entry, addr_entry, argc, ty, abi = nil, &cbp) - if( argc < 0 ) - raise(ArgumentError, "arity should not be less than 0.") - end - addr = nil - - if DL.fiddle? - abi ||= Fiddle::Function::DEFAULT - closure = Fiddle::Closure::BlockCaller.new(ty, [TYPE_VOIDP] * argc, abi, &cbp) - proc_entry[closure.to_i] = closure - addr = closure.to_i - else - SEM.synchronize{ - ary = proc_entry[ty] - (0...MAX_CALLBACK).each{|n| - idx = (n * DLSTACK_SIZE) + argc - if( ary[idx].nil? ) - ary[idx] = cbp - addr = addr_entry[ty][idx] - break - end - } - } - end - - addr - end - - def set_cdecl_callback(ty, argc, &cbp) - set_callback_internal(CdeclCallbackProcs, CdeclCallbackAddrs, argc, ty, &cbp) - end - - def set_stdcall_callback(ty, argc, &cbp) - if DL.fiddle? - set_callback_internal(StdcallCallbackProcs, StdcallCallbackAddrs, argc, ty, Fiddle::Function::STDCALL, &cbp) - else - set_callback_internal(StdcallCallbackProcs, StdcallCallbackAddrs, argc, ty, &cbp) - end - end - - def remove_callback_internal(proc_entry, addr_entry, addr, ctype = nil) - if DL.fiddle? - addr = addr.to_i - return false unless proc_entry.key?(addr) - proc_entry.delete(addr) - true - else - index = nil - if( ctype ) - addr_entry[ctype].each_with_index{|xaddr, idx| - if( xaddr == addr ) - index = idx - end - } - else - addr_entry.each{|ty,entry| - entry.each_with_index{|xaddr, idx| - if( xaddr == addr ) - index = idx - end - } - } - end - if( index and proc_entry[ctype][index] ) - proc_entry[ctype][index] = nil - return true - else - return false - end - end - end - - def remove_cdecl_callback(addr, ctype = nil) - remove_callback_internal(CdeclCallbackProcs, CdeclCallbackAddrs, addr, ctype) - end - - def remove_stdcall_callback(addr, ctype = nil) - remove_callback_internal(StdcallCallbackProcs, StdcallCallbackAddrs, addr, ctype) - end - - alias set_callback set_cdecl_callback - alias remove_callback remove_cdecl_callback -end diff --git a/Src/StdLib/ruby/1.9.1/dl/cparser.rb b/Src/StdLib/ruby/1.9.1/dl/cparser.rb deleted file mode 100644 index 76ddbd456..000000000 --- a/Src/StdLib/ruby/1.9.1/dl/cparser.rb +++ /dev/null @@ -1,109 +0,0 @@ -module DL - module CParser - def parse_struct_signature(signature, tymap=nil) - if( signature.is_a?(String) ) - signature = signature.split(/\s*,\s*/) - end - mems = [] - tys = [] - signature.each{|msig| - tks = msig.split(/\s+(\*)?/) - ty = tks[0..-2].join(" ") - member = tks[-1] - - case ty - when /\[(\d+)\]/ - n = $1.to_i - ty.gsub!(/\s*\[\d+\]/,"") - ty = [ty, n] - when /\[\]/ - ty.gsub!(/\s*\[\]/, "*") - end - - case member - when /\[(\d+)\]/ - ty = [ty, $1.to_i] - member.gsub!(/\s*\[\d+\]/,"") - when /\[\]/ - ty = ty + "*" - member.gsub!(/\s*\[\]/, "") - end - - mems.push(member) - tys.push(parse_ctype(ty,tymap)) - } - return tys, mems - end - - def parse_signature(signature, tymap=nil) - tymap ||= {} - signature = signature.gsub(/\s+/, " ").strip - case signature - when /^([\w@\*\s]+)\(([\w\*\s\,\[\]]*)\)$/ - ret = $1 - (args = $2).strip! - ret = ret.split(/\s+/) - args = args.split(/\s*,\s*/) - func = ret.pop - if( func =~ /^\*/ ) - func.gsub!(/^\*+/,"") - ret.push("*") - end - ret = ret.join(" ") - return [func, parse_ctype(ret, tymap), args.collect{|arg| parse_ctype(arg, tymap)}] - else - raise(RuntimeError,"can't parse the function prototype: #{signature}") - end - end - - def parse_ctype(ty, tymap=nil) - tymap ||= {} - case ty - when Array - return [parse_ctype(ty[0], tymap), ty[1]] - when "void" - return TYPE_VOID - when "char" - return TYPE_CHAR - when "unsigned char" - return -TYPE_CHAR - when "short" - return TYPE_SHORT - when "unsigned short" - return -TYPE_SHORT - when "int" - return TYPE_INT - when "unsigned int", 'uint' - return -TYPE_INT - when "long" - return TYPE_LONG - when "unsigned long" - return -TYPE_LONG - when "long long" - if( defined?(TYPE_LONG_LONG) ) - return TYPE_LONG_LONG - else - raise(RuntimeError, "unsupported type: #{ty}") - end - when "unsigned long long" - if( defined?(TYPE_LONG_LONG) ) - return -TYPE_LONG_LONG - else - raise(RuntimeError, "unsupported type: #{ty}") - end - when "float" - return TYPE_FLOAT - when "double" - return TYPE_DOUBLE - when /\*/, /\[\s*\]/ - return TYPE_VOIDP - else - if( tymap[ty] ) - return parse_ctype(tymap[ty], tymap) - else - raise(DLError, "unknown type: #{ty}") - end - end - end - end -end diff --git a/Src/StdLib/ruby/1.9.1/dl/func.rb b/Src/StdLib/ruby/1.9.1/dl/func.rb deleted file mode 100644 index 0bf0a1717..000000000 --- a/Src/StdLib/ruby/1.9.1/dl/func.rb +++ /dev/null @@ -1,187 +0,0 @@ -require 'dl' -require 'dl/callback' -require 'dl/stack' -require 'dl/value' -require 'thread' - -module DL - parent = DL.fiddle? ? Fiddle::Function : Object - - class Function < parent - include DL - include ValueUtil - - def initialize cfunc, argtypes, abi = nil, &block - if DL.fiddle? - abi ||= Fiddle::Function::DEFAULT - if block_given? - @cfunc = Class.new(Fiddle::Closure) { - define_method(:call, block) - }.new(cfunc.ctype, argtypes) - else - @cfunc = cfunc - end - - @args = argtypes - super(@cfunc, @args.reject { |x| x == TYPE_VOID }, cfunc.ctype, abi) - else - @cfunc = cfunc - @stack = Stack.new(argtypes.collect{|ty| ty.abs}) - if( @cfunc.ctype < 0 ) - @cfunc.ctype = @cfunc.ctype.abs - @unsigned = true - else - @unsigned = false - end - if block_given? - bind(&block) - end - end - end - - def to_i() - @cfunc.to_i - end - - def name - @cfunc.name - end - - def call(*args, &block) - if DL.fiddle? - if block_given? - args.find { |a| DL::Function === a }.bind_at_call(&block) - end - super - else - funcs = [] - _args = wrap_args(args, @stack.types, funcs, &block) - r = @cfunc.call(@stack.pack(_args)) - funcs.each{|f| f.unbind_at_call()} - return wrap_result(r) - end - end - - def wrap_result(r) - case @cfunc.ctype - when TYPE_VOIDP - r = CPtr.new(r) - else - if( @unsigned ) - r = unsigned_value(r, @cfunc.ctype) - end - end - r - end - - def bind(&block) - if DL.fiddle? - @cfunc = Class.new(Fiddle::Closure) { - def initialize ctype, args, block - super(ctype, args) - @block = block - end - - def call *args - @block.call(*args) - end - }.new(@cfunc.ctype, @args, block) - else - if( !block ) - raise(RuntimeError, "block must be given.") - end - if( @cfunc.ptr == 0 ) - cb = Proc.new{|*args| - ary = @stack.unpack(args) - @stack.types.each_with_index{|ty, idx| - case ty - when TYPE_VOIDP - ary[idx] = CPtr.new(ary[idx]) - end - } - r = block.call(*ary) - wrap_arg(r, @cfunc.ctype, []) - } - case @cfunc.calltype - when :cdecl - @cfunc.ptr = set_cdecl_callback(@cfunc.ctype, @stack.size, &cb) - when :stdcall - @cfunc.ptr = set_stdcall_callback(@cfunc.ctype, @stack.size, &cb) - else - raise(RuntimeError, "unsupported calltype: #{@cfunc.calltype}") - end - if( @cfunc.ptr == 0 ) - raise(RuntimeException, "can't bind C function.") - end - end - end - end - - def unbind() - if( @cfunc.ptr != 0 ) - case @cfunc.calltype - when :cdecl - remove_cdecl_callback(@cfunc.ptr, @cfunc.ctype) - when :stdcall - remove_stdcall_callback(@cfunc.ptr, @cfunc.ctype) - else - raise(RuntimeError, "unsupported calltype: #{@cfunc.calltype}") - end - @cfunc.ptr = 0 - end - end - - def bound?() - @cfunc.ptr != 0 - end - - def bind_at_call(&block) - bind(&block) - end - - def unbind_at_call() - end - end - - class TempFunction < Function - def bind_at_call(&block) - bind(&block) - end - - def unbind_at_call() - unbind() - end - end - - class CarriedFunction < Function - def initialize(cfunc, argtypes, n) - super(cfunc, argtypes) - @carrier = [] - @index = n - @mutex = Mutex.new - end - - def create_carrier(data) - ary = [] - userdata = [ary, data] - @mutex.lock() - @carrier.push(userdata) - return dlwrap(userdata) - end - - def bind_at_call(&block) - userdata = @carrier[-1] - userdata[0].push(block) - bind{|*args| - ptr = args[@index] - if( !ptr ) - raise(RuntimeError, "The index of userdata should be lower than #{args.size}.") - end - userdata = dlunwrap(Integer(ptr)) - args[@index] = userdata[1] - userdata[0][0].call(*args) - } - @mutex.unlock() - end - end -end diff --git a/Src/StdLib/ruby/1.9.1/dl/import.rb b/Src/StdLib/ruby/1.9.1/dl/import.rb deleted file mode 100644 index 5132df7a7..000000000 --- a/Src/StdLib/ruby/1.9.1/dl/import.rb +++ /dev/null @@ -1,235 +0,0 @@ -require 'dl' -require 'dl/func.rb' -require 'dl/struct.rb' -require 'dl/cparser.rb' - -module DL - class CompositeHandler - def initialize(handlers) - @handlers = handlers - end - - def handlers() - @handlers - end - - def sym(symbol) - @handlers.each{|handle| - if( handle ) - begin - addr = handle.sym(symbol) - return addr - rescue DLError - end - end - } - return nil - end - - def [](symbol) - sym(symbol) - end - end - - module Importer - include DL - include CParser - extend Importer - - def dlload(*libs) - handles = libs.collect{|lib| - case lib - when nil - nil - when Handle - lib - when Importer - lib.handlers - else - begin - DL.dlopen(lib) - rescue DLError - raise(DLError, "can't load #{lib}") - end - end - }.flatten() - @handler = CompositeHandler.new(handles) - @func_map = {} - @type_alias = {} - end - - def typealias(alias_type, orig_type) - @type_alias[alias_type] = orig_type - end - - def sizeof(ty) - case ty - when String - ty = parse_ctype(ty, @type_alias).abs() - case ty - when TYPE_CHAR - return SIZEOF_CHAR - when TYPE_SHORT - return SIZEOF_SHORT - when TYPE_INT - return SIZEOF_INT - when TYPE_LONG - return SIZEOF_LONG - when TYPE_LONG_LONG - return SIZEOF_LONG_LON - when TYPE_FLOAT - return SIZEOF_FLOAT - when TYPE_DOUBLE - return SIZEOF_DOUBLE - when TYPE_VOIDP - return SIZEOF_VOIDP - else - raise(DLError, "unknown type: #{ty}") - end - when Class - if( ty.instance_methods().include?(:to_ptr) ) - return ty.size() - end - end - return CPtr[ty].size() - end - - def parse_bind_options(opts) - h = {} - prekey = nil - while( opt = opts.shift() ) - case opt - when :stdcall, :cdecl - h[:call_type] = opt - when :carried, :temp, :temporal, :bind - h[:callback_type] = opt - h[:carrier] = opts.shift() - else - h[opt] = true - end - end - h - end - private :parse_bind_options - - def extern(signature, *opts) - symname, ctype, argtype = parse_signature(signature, @type_alias) - opt = parse_bind_options(opts) - f = import_function(symname, ctype, argtype, opt[:call_type]) - name = symname.gsub(/@.+/,'') - @func_map[name] = f - # define_method(name){|*args,&block| f.call(*args,&block)} - begin - /^(.+?):(\d+)/ =~ caller.first - file, line = $1, $2.to_i - rescue - file, line = __FILE__, __LINE__+3 - end - module_eval(<<-EOS, file, line) - def #{name}(*args, &block) - @func_map['#{name}'].call(*args,&block) - end - EOS - module_function(name) - f - end - - def bind(signature, *opts, &blk) - name, ctype, argtype = parse_signature(signature, @type_alias) - h = parse_bind_options(opts) - case h[:callback_type] - when :bind, nil - f = bind_function(name, ctype, argtype, h[:call_type], &blk) - when :temp, :temporal - f = create_temp_function(name, ctype, argtype, h[:call_type]) - when :carried - f = create_carried_function(name, ctype, argtype, h[:call_type], h[:carrier]) - else - raise(RuntimeError, "unknown callback type: #{h[:callback_type]}") - end - @func_map[name] = f - #define_method(name){|*args,&block| f.call(*args,&block)} - begin - /^(.+?):(\d+)/ =~ caller.first - file, line = $1, $2.to_i - rescue - file, line = __FILE__, __LINE__+3 - end - module_eval(<<-EOS, file, line) - def #{name}(*args,&block) - @func_map['#{name}'].call(*args,&block) - end - EOS - module_function(name) - f - end - - def struct(signature) - tys, mems = parse_struct_signature(signature, @type_alias) - DL::CStructBuilder.create(CStruct, tys, mems) - end - - def union(signature) - tys, mems = parse_struct_signature(signature, @type_alias) - DL::CStructBuilder.create(CUnion, tys, mems) - end - - def [](name) - @func_map[name] - end - - def create_value(ty, val=nil) - s = struct([ty + " value"]) - ptr = s.malloc() - if( val ) - ptr.value = val - end - return ptr - end - alias value create_value - - def import_value(ty, addr) - s = struct([ty + " value"]) - ptr = s.new(addr) - return ptr - end - - def import_symbol(name) - addr = @handler.sym(name) - if( !addr ) - raise(DLError, "cannot find the symbol: #{name}") - end - CPtr.new(addr) - end - - def import_function(name, ctype, argtype, call_type = nil) - addr = @handler.sym(name) - if( !addr ) - raise(DLError, "cannot find the function: #{name}()") - end - Function.new(CFunc.new(addr, ctype, name, call_type || :cdecl), argtype) - end - - def bind_function(name, ctype, argtype, call_type = nil, &block) - if DL.fiddle? - closure = Class.new(Fiddle::Closure) { - define_method(:call, block) - }.new(ctype, argtype) - - Function.new(closure, argtype) - else - f = Function.new(CFunc.new(0, ctype, name, call_type || :cdecl), argtype) - f.bind(&block) - f - end - end - - def create_temp_function(name, ctype, argtype, call_type = nil) - TempFunction.new(CFunc.new(0, ctype, name, call_type || :cdecl), argtype) - end - - def create_carried_function(name, ctype, argtype, call_type = nil, n = 0) - CarriedFunction.new(CFunc.new(0, ctype, name, call_type || :cdecl), argtype, n) - end - end -end diff --git a/Src/StdLib/ruby/1.9.1/dl/pack.rb b/Src/StdLib/ruby/1.9.1/dl/pack.rb deleted file mode 100644 index aa1b365b3..000000000 --- a/Src/StdLib/ruby/1.9.1/dl/pack.rb +++ /dev/null @@ -1,128 +0,0 @@ -require 'dl' - -module DL - module PackInfo - ALIGN_MAP = { - TYPE_VOIDP => ALIGN_VOIDP, - TYPE_CHAR => ALIGN_CHAR, - TYPE_SHORT => ALIGN_SHORT, - TYPE_INT => ALIGN_INT, - TYPE_LONG => ALIGN_LONG, - TYPE_FLOAT => ALIGN_FLOAT, - TYPE_DOUBLE => ALIGN_DOUBLE, - -TYPE_CHAR => ALIGN_CHAR, - -TYPE_SHORT => ALIGN_SHORT, - -TYPE_INT => ALIGN_INT, - -TYPE_LONG => ALIGN_LONG, - } - - PACK_MAP = { - TYPE_VOIDP => ((SIZEOF_VOIDP == SIZEOF_LONG_LONG) ? "q" : "l!"), - TYPE_CHAR => "c", - TYPE_SHORT => "s!", - TYPE_INT => "i!", - TYPE_LONG => "l!", - TYPE_FLOAT => "f", - TYPE_DOUBLE => "d", - -TYPE_CHAR => "c", - -TYPE_SHORT => "s!", - -TYPE_INT => "i!", - -TYPE_LONG => "l!", - } - - SIZE_MAP = { - TYPE_VOIDP => SIZEOF_VOIDP, - TYPE_CHAR => SIZEOF_CHAR, - TYPE_SHORT => SIZEOF_SHORT, - TYPE_INT => SIZEOF_INT, - TYPE_LONG => SIZEOF_LONG, - TYPE_FLOAT => SIZEOF_FLOAT, - TYPE_DOUBLE => SIZEOF_DOUBLE, - -TYPE_CHAR => SIZEOF_CHAR, - -TYPE_SHORT => SIZEOF_SHORT, - -TYPE_INT => SIZEOF_INT, - -TYPE_LONG => SIZEOF_LONG, - } - if defined?(TYPE_LONG_LONG) - ALIGN_MAP[TYPE_LONG_LONG] = ALIGN_MAP[-TYPE_LONG_LONG] = ALIGN_LONG_LONG - PACK_MAP[TYPE_LONG_LONG] = PACK_MAP[-TYPE_LONG_LONG] = "q" - SIZE_MAP[TYPE_LONG_LONG] = SIZE_MAP[-TYPE_LONG_LONG] = SIZEOF_LONG_LONG - end - - def align(addr, align) - d = addr % align - if( d == 0 ) - addr - else - addr + (align - d) - end - end - module_function :align - end - - class Packer - include PackInfo - - def self.[](*types) - new(types) - end - - def initialize(types) - parse_types(types) - end - - def size() - @size - end - - def pack(ary) - case SIZEOF_VOIDP - when SIZEOF_LONG - ary.pack(@template) - when SIZEOF_LONG_LONG - ary.pack(@template) - else - raise(RuntimeError, "sizeof(void*)?") - end - end - - def unpack(ary) - case SIZEOF_VOIDP - when SIZEOF_LONG - ary.join().unpack(@template) - when SIZEOF_LONG_LONG - ary.join().unpack(@template) - else - raise(RuntimeError, "sizeof(void*)?") - end - end - - private - - def parse_types(types) - @template = "" - addr = 0 - types.each{|t| - orig_addr = addr - if( t.is_a?(Array) ) - addr = align(orig_addr, ALIGN_MAP[TYPE_VOIDP]) - else - addr = align(orig_addr, ALIGN_MAP[t]) - end - d = addr - orig_addr - if( d > 0 ) - @template << "x#{d}" - end - if( t.is_a?(Array) ) - @template << (PACK_MAP[t[0]] * t[1]) - addr += (SIZE_MAP[t[0]] * t[1]) - else - @template << PACK_MAP[t] - addr += SIZE_MAP[t] - end - } - addr = align(addr, ALIGN_MAP[TYPE_VOIDP]) - @size = addr - end - end -end diff --git a/Src/StdLib/ruby/1.9.1/dl/stack.rb b/Src/StdLib/ruby/1.9.1/dl/stack.rb deleted file mode 100644 index d6bfa6793..000000000 --- a/Src/StdLib/ruby/1.9.1/dl/stack.rb +++ /dev/null @@ -1,116 +0,0 @@ -require 'dl' - -module DL - class Stack - def self.[](*types) - new(types) - end - - def initialize(types) - parse_types(types) - end - - def size() - @size - end - - def types() - @types - end - - def pack(ary) - case SIZEOF_VOIDP - when SIZEOF_LONG - ary.pack(@template).unpack('l!*') - when SIZEOF_LONG_LONG - ary.pack(@template).unpack('q*') - else - raise(RuntimeError, "sizeof(void*)?") - end - end - - def unpack(ary) - case SIZEOF_VOIDP - when SIZEOF_LONG - ary.pack('l!*').unpack(@template) - when SIZEOF_LONG_LONG - ary.pack('q*').unpack(@template) - else - raise(RuntimeError, "sizeof(void*)?") - end - end - - private - - def align(addr, align) - d = addr % align - if( d == 0 ) - addr - else - addr + (align - d) - end - end - - ALIGN_MAP = { - TYPE_VOIDP => ALIGN_VOIDP, - TYPE_CHAR => ALIGN_VOIDP, - TYPE_SHORT => ALIGN_VOIDP, - TYPE_INT => ALIGN_VOIDP, - TYPE_LONG => ALIGN_VOIDP, - TYPE_FLOAT => ALIGN_FLOAT, - TYPE_DOUBLE => ALIGN_DOUBLE, - } - - PACK_MAP = { - TYPE_VOIDP => ((SIZEOF_VOIDP == SIZEOF_LONG_LONG)? "q" : "l!"), - TYPE_CHAR => "c", - TYPE_SHORT => "s!", - TYPE_INT => "i!", - TYPE_LONG => "l!", - TYPE_FLOAT => "f", - TYPE_DOUBLE => "d", - } - - SIZE_MAP = { - TYPE_VOIDP => SIZEOF_VOIDP, - TYPE_CHAR => SIZEOF_CHAR, - TYPE_SHORT => SIZEOF_SHORT, - TYPE_INT => SIZEOF_INT, - TYPE_LONG => SIZEOF_LONG, - TYPE_FLOAT => SIZEOF_FLOAT, - TYPE_DOUBLE => SIZEOF_DOUBLE, - } - if defined?(TYPE_LONG_LONG) - ALIGN_MAP[TYPE_LONG_LONG] = ALIGN_LONG_LONG - PACK_MAP[TYPE_LONG_LONG] = "q" - SIZE_MAP[TYPE_LONG_LONG] = SIZEOF_LONG_LONG - end - - def parse_types(types) - @types = types - @template = "" - addr = 0 - types.each{|t| - addr = add_padding(addr, ALIGN_MAP[t]) - @template << PACK_MAP[t] - addr += SIZE_MAP[t] - } - addr = add_padding(addr, ALIGN_MAP[SIZEOF_VOIDP]) - if( addr % SIZEOF_VOIDP == 0 ) - @size = addr / SIZEOF_VOIDP - else - @size = (addr / SIZEOF_VOIDP) + 1 - end - end - - def add_padding(addr, align) - orig_addr = addr - addr = align(orig_addr, align) - d = addr - orig_addr - if( d > 0 ) - @template << "x#{d}" - end - addr - end - end -end diff --git a/Src/StdLib/ruby/1.9.1/dl/struct.rb b/Src/StdLib/ruby/1.9.1/dl/struct.rb deleted file mode 100644 index 26dca44e8..000000000 --- a/Src/StdLib/ruby/1.9.1/dl/struct.rb +++ /dev/null @@ -1,213 +0,0 @@ -require 'dl' -require 'dl/pack.rb' - -module DL - class CStruct - def CStruct.entity_class() - CStructEntity - end - end - - class CUnion - def CUnion.entity_class() - CUnionEntity - end - end - - module CStructBuilder - def create(klass, types, members) - new_class = Class.new(klass){ - define_method(:initialize){|addr| - @entity = klass.entity_class.new(addr, types) - @entity.assign_names(members) - } - define_method(:to_ptr){ @entity } - define_method(:to_i){ @entity.to_i } - members.each{|name| - define_method(name){ @entity[name] } - define_method(name + "="){|val| @entity[name] = val } - } - } - size = klass.entity_class.size(types) - new_class.module_eval(<<-EOS, __FILE__, __LINE__+1) - def new_class.size() - #{size} - end - def new_class.malloc() - addr = DL.malloc(#{size}) - new(addr) - end - EOS - return new_class - end - module_function :create - end - - class CStructEntity < CPtr - include PackInfo - include ValueUtil - - def CStructEntity.malloc(types, func = nil) - addr = DL.malloc(CStructEntity.size(types)) - CStructEntity.new(addr, types, func) - end - - def CStructEntity.size(types) - offset = 0 - max_align = 0 - types.each_with_index{|t,i| - orig_offset = offset - if( t.is_a?(Array) ) - align = PackInfo::ALIGN_MAP[t[0]] - offset = PackInfo.align(orig_offset, align) - size = offset - orig_offset - offset += (PackInfo::SIZE_MAP[t[0]] * t[1]) - else - align = PackInfo::ALIGN_MAP[t] - offset = PackInfo.align(orig_offset, align) - size = offset - orig_offset - offset += PackInfo::SIZE_MAP[t] - end - if (max_align < align) - max_align = align - end - } - offset = PackInfo.align(offset, max_align) - offset - end - - def initialize(addr, types, func = nil) - set_ctypes(types) - super(addr, @size, func) - end - - def assign_names(members) - @members = members - end - - def set_ctypes(types) - @ctypes = types - @offset = [] - offset = 0 - max_align = 0 - types.each_with_index{|t,i| - orig_offset = offset - if( t.is_a?(Array) ) - align = ALIGN_MAP[t[0]] - else - align = ALIGN_MAP[t] - end - offset = PackInfo.align(orig_offset, align) - size = offset - orig_offset - @offset[i] = offset - if( t.is_a?(Array) ) - offset += (SIZE_MAP[t[0]] * t[1]) - else - offset += SIZE_MAP[t] - end - if (max_align < align) - max_align = align - end - } - offset = PackInfo.align(offset, max_align) - @size = offset - end - - def [](name) - idx = @members.index(name) - if( idx.nil? ) - raise(ArgumentError, "no such member: #{name}") - end - ty = @ctypes[idx] - if( ty.is_a?(Array) ) - r = super(@offset[idx], SIZE_MAP[ty[0]] * ty[1]) - else - r = super(@offset[idx], SIZE_MAP[ty.abs]) - end - packer = Packer.new([ty]) - val = packer.unpack([r]) - case ty - when Array - case ty[0] - when TYPE_VOIDP - val = val.collect{|v| CPtr.new(v)} - end - when TYPE_VOIDP - val = CPtr.new(val[0]) - else - val = val[0] - end - if( ty.is_a?(Integer) && (ty < 0) ) - return unsigned_value(val, ty) - elsif( ty.is_a?(Array) && (ty[0] < 0) ) - return val.collect{|v| unsigned_value(v,ty[0])} - else - return val - end - end - - def []=(name, val) - idx = @members.index(name) - if( idx.nil? ) - raise(ArgumentError, "no such member: #{name}") - end - ty = @ctypes[idx] - packer = Packer.new([ty]) - val = wrap_arg(val, ty, []) - buff = packer.pack([val].flatten()) - super(@offset[idx], buff.size, buff) - if( ty.is_a?(Integer) && (ty < 0) ) - return unsigned_value(val, ty) - elsif( ty.is_a?(Array) && (ty[0] < 0) ) - return val.collect{|v| unsigned_value(v,ty[0])} - else - return val - end - end - - def to_s() - super(@size) - end - end - - class CUnionEntity < CStructEntity - include PackInfo - - def CUnionEntity.malloc(types, func=nil) - addr = DL.malloc(CUnionEntity.size(types)) - CUnionEntity.new(addr, types, func) - end - - def CUnionEntity.size(types) - size = 0 - types.each_with_index{|t,i| - if( t.is_a?(Array) ) - tsize = PackInfo::SIZE_MAP[t[0]] * t[1] - else - tsize = PackInfo::SIZE_MAP[t] - end - if( tsize > size ) - size = tsize - end - } - end - - def set_ctypes(types) - @ctypes = types - @offset = [] - @size = 0 - types.each_with_index{|t,i| - @offset[i] = 0 - if( t.is_a?(Array) ) - size = SIZE_MAP[t[0]] * t[1] - else - size = SIZE_MAP[t] - end - if( size > @size ) - @size = size - end - } - end - end -end - diff --git a/Src/StdLib/ruby/1.9.1/dl/types.rb b/Src/StdLib/ruby/1.9.1/dl/types.rb deleted file mode 100644 index ffae24f26..000000000 --- a/Src/StdLib/ruby/1.9.1/dl/types.rb +++ /dev/null @@ -1,40 +0,0 @@ -module DL - module Win32Types - def included(m) - m.module_eval{ - typealias "DWORD", "unsigned long" - typealias "PDWORD", "unsigned long *" - typealias "WORD", "unsigned short" - typealias "PWORD", "unsigned short *" - typealias "BOOL", "int" - typealias "ATOM", "int" - typealias "BYTE", "unsigned char" - typealias "PBYTE", "unsigned char *" - typealias "UINT", "unsigned int" - typealias "ULONG", "unsigned long" - typealias "UCHAR", "unsigned char" - typealias "HANDLE", "unsigned long" - typealias "PHANDLE", "void*" - typealias "PVOID", "void*" - typealias "LPCSTR", "char*" - typealias "LPSTR", "char*" - typealias "HINSTANCE", "unsigned int" - typealias "HDC", "unsigned int" - typealias "HWND", "unsigned int" - } - end - module_function :included - end - - module BasicTypes - def included(m) - m.module_eval{ - typealias "uint", "unsigned int" - typealias "u_int", "unsigned int" - typealias "ulong", "unsigned long" - typealias "u_long", "unsigned long" - } - end - module_function :included - end -end diff --git a/Src/StdLib/ruby/1.9.1/dl/value.rb b/Src/StdLib/ruby/1.9.1/dl/value.rb deleted file mode 100644 index 84a05741e..000000000 --- a/Src/StdLib/ruby/1.9.1/dl/value.rb +++ /dev/null @@ -1,112 +0,0 @@ -require 'dl' - -module DL - module ValueUtil - def unsigned_value(val, ty) - case ty.abs - when TYPE_CHAR - [val].pack("c").unpack("C")[0] - when TYPE_SHORT - [val].pack("s!").unpack("S!")[0] - when TYPE_INT - [val].pack("i!").unpack("I!")[0] - when TYPE_LONG - [val].pack("l!").unpack("L!")[0] - when TYPE_LONG_LONG - [val].pack("q!").unpack("Q!")[0] - else - val - end - end - - def signed_value(val, ty) - case ty.abs - when TYPE_CHAR - [val].pack("C").unpack("c")[0] - when TYPE_SHORT - [val].pack("S!").unpack("s!")[0] - when TYPE_INT - [val].pack("I!").unpack("i!")[0] - when TYPE_LONG - [val].pack("L!").unpack("l!")[0] - when TYPE_LONG_LONG - [val].pack("Q!").unpack("q!")[0] - else - val - end - end - - def wrap_args(args, tys, funcs, &block) - result = [] - tys ||= [] - args.each_with_index{|arg, idx| - result.push(wrap_arg(arg, tys[idx], funcs, &block)) - } - result - end - - def wrap_arg(arg, ty, funcs = [], &block) - funcs ||= [] - case arg - when nil - return 0 - when CPtr - return arg.to_i - when IO - case ty - when TYPE_VOIDP - return CPtr[arg].to_i - else - return arg.to_i - end - when Function - if( block ) - arg.bind_at_call(&block) - funcs.push(arg) - elsif !arg.bound? - raise(RuntimeError, "block must be given.") - end - return arg.to_i - when String - if( ty.is_a?(Array) ) - return arg.unpack('C*') - else - case SIZEOF_VOIDP - when SIZEOF_LONG - return [arg].pack("p").unpack("l!")[0] - when SIZEOF_LONG_LONG - return [arg].pack("p").unpack("q")[0] - else - raise(RuntimeError, "sizeof(void*)?") - end - end - when Float, Integer - return arg - when Array - if( ty.is_a?(Array) ) # used only by struct - case ty[0] - when TYPE_VOIDP - return arg.collect{|v| Integer(v)} - when TYPE_CHAR - if( arg.is_a?(String) ) - return val.unpack('C*') - end - end - return arg - else - return arg - end - else - if( arg.respond_to?(:to_ptr) ) - return arg.to_ptr.to_i - else - begin - return Integer(arg) - rescue - raise(ArgumentError, "unknown argument type: #{arg.class}") - end - end - end - end - end -end diff --git a/Src/StdLib/ruby/1.9.1/e2mmap.rb b/Src/StdLib/ruby/1.9.1/e2mmap.rb deleted file mode 100644 index ad4d7ca75..000000000 --- a/Src/StdLib/ruby/1.9.1/e2mmap.rb +++ /dev/null @@ -1,172 +0,0 @@ -# -# e2mmap.rb - for ruby 1.1 -# $Release Version: 2.0$ -# $Revision: 1.10 $ -# by Keiju ISHITSUKA -# -# -- -# Usage: -# -# U1) -# class Foo -# extend Exception2MessageMapper -# def_e2message ExistingExceptionClass, "message..." -# def_exception :NewExceptionClass, "message..."[, superclass] -# ... -# end -# -# U2) -# module Error -# extend Exception2MessageMapper -# def_e2meggage ExistingExceptionClass, "message..." -# def_exception :NewExceptionClass, "message..."[, superclass] -# ... -# end -# class Foo -# include Error -# ... -# end -# -# foo = Foo.new -# foo.Fail .... -# -# U3) -# module Error -# extend Exception2MessageMapper -# def_e2message ExistingExceptionClass, "message..." -# def_exception :NewExceptionClass, "message..."[, superclass] -# ... -# end -# class Foo -# extend Exception2MessageMapper -# include Error -# ... -# end -# -# Foo.Fail NewExceptionClass, arg... -# Foo.Fail ExistingExceptionClass, arg... -# -# -module Exception2MessageMapper - @RCS_ID='-$Id: e2mmap.rb,v 1.10 1999/02/17 12:33:17 keiju Exp keiju $-' - - E2MM = Exception2MessageMapper - - def E2MM.extend_object(cl) - super - cl.bind(self) unless cl < E2MM - end - - def bind(cl) - self.module_eval %[ - def Raise(err = nil, *rest) - Exception2MessageMapper.Raise(self.class, err, *rest) - end - alias Fail Raise - - def self.included(mod) - mod.extend Exception2MessageMapper - end - ] - end - - # Fail(err, *rest) - # err: exception - # rest: message arguments - # - def Raise(err = nil, *rest) - E2MM.Raise(self, err, *rest) - end - alias Fail Raise - alias fail Raise - - # def_e2message(c, m) - # c: exception - # m: message_form - # define exception c with message m. - # - def def_e2message(c, m) - E2MM.def_e2message(self, c, m) - end - - # def_exception(n, m, s) - # n: exception_name - # m: message_form - # s: superclass(default: StandardError) - # define exception named ``c'' with message m. - # - def def_exception(n, m, s = StandardError) - E2MM.def_exception(self, n, m, s) - end - - # - # Private definitions. - # - # {[class, exp] => message, ...} - @MessageMap = {} - - # E2MM.def_e2message(k, e, m) - # k: class to define exception under. - # e: exception - # m: message_form - # define exception c with message m. - # - def E2MM.def_e2message(k, c, m) - 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 - # m: message_form - # s: superclass(default: StandardError) - # define exception named ``c'' with message m. - # - def E2MM.def_exception(k, n, m, s = StandardError) - n = n.id2name if n.kind_of?(Integer) - e = Class.new(s) - E2MM.instance_eval{@MessageMap[[k, e]] = m} - k.const_set(n, e) - end - - # Fail(klass, err, *rest) - # klass: class to define exception under. - # err: exception - # rest: message arguments - # - def E2MM.Raise(klass = E2MM, err = nil, *rest) - if form = e2mm_message(klass, err) - b = $@.nil? ? caller(1) : $@ - #p $@ - #p __FILE__ - b.shift if b[0] =~ /^#{Regexp.quote(__FILE__)}:/ - raise err, sprintf(form, *rest), b - else - E2MM.Fail E2MM, ErrNotRegisteredException, err.inspect - end - end - class << E2MM - alias Fail Raise - end - - def E2MM.e2mm_message(klass, exp) - for c in klass.ancestors - if mes = @MessageMap[[c,exp]] - #p mes - m = klass.instance_eval('"' + mes + '"') - return m - end - end - nil - end - class << self - alias message e2mm_message - end - - E2MM.def_exception(E2MM, - :ErrNotRegisteredException, - "not registerd exception(%s)") -end - - diff --git a/Src/StdLib/ruby/1.9.1/gserver.rb b/Src/StdLib/ruby/1.9.1/gserver.rb deleted file mode 100644 index 5a14d0cfe..000000000 --- a/Src/StdLib/ruby/1.9.1/gserver.rb +++ /dev/null @@ -1,253 +0,0 @@ -# -# Copyright (C) 2001 John W. Small All Rights Reserved -# -# Author:: John W. Small -# Documentation:: Gavin Sinclair -# Licence:: Freeware. -# -# See the class GServer for documentation. -# - -require "socket" -require "thread" - -# -# GServer implements a generic server, featuring thread pool management, -# simple logging, and multi-server management. See HttpServer in -# xmlrpc/httpserver.rb in the Ruby standard library for an example of -# GServer in action. -# -# Any kind of application-level server can be implemented using this class. -# It accepts multiple simultaneous connections from clients, up to an optional -# maximum number. Several _services_ (i.e. one service per TCP port) can be -# run simultaneously, and stopped at any time through the class method -# GServer.stop(port). All the threading issues are handled, saving -# you the effort. All events are optionally logged, but you can provide your -# own event handlers if you wish. -# -# === Example -# -# Using GServer is simple. Below we implement a simple time server, run it, -# query it, and shut it down. Try this code in +irb+: -# -# require 'gserver' -# -# # -# # A server that returns the time in seconds since 1970. -# # -# class TimeServer < GServer -# def initialize(port=10001, *args) -# super(port, *args) -# end -# def serve(io) -# io.puts(Time.now.to_s) -# end -# end -# -# # Run the server with logging enabled (it's a separate thread). -# server = TimeServer.new -# server.audit = true # Turn logging on. -# server.start -# -# # *** Now point your browser to http://localhost:10001 to see it working *** -# -# # See if it's still running. -# GServer.in_service?(10001) # -> true -# server.stopped? # -> false -# -# # Shut the server down gracefully. -# server.shutdown -# -# # Alternatively, stop it immediately. -# GServer.stop(10001) -# # or, of course, "server.stop". -# -# All the business of accepting connections and exception handling is taken -# care of. All we have to do is implement the method that actually serves the -# client. -# -# === Advanced -# -# As the example above shows, the way to use GServer is to subclass it to -# create a specific server, overriding the +serve+ method. You can override -# other methods as well if you wish, perhaps to collect statistics, or emit -# more detailed logging. -# -# connecting -# disconnecting -# starting -# stopping -# -# The above methods are only called if auditing is enabled. -# -# You can also override +log+ and +error+ if, for example, you wish to use a -# more sophisticated logging system. -# -class GServer - - DEFAULT_HOST = "127.0.0.1" - - def serve(io) - end - - @@services = {} # Hash of opened ports, i.e. services - @@servicesMutex = Mutex.new - - def GServer.stop(port, host = DEFAULT_HOST) - @@servicesMutex.synchronize { - @@services[host][port].stop - } - end - - def GServer.in_service?(port, host = DEFAULT_HOST) - @@services.has_key?(host) and - @@services[host].has_key?(port) - end - - def stop - @connectionsMutex.synchronize { - if @tcpServerThread - @tcpServerThread.raise "stop" - end - } - end - - def stopped? - @tcpServerThread == nil - end - - def shutdown - @shutdown = true - end - - def connections - @connections.size - end - - def join - @tcpServerThread.join if @tcpServerThread - end - - attr_reader :port, :host, :maxConnections - attr_accessor :stdlog, :audit, :debug - - def connecting(client) - addr = client.peeraddr - log("#{self.class.to_s} #{@host}:#{@port} client:#{addr[1]} " + - "#{addr[2]}<#{addr[3]}> connect") - true - end - - def disconnecting(clientPort) - log("#{self.class.to_s} #{@host}:#{@port} " + - "client:#{clientPort} disconnect") - end - - protected :connecting, :disconnecting - - def starting() - log("#{self.class.to_s} #{@host}:#{@port} start") - end - - def stopping() - log("#{self.class.to_s} #{@host}:#{@port} stop") - end - - protected :starting, :stopping - - def error(detail) - log(detail.backtrace.join("\n")) - end - - def log(msg) - if @stdlog - @stdlog.puts("[#{Time.new.ctime}] %s" % msg) - @stdlog.flush - end - end - - protected :error, :log - - def initialize(port, host = DEFAULT_HOST, maxConnections = 4, - stdlog = $stderr, audit = false, debug = false) - @tcpServerThread = nil - @port = port - @host = host - @maxConnections = maxConnections - @connections = [] - @connectionsMutex = Mutex.new - @connectionsCV = ConditionVariable.new - @stdlog = stdlog - @audit = audit - @debug = debug - end - - def start(maxConnections = -1) - raise "running" if !stopped? - @shutdown = false - @maxConnections = maxConnections if maxConnections > 0 - @@servicesMutex.synchronize { - if GServer.in_service?(@port,@host) - raise "Port already in use: #{host}:#{@port}!" - end - @tcpServer = TCPServer.new(@host,@port) - @port = @tcpServer.addr[1] - @@services[@host] = {} unless @@services.has_key?(@host) - @@services[@host][@port] = self; - } - @tcpServerThread = Thread.new { - begin - starting if @audit - while !@shutdown - @connectionsMutex.synchronize { - while @connections.size >= @maxConnections - @connectionsCV.wait(@connectionsMutex) - end - } - client = @tcpServer.accept - @connections << Thread.new(client) { |myClient| - begin - myPort = myClient.peeraddr[1] - serve(myClient) if !@audit or connecting(myClient) - rescue => detail - error(detail) if @debug - ensure - begin - myClient.close - rescue - end - @connectionsMutex.synchronize { - @connections.delete(Thread.current) - @connectionsCV.signal - } - disconnecting(myPort) if @audit - end - } - end - rescue => detail - error(detail) if @debug - ensure - begin - @tcpServer.close - rescue - end - if @shutdown - @connectionsMutex.synchronize { - while @connections.size > 0 - @connectionsCV.wait(@connectionsMutex) - end - } - else - @connections.each { |c| c.raise "stop" } - end - @tcpServerThread = nil - @@servicesMutex.synchronize { - @@services[@host].delete(@port) - } - stopping if @audit - end - } - self - end - -end diff --git a/Src/StdLib/ruby/1.9.1/mathn.rb b/Src/StdLib/ruby/1.9.1/mathn.rb deleted file mode 100644 index 286e9c6ea..000000000 --- a/Src/StdLib/ruby/1.9.1/mathn.rb +++ /dev/null @@ -1,195 +0,0 @@ -# -# mathn.rb - -# $Release Version: 0.5 $ -# $Revision: 1.1.1.1.4.1 $ -# by Keiju ISHITSUKA(SHL Japan Inc.) -# -# -- -# -# -# - -require "cmath.rb" -require "matrix.rb" -require "prime.rb" - -require "mathn/rational" -require "mathn/complex" - -unless defined?(Math.exp!) - Object.instance_eval{remove_const :Math} - Math = CMath -end - -class Integer - remove_method :/ - alias / quo - - alias power! ** unless method_defined? :power! - - def ** (other) - if self < 0 && other.round != other - Complex(self, 0.0) ** other - else - power!(other) - end - end - -end - - -class Rational - remove_method :** - def ** (other) - if other.kind_of?(Rational) - other2 = other - if self < 0 - return Complex(self, 0.0) ** other - elsif other == 0 - return Rational(1,1) - elsif self == 0 - return Rational(0,1) - elsif self == 1 - return Rational(1,1) - end - - npd = numerator.prime_division - dpd = denominator.prime_division - if other < 0 - other = -other - npd, dpd = dpd, npd - end - - for elm in npd - elm[1] = elm[1] * other - if !elm[1].kind_of?(Integer) and elm[1].denominator != 1 - return Float(self) ** other2 - end - elm[1] = elm[1].to_i - end - - for elm in dpd - elm[1] = elm[1] * other - if !elm[1].kind_of?(Integer) and elm[1].denominator != 1 - return Float(self) ** other2 - end - elm[1] = elm[1].to_i - end - - num = Integer.from_prime_division(npd) - den = Integer.from_prime_division(dpd) - - Rational(num,den) - - elsif other.kind_of?(Integer) - if other > 0 - num = numerator ** other - den = denominator ** other - elsif other < 0 - num = denominator ** -other - den = numerator ** -other - elsif other == 0 - num = 1 - den = 1 - end - Rational(num, den) - elsif other.kind_of?(Float) - Float(self) ** other - else - x , y = other.coerce(self) - x ** y - end - end -end - -module Math - remove_method(:sqrt) - def sqrt(a) - if a.kind_of?(Complex) - abs = sqrt(a.real*a.real + a.imag*a.imag) -# if not abs.kind_of?(Rational) -# return a**Rational(1,2) -# end - x = sqrt((a.real + abs)/Rational(2)) - y = sqrt((-a.real + abs)/Rational(2)) -# if !(x.kind_of?(Rational) and y.kind_of?(Rational)) -# return a**Rational(1,2) -# end - if a.imag >= 0 - Complex(x, y) - else - Complex(x, -y) - end - elsif a.respond_to?(:nan?) and a.nan? - a - elsif a >= 0 - rsqrt(a) - else - Complex(0,rsqrt(-a)) - end - end - - def rsqrt(a) - if a.kind_of?(Float) - sqrt!(a) - elsif a.kind_of?(Rational) - rsqrt(a.numerator)/rsqrt(a.denominator) - else - src = a - max = 2 ** 32 - byte_a = [src & 0xffffffff] - # ruby's bug - while (src >= max) and (src >>= 32) - byte_a.unshift src & 0xffffffff - end - - answer = 0 - main = 0 - side = 0 - for elm in byte_a - main = (main << 32) + elm - side <<= 16 - if answer != 0 - if main * 4 < side * side - applo = main.div(side) - else - applo = ((sqrt!(side * side + 4 * main) - side)/2.0).to_i + 1 - end - else - applo = sqrt!(main).to_i + 1 - end - - while (x = (side + applo) * applo) > main - applo -= 1 - end - main -= x - answer = (answer << 16) + applo - side += applo * 2 - end - if main == 0 - answer - else - sqrt!(a) - end - end - end - - class << self - remove_method(:sqrt) - end - module_function :sqrt - module_function :rsqrt -end - -class Float - alias power! ** - - def ** (other) - if self < 0 && other.round != other - Complex(self, 0.0) ** other - else - power!(other) - end - end - -end diff --git a/Src/StdLib/ruby/1.9.1/net/telnet.rb b/Src/StdLib/ruby/1.9.1/net/telnet.rb deleted file mode 100644 index c69ee137d..000000000 --- a/Src/StdLib/ruby/1.9.1/net/telnet.rb +++ /dev/null @@ -1,759 +0,0 @@ -# = net/telnet.rb - Simple Telnet Client Library -# -# Author:: Wakou Aoyama -# Documentation:: William Webber and Wakou Aoyama -# -# This file holds the class Net::Telnet, which provides client-side -# telnet functionality. -# -# For documentation, see Net::Telnet. -# - -require "socket" -require "timeout" -require "English" - -module Net - - # - # == Net::Telnet - # - # Provides telnet client functionality. - # - # This class also has, through delegation, all the methods of a - # socket object (by default, a +TCPSocket+, but can be set by the - # +Proxy+ option to new()). This provides methods such as - # close() to end the session and sysread() to read - # data directly from the host, instead of via the waitfor() - # mechanism. Note that if you do use sysread() directly - # when in telnet mode, you should probably pass the output through - # preprocess() to extract telnet command sequences. - # - # == Overview - # - # The telnet protocol allows a client to login remotely to a user - # account on a server and execute commands via a shell. The equivalent - # is done by creating a Net::Telnet class with the +Host+ option - # set to your host, calling #login() with your user and password, - # issuing one or more #cmd() calls, and then calling #close() - # to end the session. The #waitfor(), #print(), #puts(), and - # #write() methods, which #cmd() is implemented on top of, are - # only needed if you are doing something more complicated. - # - # A Net::Telnet object can also be used to connect to non-telnet - # services, such as SMTP or HTTP. In this case, you normally - # want to provide the +Port+ option to specify the port to - # connect to, and set the +Telnetmode+ option to false to prevent - # the client from attempting to interpret telnet command sequences. - # Generally, #login() will not work with other protocols, and you - # have to handle authentication yourself. - # - # For some protocols, it will be possible to specify the +Prompt+ - # option once when you create the Telnet object and use #cmd() calls; - # for others, you will have to specify the response sequence to - # look for as the Match option to every #cmd() call, or call - # #puts() and #waitfor() directly; for yet others, you will have - # to use #sysread() instead of #waitfor() and parse server - # responses yourself. - # - # It is worth noting that when you create a new Net::Telnet object, - # you can supply a proxy IO channel via the Proxy option. This - # can be used to attach the Telnet object to other Telnet objects, - # to already open sockets, or to any read-write IO object. This - # can be useful, for instance, for setting up a test fixture for - # unit testing. - # - # == Examples - # - # === Log in and send a command, echoing all output to stdout - # - # localhost = Net::Telnet::new("Host" => "localhost", - # "Timeout" => 10, - # "Prompt" => /[$%#>] \z/n) - # localhost.login("username", "password") { |c| print c } - # localhost.cmd("command") { |c| print c } - # localhost.close - # - # - # === Check a POP server to see if you have mail - # - # pop = Net::Telnet::new("Host" => "your_destination_host_here", - # "Port" => 110, - # "Telnetmode" => false, - # "Prompt" => /^\+OK/n) - # pop.cmd("user " + "your_username_here") { |c| print c } - # pop.cmd("pass " + "your_password_here") { |c| print c } - # pop.cmd("list") { |c| print c } - # - # == References - # - # There are a large number of RFCs relevant to the Telnet protocol. - # RFCs 854-861 define the base protocol. For a complete listing - # of relevant RFCs, see - # http://www.omnifarious.org/~hopper/technical/telnet-rfc.html - # - class Telnet - - # :stopdoc: - IAC = 255.chr # "\377" # "\xff" # interpret as command - DONT = 254.chr # "\376" # "\xfe" # you are not to use option - DO = 253.chr # "\375" # "\xfd" # please, you use option - WONT = 252.chr # "\374" # "\xfc" # I won't use option - WILL = 251.chr # "\373" # "\xfb" # I will use option - SB = 250.chr # "\372" # "\xfa" # interpret as subnegotiation - GA = 249.chr # "\371" # "\xf9" # you may reverse the line - EL = 248.chr # "\370" # "\xf8" # erase the current line - EC = 247.chr # "\367" # "\xf7" # erase the current character - AYT = 246.chr # "\366" # "\xf6" # are you there - AO = 245.chr # "\365" # "\xf5" # abort output--but let prog finish - IP = 244.chr # "\364" # "\xf4" # interrupt process--permanently - BREAK = 243.chr # "\363" # "\xf3" # break - DM = 242.chr # "\362" # "\xf2" # data mark--for connect. cleaning - NOP = 241.chr # "\361" # "\xf1" # nop - SE = 240.chr # "\360" # "\xf0" # end sub negotiation - EOR = 239.chr # "\357" # "\xef" # end of record (transparent mode) - ABORT = 238.chr # "\356" # "\xee" # Abort process - SUSP = 237.chr # "\355" # "\xed" # Suspend process - EOF = 236.chr # "\354" # "\xec" # End of file - SYNCH = 242.chr # "\362" # "\xf2" # for telfunc calls - - OPT_BINARY = 0.chr # "\000" # "\x00" # Binary Transmission - OPT_ECHO = 1.chr # "\001" # "\x01" # Echo - OPT_RCP = 2.chr # "\002" # "\x02" # Reconnection - OPT_SGA = 3.chr # "\003" # "\x03" # Suppress Go Ahead - OPT_NAMS = 4.chr # "\004" # "\x04" # Approx Message Size Negotiation - OPT_STATUS = 5.chr # "\005" # "\x05" # Status - OPT_TM = 6.chr # "\006" # "\x06" # Timing Mark - OPT_RCTE = 7.chr # "\a" # "\x07" # Remote Controlled Trans and Echo - OPT_NAOL = 8.chr # "\010" # "\x08" # Output Line Width - OPT_NAOP = 9.chr # "\t" # "\x09" # Output Page Size - OPT_NAOCRD = 10.chr # "\n" # "\x0a" # Output Carriage-Return Disposition - OPT_NAOHTS = 11.chr # "\v" # "\x0b" # Output Horizontal Tab Stops - OPT_NAOHTD = 12.chr # "\f" # "\x0c" # Output Horizontal Tab Disposition - OPT_NAOFFD = 13.chr # "\r" # "\x0d" # Output Formfeed Disposition - OPT_NAOVTS = 14.chr # "\016" # "\x0e" # Output Vertical Tabstops - OPT_NAOVTD = 15.chr # "\017" # "\x0f" # Output Vertical Tab Disposition - OPT_NAOLFD = 16.chr # "\020" # "\x10" # Output Linefeed Disposition - OPT_XASCII = 17.chr # "\021" # "\x11" # Extended ASCII - OPT_LOGOUT = 18.chr # "\022" # "\x12" # Logout - OPT_BM = 19.chr # "\023" # "\x13" # Byte Macro - OPT_DET = 20.chr # "\024" # "\x14" # Data Entry Terminal - OPT_SUPDUP = 21.chr # "\025" # "\x15" # SUPDUP - OPT_SUPDUPOUTPUT = 22.chr # "\026" # "\x16" # SUPDUP Output - OPT_SNDLOC = 23.chr # "\027" # "\x17" # Send Location - OPT_TTYPE = 24.chr # "\030" # "\x18" # Terminal Type - OPT_EOR = 25.chr # "\031" # "\x19" # End of Record - OPT_TUID = 26.chr # "\032" # "\x1a" # TACACS User Identification - OPT_OUTMRK = 27.chr # "\e" # "\x1b" # Output Marking - OPT_TTYLOC = 28.chr # "\034" # "\x1c" # Terminal Location Number - OPT_3270REGIME = 29.chr # "\035" # "\x1d" # Telnet 3270 Regime - OPT_X3PAD = 30.chr # "\036" # "\x1e" # X.3 PAD - OPT_NAWS = 31.chr # "\037" # "\x1f" # Negotiate About Window Size - OPT_TSPEED = 32.chr # " " # "\x20" # Terminal Speed - OPT_LFLOW = 33.chr # "!" # "\x21" # Remote Flow Control - OPT_LINEMODE = 34.chr # "\"" # "\x22" # Linemode - OPT_XDISPLOC = 35.chr # "#" # "\x23" # X Display Location - OPT_OLD_ENVIRON = 36.chr # "$" # "\x24" # Environment Option - OPT_AUTHENTICATION = 37.chr # "%" # "\x25" # Authentication Option - OPT_ENCRYPT = 38.chr # "&" # "\x26" # Encryption Option - OPT_NEW_ENVIRON = 39.chr # "'" # "\x27" # New Environment Option - OPT_EXOPL = 255.chr # "\377" # "\xff" # Extended-Options-List - - NULL = "\000" - CR = "\015" - LF = "\012" - EOL = CR + LF - REVISION = '$Id: telnet.rb 25733 2009-11-12 14:03:03Z xibbar $' - # :startdoc: - - # - # Creates a new Net::Telnet object. - # - # Attempts to connect to the host (unless the Proxy option is - # provided: see below). If a block is provided, it is yielded - # status messages on the attempt to connect to the server, of - # the form: - # - # Trying localhost... - # Connected to localhost. - # - # +options+ is a hash of options. The following example lists - # all options and their default values. - # - # host = Net::Telnet::new( - # "Host" => "localhost", # default: "localhost" - # "Port" => 23, # default: 23 - # "Binmode" => false, # default: false - # "Output_log" => "output_log", # default: nil (no output) - # "Dump_log" => "dump_log", # default: nil (no output) - # "Prompt" => /[$%#>] \z/n, # default: /[$%#>] \z/n - # "Telnetmode" => true, # default: true - # "Timeout" => 10, # default: 10 - # # if ignore timeout then set "Timeout" to false. - # "Waittime" => 0, # default: 0 - # "Proxy" => proxy # default: nil - # # proxy is Net::Telnet or IO object - # ) - # - # The options have the following meanings: - # - # Host:: the hostname or IP address of the host to connect to, as a String. - # Defaults to "localhost". - # - # Port:: the port to connect to. Defaults to 23. - # - # Binmode:: if false (the default), newline substitution is performed. - # Outgoing LF is - # converted to CRLF, and incoming CRLF is converted to LF. If - # true, this substitution is not performed. This value can - # also be set with the #binmode() method. The - # outgoing conversion only applies to the #puts() and #print() - # methods, not the #write() method. The precise nature of - # the newline conversion is also affected by the telnet options - # SGA and BIN. - # - # Output_log:: the name of the file to write connection status messages - # and all received traffic to. In the case of a proper - # Telnet session, this will include the client input as - # echoed by the host; otherwise, it only includes server - # responses. Output is appended verbatim to this file. - # By default, no output log is kept. - # - # Dump_log:: as for Output_log, except that output is written in hexdump - # format (16 bytes per line as hex pairs, followed by their - # printable equivalent), with connection status messages - # preceded by '#', sent traffic preceded by '>', and - # received traffic preceded by '<'. By default, not dump log - # is kept. - # - # Prompt:: a regular expression matching the host's command-line prompt - # sequence. This is needed by the Telnet class to determine - # when the output from a command has finished and the host is - # ready to receive a new command. By default, this regular - # expression is /[$%#>] \z/n. - # - # Telnetmode:: a boolean value, true by default. In telnet mode, - # traffic received from the host is parsed for special - # command sequences, and these sequences are escaped - # in outgoing traffic sent using #puts() or #print() - # (but not #write()). If you are using the Net::Telnet - # object to connect to a non-telnet service (such as - # SMTP or POP), this should be set to "false" to prevent - # undesired data corruption. This value can also be set - # by the #telnetmode() method. - # - # Timeout:: the number of seconds to wait before timing out both the - # initial attempt to connect to host (in this constructor), - # and all attempts to read data from the host (in #waitfor(), - # #cmd(), and #login()). Exceeding this timeout causes a - # TimeoutError to be raised. The default value is 10 seconds. - # You can disable the timeout by setting this value to false. - # In this case, the connect attempt will eventually timeout - # on the underlying connect(2) socket call with an - # Errno::ETIMEDOUT error (but generally only after a few - # minutes), but other attempts to read data from the host - # will hand indefinitely if no data is forthcoming. - # - # Waittime:: the amount of time to wait after seeing what looks like a - # prompt (that is, received data that matches the Prompt - # option regular expression) to see if more data arrives. - # If more data does arrive in this time, Net::Telnet assumes - # that what it saw was not really a prompt. This is to try to - # avoid false matches, but it can also lead to missing real - # prompts (if, for instance, a background process writes to - # the terminal soon after the prompt is displayed). By - # default, set to 0, meaning not to wait for more data. - # - # Proxy:: a proxy object to used instead of opening a direct connection - # to the host. Must be either another Net::Telnet object or - # an IO object. If it is another Net::Telnet object, this - # instance will use that one's socket for communication. If an - # IO object, it is used directly for communication. Any other - # kind of object will cause an error to be raised. - # - def initialize(options) # :yield: mesg - @options = options - @options["Host"] = "localhost" unless @options.has_key?("Host") - @options["Port"] = 23 unless @options.has_key?("Port") - @options["Prompt"] = /[$%#>] \z/n unless @options.has_key?("Prompt") - @options["Timeout"] = 10 unless @options.has_key?("Timeout") - @options["Waittime"] = 0 unless @options.has_key?("Waittime") - unless @options.has_key?("Binmode") - @options["Binmode"] = false - else - unless (true == @options["Binmode"] or false == @options["Binmode"]) - raise ArgumentError, "Binmode option must be true or false" - end - end - - unless @options.has_key?("Telnetmode") - @options["Telnetmode"] = true - else - unless (true == @options["Telnetmode"] or false == @options["Telnetmode"]) - raise ArgumentError, "Telnetmode option must be true or false" - end - end - - @telnet_option = { "SGA" => false, "BINARY" => false } - - if @options.has_key?("Output_log") - @log = File.open(@options["Output_log"], 'a+') - @log.sync = true - @log.binmode - end - - if @options.has_key?("Dump_log") - @dumplog = File.open(@options["Dump_log"], 'a+') - @dumplog.sync = true - @dumplog.binmode - def @dumplog.log_dump(dir, x) # :nodoc: - len = x.length - addr = 0 - offset = 0 - while 0 < len - if len < 16 - line = x[offset, len] - else - line = x[offset, 16] - end - hexvals = line.unpack('H*')[0] - hexvals += ' ' * (32 - hexvals.length) - hexvals = format("%s %s %s %s " * 4, *hexvals.unpack('a2' * 16)) - line = line.gsub(/[\000-\037\177-\377]/n, '.') - printf "%s 0x%5.5x: %s%s\n", dir, addr, hexvals, line - addr += 16 - offset += 16 - len -= 16 - end - print "\n" - end - end - - if @options.has_key?("Proxy") - if @options["Proxy"].kind_of?(Net::Telnet) - @sock = @options["Proxy"].sock - elsif @options["Proxy"].kind_of?(IO) - @sock = @options["Proxy"] - else - raise "Error: Proxy must be an instance of Net::Telnet or IO." - end - else - message = "Trying " + @options["Host"] + "...\n" - yield(message) if block_given? - @log.write(message) if @options.has_key?("Output_log") - @dumplog.log_dump('#', message) if @options.has_key?("Dump_log") - - begin - if @options["Timeout"] == false - @sock = TCPSocket.open(@options["Host"], @options["Port"]) - else - timeout(@options["Timeout"]) do - @sock = TCPSocket.open(@options["Host"], @options["Port"]) - end - end - rescue TimeoutError - raise TimeoutError, "timed out while opening a connection to the host" - rescue - @log.write($ERROR_INFO.to_s + "\n") if @options.has_key?("Output_log") - @dumplog.log_dump('#', $ERROR_INFO.to_s + "\n") if @options.has_key?("Dump_log") - raise - end - @sock.sync = true - @sock.binmode - - message = "Connected to " + @options["Host"] + ".\n" - yield(message) if block_given? - @log.write(message) if @options.has_key?("Output_log") - @dumplog.log_dump('#', message) if @options.has_key?("Dump_log") - end - - end # initialize - - # 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 - - # Set telnet command interpretation on (+mode+ == true) or off - # (+mode+ == false), or return the current value (+mode+ not - # provided). It should be on for true telnet sessions, off if - # using Net::Telnet to connect to a non-telnet service such - # as SMTP. - def telnetmode(mode = nil) - case mode - when nil - @options["Telnetmode"] - when true, false - @options["Telnetmode"] = mode - else - raise ArgumentError, "argument must be true or false, or missing" - end - end - - # Turn telnet command interpretation on (true) or off (false). It - # should be on for true telnet sessions, off if using Net::Telnet - # to connect to a non-telnet service such as SMTP. - def telnetmode=(mode) - if (true == mode or false == mode) - @options["Telnetmode"] = mode - else - raise ArgumentError, "argument must be true or false" - end - end - - # Turn newline conversion on (+mode+ == false) or off (+mode+ == true), - # or return the current value (+mode+ is not specified). - def binmode(mode = nil) - case mode - when nil - @options["Binmode"] - when true, false - @options["Binmode"] = mode - else - raise ArgumentError, "argument must be true or false" - end - end - - # Turn newline conversion on (false) or off (true). - def binmode=(mode) - if (true == mode or false == mode) - @options["Binmode"] = mode - else - raise ArgumentError, "argument must be true or false" - end - end - - # Preprocess received data from the host. - # - # Performs newline conversion and detects telnet command sequences. - # Called automatically by #waitfor(). You should only use this - # method yourself if you have read input directly using sysread() - # or similar, and even then only if in telnet mode. - def preprocess(string) - # combine CR+NULL into CR - string = string.gsub(/#{CR}#{NULL}/no, CR) if @options["Telnetmode"] - - # combine EOL into "\n" - string = string.gsub(/#{EOL}/no, "\n") unless @options["Binmode"] - - # remove NULL - string = string.gsub(/#{NULL}/no, '') unless @options["Binmode"] - - string.gsub(/#{IAC}( - [#{IAC}#{AO}#{AYT}#{DM}#{IP}#{NOP}]| - [#{DO}#{DONT}#{WILL}#{WONT}] - [#{OPT_BINARY}-#{OPT_NEW_ENVIRON}#{OPT_EXOPL}]| - #{SB}[^#{IAC}]*#{IAC}#{SE} - )/xno) do - if IAC == $1 # handle escaped IAC characters - IAC - elsif AYT == $1 # respond to "IAC AYT" (are you there) - self.write("nobody here but us pigeons" + EOL) - '' - elsif DO[0] == $1[0] # respond to "IAC DO x" - if OPT_BINARY[0] == $1[1] - @telnet_option["BINARY"] = true - self.write(IAC + WILL + OPT_BINARY) - else - self.write(IAC + WONT + $1[1..1]) - end - '' - elsif DONT[0] == $1[0] # respond to "IAC DON'T x" with "IAC WON'T x" - self.write(IAC + WONT + $1[1..1]) - '' - elsif WILL[0] == $1[0] # respond to "IAC WILL x" - if OPT_BINARY[0] == $1[1] - self.write(IAC + DO + OPT_BINARY) - elsif OPT_ECHO[0] == $1[1] - self.write(IAC + DO + OPT_ECHO) - elsif OPT_SGA[0] == $1[1] - @telnet_option["SGA"] = true - self.write(IAC + DO + OPT_SGA) - else - self.write(IAC + DONT + $1[1..1]) - end - '' - elsif WONT[0] == $1[0] # respond to "IAC WON'T x" - if OPT_ECHO[0] == $1[1] - self.write(IAC + DONT + OPT_ECHO) - elsif OPT_SGA[0] == $1[1] - @telnet_option["SGA"] = false - self.write(IAC + DONT + OPT_SGA) - else - self.write(IAC + DONT + $1[1..1]) - end - '' - else - '' - end - end - end # preprocess - - # Read data from the host until a certain sequence is matched. - # - # If a block is given, the received data will be yielded as it - # is read in (not necessarily all in one go), or nil if EOF - # occurs before any data is received. Whether a block is given - # or not, all data read will be returned in a single string, or again - # nil if EOF occurs before any data is received. Note that - # received data includes the matched sequence we were looking for. - # - # +options+ can be either a regular expression or a hash of options. - # If a regular expression, this specifies the data to wait for. - # If a hash, this can specify the following options: - # - # Match:: a regular expression, specifying the data to wait for. - # Prompt:: as for Match; used only if Match is not specified. - # String:: as for Match, except a string that will be converted - # into a regular expression. Used only if Match and - # Prompt are not specified. - # Timeout:: the number of seconds to wait for data from the host - # before raising a TimeoutError. If set to false, - # no timeout will occur. If not specified, the - # Timeout option value specified when this instance - # was created will be used, or, failing that, the - # default value of 10 seconds. - # Waittime:: the number of seconds to wait after matching against - # the input data to see if more data arrives. If more - # data arrives within this time, we will judge ourselves - # not to have matched successfully, and will continue - # trying to match. If not specified, the Waittime option - # value specified when this instance was created will be - # used, or, failing that, the default value of 0 seconds, - # which means not to wait for more input. - # FailEOF:: if true, when the remote end closes the connection then an - # 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"] - fail_eof = @options["FailEOF"] - - if options.kind_of?(Hash) - prompt = if options.has_key?("Match") - options["Match"] - elsif options.has_key?("Prompt") - options["Prompt"] - elsif options.has_key?("String") - Regexp.new( Regexp.quote(options["String"]) ) - end - time_out = options["Timeout"] if options.has_key?("Timeout") - waittime = options["Waittime"] if options.has_key?("Waittime") - fail_eof = options["FailEOF"] if options.has_key?("FailEOF") - else - prompt = options - end - - if time_out == false - time_out = nil - end - - line = '' - buf = '' - rest = '' - until(prompt === line and not IO::select([@sock], nil, nil, waittime)) - unless IO::select([@sock], nil, nil, time_out) - raise TimeoutError, "timed out while waiting for more data" - end - begin - c = @sock.readpartial(1024 * 1024) - @dumplog.log_dump('<', c) if @options.has_key?("Dump_log") - if @options["Telnetmode"] - c = rest + c - if Integer(c.rindex(/#{IAC}#{SE}/no) || 0) < - Integer(c.rindex(/#{IAC}#{SB}/no) || 0) - buf = preprocess(c[0 ... c.rindex(/#{IAC}#{SB}/no)]) - rest = c[c.rindex(/#{IAC}#{SB}/no) .. -1] - elsif pt = c.rindex(/#{IAC}[^#{IAC}#{AO}#{AYT}#{DM}#{IP}#{NOP}]?\z/no) || - c.rindex(/\r\z/no) - buf = preprocess(c[0 ... pt]) - rest = c[pt .. -1] - else - buf = preprocess(c) - rest = '' - end - else - # Not Telnetmode. - # - # We cannot use preprocess() on this data, because that - # method makes some Telnetmode-specific assumptions. - buf = rest + c - rest = '' - unless @options["Binmode"] - if pt = buf.rindex(/\r\z/no) - buf = buf[0 ... pt] - rest = buf[pt .. -1] - end - buf.gsub!(/#{EOL}/no, "\n") - end - end - @log.print(buf) if @options.has_key?("Output_log") - line += buf - yield buf if block_given? - rescue EOFError # End of file reached - raise if fail_eof - if line == '' - line = nil - yield nil if block_given? - end - break - end - end - line - end - - # Write +string+ to the host. - # - # Does not perform any conversions on +string+. Will log +string+ to the - # dumplog, if the Dump_log option is set. - def write(string) - length = string.length - while 0 < length - IO::select(nil, [@sock]) - @dumplog.log_dump('>', string[-length..-1]) if @options.has_key?("Dump_log") - length -= @sock.syswrite(string[-length..-1]) - end - end - - # Sends a string to the host. - # - # This does _not_ automatically append a newline to the string. Embedded - # newlines may be converted and telnet command sequences escaped - # depending upon the values of telnetmode, binmode, and telnet options - # set by the host. - def print(string) - string = string.gsub(/#{IAC}/no, IAC + IAC) if @options["Telnetmode"] - - if @options["Binmode"] - self.write(string) - else - if @telnet_option["BINARY"] and @telnet_option["SGA"] - # IAC WILL SGA IAC DO BIN send EOL --> CR - self.write(string.gsub(/\n/n, CR)) - elsif @telnet_option["SGA"] - # IAC WILL SGA send EOL --> CR+NULL - self.write(string.gsub(/\n/n, CR + NULL)) - else - # NONE send EOL --> CR+LF - self.write(string.gsub(/\n/n, EOL)) - end - end - end - - # Sends a string to the host. - # - # Same as #print(), but appends a newline to the string. - def puts(string) - self.print(string + "\n") - end - - # Send a command to the host. - # - # More exactly, sends a string to the host, and reads in all received - # data until is sees the prompt or other matched sequence. - # - # If a block is given, the received data will be yielded to it as - # it is read in. Whether a block is given or not, the received data - # will be return as a string. Note that the received data includes - # the prompt and in most cases the host's echo of our command. - # - # +options+ is either a String, specified the string or command to - # send to the host; or it is a hash of options. If a hash, the - # following options can be specified: - # - # String:: the command or other string to send to the host. - # Match:: a regular expression, the sequence to look for in - # the received data before returning. If not specified, - # the Prompt option value specified when this instance - # was created will be used, or, failing that, the default - # prompt of /[$%#>] \z/n. - # Timeout:: the seconds to wait for data from the host before raising - # a Timeout error. If not specified, the Timeout option - # value specified when this instance was created will be - # used, or, failing that, the default value of 10 seconds. - # - # The command or other string will have the newline sequence appended - # to it. - def cmd(options) # :yield: recvdata - match = @options["Prompt"] - time_out = @options["Timeout"] - fail_eof = @options["FailEOF"] - - if options.kind_of?(Hash) - string = options["String"] - match = options["Match"] if options.has_key?("Match") - time_out = options["Timeout"] if options.has_key?("Timeout") - fail_eof = options["FailEOF"] if options.has_key?("FailEOF") - else - string = options - end - - self.puts(string) - if block_given? - waitfor({"Prompt" => match, "Timeout" => time_out, "FailEOF" => fail_eof}){|c| yield c } - else - waitfor({"Prompt" => match, "Timeout" => time_out, "FailEOF" => fail_eof}) - end - end - - # Login to the host with a given username and password. - # - # The username and password can either be provided as two string - # arguments in that order, or as a hash with keys "Name" and - # "Password". - # - # This method looks for the strings "login" and "Password" from the - # host to determine when to send the username and password. If the - # login sequence does not follow this pattern (for instance, you - # are connecting to a service other than telnet), you will need - # to handle login yourself. - # - # The password can be omitted, either by only - # provided one String argument, which will be used as the username, - # or by providing a has that has no "Password" key. In this case, - # the method will not look for the "Password:" prompt; if it is - # sent, it will have to be dealt with by later calls. - # - # The method returns all data received during the login process from - # the host, including the echoed username but not the password (which - # the host should not echo). If a block is passed in, this received - # data is also yielded to the block as it is received. - def login(options, password = nil) # :yield: recvdata - login_prompt = /[Ll]ogin[: ]*\z/n - password_prompt = /[Pp]ass(?:word|phrase)[: ]*\z/n - if options.kind_of?(Hash) - username = options["Name"] - password = options["Password"] - login_prompt = options["LoginPrompt"] if options["LoginPrompt"] - password_prompt = options["PasswordPrompt"] if options["PasswordPrompt"] - else - username = options - end - - if block_given? - line = waitfor(login_prompt){|c| yield c } - if password - line += cmd({"String" => username, - "Match" => password_prompt}){|c| yield c } - line += cmd(password){|c| yield c } - else - line += cmd(username){|c| yield c } - end - else - line = waitfor(login_prompt) - if password - line += cmd({"String" => username, - "Match" => password_prompt}) - line += cmd(password) - else - line += cmd(username) - end - end - line - end - - end # class Telnet -end # module Net - diff --git a/Src/StdLib/ruby/1.9.1/profile.rb b/Src/StdLib/ruby/1.9.1/profile.rb deleted file mode 100644 index f93903891..000000000 --- a/Src/StdLib/ruby/1.9.1/profile.rb +++ /dev/null @@ -1,10 +0,0 @@ -require 'profiler' - -RubyVM::InstructionSequence.compile_option = { - :trace_instruction => true, - :specialized_instruction => false -} -END { - Profiler__::print_profile(STDERR) -} -Profiler__::start_profile diff --git a/Src/StdLib/ruby/1.9.1/profiler.rb b/Src/StdLib/ruby/1.9.1/profiler.rb deleted file mode 100644 index 44fd3eba2..000000000 --- a/Src/StdLib/ruby/1.9.1/profiler.rb +++ /dev/null @@ -1,59 +0,0 @@ -module Profiler__ - # internal values - @@start = @@stack = @@map = nil - PROFILE_PROC = proc{|event, file, line, id, binding, klass| - case event - when "call", "c-call" - now = Process.times[0] - @@stack.push [now, 0.0] - when "return", "c-return" - now = Process.times[0] - key = [klass, id] - if tick = @@stack.pop - data = (@@map[key] ||= [0, 0.0, 0.0, key]) - data[0] += 1 - cost = now - tick[0] - data[1] += cost - data[2] += cost - tick[1] - @@stack[-1][1] += cost if @@stack[-1] - end - end - } -module_function - def start_profile - @@start = Process.times[0] - @@stack = [] - @@map = {} - set_trace_func PROFILE_PROC - end - def stop_profile - set_trace_func nil - end - def print_profile(f) - stop_profile - total = Process.times[0] - @@start - if total == 0 then total = 0.01 end - data = @@map.values - data = data.sort_by{|x| -x[2]} - sum = 0 - f.printf " %% cumulative self self total\n" - f.printf " time seconds seconds calls ms/call ms/call name\n" - for d in data - sum += d[2] - f.printf "%6.2f %8.2f %8.2f %8d ", d[2]/total*100, sum, d[2], d[0] - f.printf "%8.2f %8.2f %s\n", d[2]*1000/d[0], d[1]*1000/d[0], get_name(*d[3]) - end - f.printf "%6.2f %8.2f %8.2f %8d ", 0.0, total, 0.0, 1 # ??? - f.printf "%8.2f %8.2f %s\n", 0.0, total*1000, "#toplevel" # ??? - end - def get_name(klass, id) - name = klass.to_s || "" - if klass.kind_of? Class - name += "#" - else - name += "." - end - name + id.id2name - end - private :get_name -end diff --git a/Src/StdLib/ruby/1.9.1/rational.rb b/Src/StdLib/ruby/1.9.1/rational.rb deleted file mode 100644 index eb4001926..000000000 --- a/Src/StdLib/ruby/1.9.1/rational.rb +++ /dev/null @@ -1,14 +0,0 @@ -# :enddoc: - -warn('lib/rational.rb is deprecated') if $VERBOSE - -class Integer - - alias quof fdiv - alias rdiv quo - - alias power! ** unless method_defined? :power! - alias rpower ** - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc.rb b/Src/StdLib/ruby/1.9.1/rdoc.rb deleted file mode 100644 index 938fb4129..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc.rb +++ /dev/null @@ -1,421 +0,0 @@ -$DEBUG_RDOC = nil - -# :main: README.txt - -## -# = \RDoc - Ruby Documentation System -# -# This package contains RDoc and RDoc::Markup. RDoc is an application that -# produces documentation for one or more Ruby source files. It works similarly -# to JavaDoc, parsing the source, and extracting the definition for classes, -# modules, and methods (along with includes and requires). It associates with -# these optional documentation contained in the immediately preceding comment -# block, and then renders the result using a pluggable output formatter. -# RDoc::Markup is a library that converts plain text into various output -# formats. The markup library is used to interpret the comment blocks that -# RDoc uses to document methods, classes, and so on. -# -# == Roadmap -# -# * If you want to use RDoc to create documentation for your Ruby source files, -# read on. -# * If you want to generate documentation for extensions written in C, see -# RDoc::Parser::C -# * If you want to drive RDoc programmatically, see RDoc::RDoc. -# * If you want to use the library to format text blocks into HTML, have a look -# at RDoc::Markup. -# * If you want to try writing your own HTML output template, see -# RDoc::Generator::HTML -# -# == Summary -# -# Once installed, you can create documentation using the +rdoc+ command -# -# % rdoc [options] [names...] -# -# For an up-to-date option summary, type -# -# % rdoc --help -# -# A typical use might be to generate documentation for a package of Ruby -# source (such as RDoc itself). -# -# % rdoc -# -# This command generates documentation for all the Ruby and C source -# files in and below the current directory. These will be stored in a -# documentation tree starting in the subdirectory +doc+. -# -# You can make this slightly more useful for your readers by having the -# index page contain the documentation for the primary file. In our -# case, we could type -# -# % rdoc --main rdoc.rb -# -# You'll find information on the various formatting tricks you can use -# in comment blocks in the documentation this generates. -# -# RDoc uses file extensions to determine how to process each file. File names -# ending +.rb+ and +.rbw+ are assumed to be Ruby source. Files -# ending +.c+ are parsed as C files. All other files are assumed to -# contain just Markup-style markup (with or without leading '#' comment -# markers). If directory names are passed to RDoc, they are scanned -# recursively for C and Ruby source files only. -# -# == \Options -# -# rdoc can be passed a variety of command-line options. In addition, -# options can be specified via the +RDOCOPT+ environment variable, which -# functions similarly to the +RUBYOPT+ environment variable. -# -# % export RDOCOPT="-S" -# -# will make rdoc default to inline method source code. Command-line options -# always will override those in +RDOCOPT+. -# -# Run: -# -# rdoc --help -# -# for full details on rdoc's options. -# -# == Documenting Source Code -# -# Comment blocks can be written fairly naturally, either using # on -# successive lines of the comment, or by including the comment in -# a =begin/=end block. If you use the latter form, the =begin line must be -# flagged with an RDoc tag: -# -# =begin rdoc -# Documentation to be processed by RDoc. -# -# ... -# =end -# -# RDoc stops processing comments if it finds a comment line containing -# a --. This can be used to separate external from internal -# comments, or to stop a comment being associated with a method, class, or -# module. Commenting can be turned back on with a line that starts with a -# ++. -# -# ## -# # Extract the age and calculate the date-of-birth. -# #-- -# # FIXME: fails if the birthday falls on February 29th -# #++ -# # The DOB is returned as a Time object. -# -# def get_dob(person) -# # ... -# end -# -# Names of classes, files, and any method names containing an -# underscore or preceded by a hash character are automatically hyperlinked -# from comment text to their description. -# -# Method parameter lists are extracted and displayed with the method -# description. If a method calls +yield+, then the parameters passed to yield -# will also be displayed: -# -# def fred -# ... -# yield line, address -# -# This will get documented as: -# -# fred() { |line, address| ... } -# -# You can override this using a comment containing ':yields: ...' immediately -# after the method definition -# -# def fred # :yields: index, position -# # ... -# -# yield line, address -# -# which will get documented as -# -# fred() { |index, position| ... } -# -# +:yields:+ is an example of a documentation directive. These appear -# immediately after the start of the document element they are modifying. -# -# RDoc automatically cross-references words with underscores or camel-case. -# To suppress cross-references, prefix the word with a \\ character. To -# include special characters like "\\n", you'll need to use two \\ -# characters like "\\\\\\n". -# -# == \Markup -# -# * The markup engine looks for a document's natural left margin. This is -# used as the initial margin for the document. -# -# * Consecutive lines starting at this margin are considered to be a -# paragraph. -# -# * If a paragraph starts with a "*", "-", or with ".", then it is -# taken to be the start of a list. The margin in increased to be the first -# non-space following the list start flag. Subsequent lines should be -# indented to this new margin until the list ends. For example: -# -# * this is a list with three paragraphs in -# the first item. This is the first paragraph. -# -# And this is the second paragraph. -# -# 1. This is an indented, numbered list. -# 2. This is the second item in that list -# -# This is the third conventional paragraph in the -# first list item. -# -# * This is the second item in the original list -# -# * You can also construct labeled lists, sometimes called description -# or definition lists. Do this by putting the label in square brackets -# and indenting the list body: -# -# [cat] a small furry mammal -# that seems to sleep a lot -# -# [ant] a little insect that is known -# to enjoy picnics -# -# A minor variation on labeled lists uses two colons to separate the -# label from the list body: -# -# cat:: a small furry mammal -# that seems to sleep a lot -# -# ant:: a little insect that is known -# to enjoy picnics -# -# This latter style guarantees that the list bodies' left margins are -# aligned: think of them as a two column table. -# -# * Any line that starts to the right of the current margin is treated -# as verbatim text. This is useful for code listings. The example of a -# list above is also verbatim text. -# -# * A line starting with an equals sign (=) is treated as a -# heading. Level one headings have one equals sign, level two headings -# have two,and so on. -# -# * A line starting with three or more hyphens (at the current indent) -# generates a horizontal rule. The more hyphens, the thicker the rule -# (within reason, and if supported by the output device) -# -# * You can use markup within text (except verbatim) to change the -# appearance of parts of that text. Out of the box, RDoc::Markup -# supports word-based and general markup. -# -# Word-based markup uses flag characters around individual words: -# -# [\*word*] displays word in a *bold* font -# [\_word_] displays word in an _emphasized_ font -# [\+word+] displays word in a +code+ font -# -# General markup affects text between a start delimiter and and end -# delimiter. Not surprisingly, these delimiters look like HTML markup. -# -# [\text...] displays word in a *bold* font -# [\text...] displays word in an _emphasized_ font -# [\text...] displays word in an italicized font -# [\text...\] displays word in a +code+ font -# -# Unlike conventional Wiki markup, general markup can cross line -# boundaries. You can turn off the interpretation of markup by -# preceding the first character with a backslash. This only works for -# simple markup, not HTML-style markup. -# -# * Hyperlinks to the web starting http:, mailto:, ftp:, or www. are -# recognized. An HTTP url that references an external image file is -# converted into an inline \. Hyperlinks starting 'link:' are -# assumed to refer to local files whose path is relative to the --op -# directory. -# -# Hyperlinks can also be of the form label[url], in which -# case the label is used in the displayed text, and +url+ is -# used as the target. If +label+ contains multiple words, -# put it in braces: {multi word label}[url]. -# -# Example hyperlinks: -# -# link:RDoc.html -# http://rdoc.rubyforge.org -# mailto:user@example.com -# {RDoc Documentation}[http://rdoc.rubyforge.org] -# {RDoc Markup}[link:RDoc/Markup.html] -# -# == Directives -# -# [+:nodoc:+ / +:nodoc:+ all] -# This directive prevents documentation for the element from -# being generated. For classes and modules, the methods, aliases, -# constants, and attributes directly within the affected class or -# module also will be omitted. By default, though, modules and -# classes within that class of module _will_ be documented. This is -# turned off by adding the +all+ modifier. -# -# module MyModule # :nodoc: -# class Input -# end -# end -# -# module OtherModule # :nodoc: all -# class Output -# end -# end -# -# In the above code, only class MyModule::Input will be documented. -# The +:nodoc:+ directive is global across all files for the class or module -# to which it applies, so use +:stopdoc:+/+:startdoc:+ to suppress -# documentation only for a particular set of methods, etc. -# -# [+:doc:+] -# Forces a method or attribute to be documented even if it wouldn't be -# otherwise. Useful if, for example, you want to include documentation of a -# particular private method. -# -# [+:notnew:+] -# Only applicable to the +initialize+ instance method. Normally RDoc -# assumes that the documentation and parameters for +initialize+ are -# actually for the +new+ method, and so fakes out a +new+ for the class. -# The +:notnew:+ modifier stops this. Remember that +initialize+ is private, -# so you won't see the documentation unless you use the +-a+ command line -# option. -# -# Comment blocks can contain other directives: -# -# [:section: title] -# Starts a new section in the output. The title following +:section:+ is -# used as the section heading, and the remainder of the comment containing -# the section is used as introductory text. Subsequent methods, aliases, -# attributes, and classes will be documented in this section. A :section: -# comment block may have one or more lines before the :section: directive. -# These will be removed, and any identical lines at the end of the block are -# also removed. This allows you to add visual cues such as: -# -# # ---------------------------------------- -# # :section: My Section -# # This is the section that I wrote. -# # See it glisten in the noon-day sun. -# # ---------------------------------------- -# -# [+:call-seq:+] -# Lines up to the next blank line in the comment are treated as the method's -# calling sequence, overriding the default parsing of method parameters and -# yield arguments. -# -# [+:include:+ _filename_] -# \Include the contents of the named file at this point. The file will be -# searched for in the directories listed by the +--include+ option, or in -# the current directory by default. The contents of the file will be -# shifted to have the same indentation as the ':' at the start of -# the :include: directive. -# -# [+:title:+ _text_] -# Sets the title for the document. Equivalent to the --title -# command line parameter. (The command line parameter overrides any :title: -# directive in the source). -# -# [+:enddoc:+] -# Document nothing further at the current level. -# -# [+:main:+ _name_] -# Equivalent to the --main command line parameter. -# -# [+:stopdoc:+ / +:startdoc:+] -# Stop and start adding new documentation elements to the current container. -# For example, if a class has a number of constants that you don't want to -# document, put a +:stopdoc:+ before the first, and a +:startdoc:+ after the -# last. If you don't specify a +:startdoc:+ by the end of the container, -# disables documentation for the entire class or module. -# -# Further directives can be found in RDoc::Parser::Ruby and RDoc::Parser::C -# -# == Other stuff -# -# RDoc is currently being maintained by Eric Hodel -# -# Dave Thomas is the original author of RDoc. -# -# == Credits -# -# * The Ruby parser in rdoc/parse.rb is based heavily on the outstanding -# work of Keiju ISHITSUKA of Nippon Rational Inc, who produced the Ruby -# parser for irb and the rtags package. -# -# * Charset patch from MoonWolf. -# -# * Rich Kilmer wrote the kilmer.rb output template. -# -# * Dan Brickley led the design of the RDF format. -# -# == License -# -# RDoc is Copyright (c) 2001-2003 Dave Thomas, The Pragmatic Programmers. It -# is free software, and may be redistributed under the terms specified -# in the README file of the Ruby distribution. -# -# == Warranty -# -# This software is provided "as is" and without any express or implied -# warranties, including, without limitation, the implied warranties of -# merchantibility and fitness for a particular purpose. - -module RDoc - - ## - # Exception thrown by any rdoc error. - - class Error < RuntimeError; end - - def self.const_missing const_name # :nodoc: - if const_name.to_s == 'RDocError' then - warn "RDoc::RDocError is deprecated" - return Error - end - - super - end - - ## - # RDoc version you are using - - VERSION = '2.5.8' - - ## - # Name of the dotfile that contains the description of files to be processed - # in the current directory - - DOT_DOC_FILENAME = ".document" - - ## - # General RDoc modifiers - - GENERAL_MODIFIERS = %w[nodoc].freeze - - ## - # RDoc modifiers for classes - - CLASS_MODIFIERS = GENERAL_MODIFIERS - - ## - # RDoc modifiers for attributes - - ATTR_MODIFIERS = GENERAL_MODIFIERS - - ## - # RDoc modifiers for constants - - CONSTANT_MODIFIERS = GENERAL_MODIFIERS - - ## - # RDoc modifiers for methods - - METHOD_MODIFIERS = GENERAL_MODIFIERS + - %w[arg args yield yields notnew not-new not_new doc] - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/alias.rb b/Src/StdLib/ruby/1.9.1/rdoc/alias.rb deleted file mode 100644 index 6f4bfc1b5..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/alias.rb +++ /dev/null @@ -1,54 +0,0 @@ -require 'rdoc/code_object' - -## -# Represent an alias, which is an old_name/new_name pair associated with a -# particular context - -class RDoc::Alias < RDoc::CodeObject - - ## - # Allow comments to be overridden - - attr_writer :comment - - ## - # Aliased name - - attr_accessor :new_name - - ## - # Aliasee's name - - attr_accessor :old_name - - ## - # Source file token stream - - attr_accessor :text - - ## - # Creates a new Alias with a token stream of +text+ that aliases +old_name+ - # to +new_name+ and has +comment+ - - def initialize(text, old_name, new_name, comment) - super() - @text = text - @old_name = old_name - @new_name = new_name - self.comment = comment - end - - def inspect # :nodoc: - parent_name = parent ? parent.name : '(unknown)' - "#<%s:0x%x %s.alias_method %s, %s>" % [ - self.class, object_id, - parent_name, @old_name, @new_name, - ] - end - - def to_s # :nodoc: - "alias: #{self.old_name} -> #{self.new_name}\n#{self.comment}" - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/anon_class.rb b/Src/StdLib/ruby/1.9.1/rdoc/anon_class.rb deleted file mode 100644 index a6d64c44b..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/anon_class.rb +++ /dev/null @@ -1,10 +0,0 @@ -require 'rdoc/class_module' - -## -# An anonymous class like: -# -# c = Class.new do end - -class RDoc::AnonClass < RDoc::ClassModule -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/any_method.rb b/Src/StdLib/ruby/1.9.1/rdoc/any_method.rb deleted file mode 100644 index f7df6cfda..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/any_method.rb +++ /dev/null @@ -1,290 +0,0 @@ -require 'rdoc/code_object' -require 'rdoc/tokenstream' - -## -# AnyMethod is the base class for objects representing methods - -class RDoc::AnyMethod < RDoc::CodeObject - - MARSHAL_VERSION = 1 # :nodoc: - - include Comparable - - ## - # Method name - - attr_writer :name - - ## - # public, protected, private - - attr_accessor :visibility - - ## - # Parameters yielded by the called block - - attr_accessor :block_params - - ## - # Don't rename \#initialize to \::new - - attr_accessor :dont_rename_initialize - - ## - # Is this a singleton method? - - attr_accessor :singleton - - ## - # Source file token stream - - attr_reader :text - - ## - # Array of other names for this method - - attr_reader :aliases - - ## - # The method we're aliasing - - attr_accessor :is_alias_for - - ## - # Parameters for this method - - attr_accessor :params - - ## - # Different ways to call this method - - attr_accessor :call_seq - - include RDoc::TokenStream - - def initialize(text, name) - super() - - @text = text - @name = name - - @aliases = [] - @block_params = nil - @call_seq = nil - @dont_rename_initialize = false - @is_alias_for = nil - @params = nil - @parent_name = nil - @singleton = nil - @token_stream = nil - @visibility = :public - end - - ## - # Order by #singleton then #name - - def <=>(other) - [@singleton ? 0 : 1, @name] <=> [other.singleton ? 0 : 1, other.name] - end - - ## - # Adds +method+ as an alias for this method - - def add_alias(method) - @aliases << method - end - - ## - # HTML fragment reference for this method - - def aref - type = singleton ? 'c' : 'i' - - "method-#{type}-#{CGI.escape name}" - end - - ## - # The call_seq or the param_seq with method name, if there is no call_seq. - # - # Use this for displaying a method's argument lists. - - def arglists - if @call_seq then - @call_seq - elsif @params then - "#{name}#{param_seq}" - end - end - - ## - # HTML id-friendly method name - - def html_name - @name.gsub(/[^a-z]+/, '-') - end - - def inspect # :nodoc: - alias_for = @is_alias_for ? " (alias for #{@is_alias_for.name})" : nil - "#<%s:0x%x %s (%s)%s>" % [ - self.class, object_id, - full_name, - visibility, - alias_for, - ] - end - - ## - # Full method name including namespace - - def full_name - @full_name ||= "#{@parent ? @parent.full_name : '(unknown)'}#{pretty_name}" - end - - ## - # Dumps this AnyMethod for use by ri. See also #marshal_load - - def marshal_dump - aliases = @aliases.map do |a| - [a.full_name, parse(a.comment)] - end - - [ MARSHAL_VERSION, - @name, - full_name, - @singleton, - @visibility, - parse(@comment), - @call_seq, - @block_params, - aliases, - @params, - ] - end - - ## - # Loads this AnyMethod from +array+. For a loaded AnyMethod the following - # methods will return cached values: - # - # * #full_name - # * #parent_name - - def marshal_load(array) - @dont_rename_initialize = nil - @is_alias_for = nil - @token_stream = nil - @aliases = [] - - @name = array[1] - @full_name = array[2] - @singleton = array[3] - @visibility = array[4] - @comment = array[5] - @call_seq = array[6] - @block_params = array[7] - @params = array[9] - - @parent_name = if @full_name =~ /#/ then - $` - else - name = @full_name.split('::') - name.pop - name.join '::' - end - - array[8].each do |new_name, comment| - add_alias RDoc::Alias.new(nil, @name, new_name, comment) - end - end - - ## - # Method name - - def name - return @name if @name - - @name = @call_seq[/^.*?\.(\w+)/, 1] || @call_seq if @call_seq - end - - ## - # Pretty parameter list for this method - - def param_seq - params = @params.gsub(/\s*\#.*/, '') - params = params.tr("\n", " ").squeeze(" ") - params = "(#{params})" unless params[0] == ?( - - if @block_params then - # If this method has explicit block parameters, remove any explicit - # &block - params.sub!(/,?\s*&\w+/, '') - - block = @block_params.gsub(/\s*\#.*/, '') - block = block.tr("\n", " ").squeeze(" ") - if block[0] == ?( - block.sub!(/^\(/, '').sub!(/\)/, '') - end - params << " { |#{block}| ... }" - end - - params - end - - ## - # Name of our parent with special handling for un-marshaled methods - - def parent_name - @parent_name || super - end - - ## - # Path to this method - - def path - "#{@parent.path}##{aref}" - end - - ## - # Method name with class/instance indicator - - def pretty_name - "#{singleton ? '::' : '#'}#{@name}" - end - - def pretty_print q # :nodoc: - alias_for = @is_alias_for ? "alias for #{@is_alias_for.name}" : nil - - q.group 2, "[#{self.class.name} #{full_name} #{visibility}", "]" do - if alias_for then - q.breakable - q.text alias_for - end - - if text then - q.breakable - q.text "text:" - q.breakable - q.pp @text - end - - unless comment.empty? then - q.breakable - q.text "comment:" - q.breakable - q.pp @comment - end - end - end - - def to_s # :nodoc: - "#{self.class.name}: #{full_name} (#{@text})\n#{@comment}" - end - - ## - # Type of method (class or instance) - - def type - singleton ? 'class' : 'instance' - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/attr.rb b/Src/StdLib/ruby/1.9.1/rdoc/attr.rb deleted file mode 100644 index 035ab6872..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/attr.rb +++ /dev/null @@ -1,178 +0,0 @@ -require 'rdoc/code_object' - -## -# An attribute created by \#attr, \#attr_reader, \#attr_writer or -# \#attr_accessor - -class RDoc::Attr < RDoc::CodeObject - - MARSHAL_VERSION = 0 # :nodoc: - - ## - # Name of the attribute - - attr_accessor :name - - ## - # Is the attribute readable, writable or both? - - attr_accessor :rw - - ## - # Source file token stream - - attr_accessor :text - - ## - # public, protected, private - - attr_accessor :visibility - - def initialize(text, name, rw, comment) - super() - @text = text - @name = name - @rw = rw - @visibility = :public - self.comment = comment - end - - ## - # Attributes are ordered by name - - def <=>(other) - self.name <=> other.name - end - - ## - # Attributes are equal when their names and rw is identical - - def == other - self.class == other.class and - self.name == other.name and - self.rw == other.rw - end - - ## - # Returns nil, for duck typing with RDoc::AnyMethod - - def arglists - end - - ## - # Returns nil, for duck typing with RDoc::AnyMethod - - def block_params - end - - ## - # Returns nil, for duck typing with RDoc::AnyMethod - - def call_seq - end - - ## - # Partially bogus as Attr has no parent. For duck typing with - # RDoc::AnyMethod. - - def full_name - @full_name ||= "#{@parent ? @parent.full_name : '(unknown)'}##{name}" - end - - ## - # An HTML id-friendly representation of #name - - def html_name - @name.gsub(/[^a-z]+/, '-') - end - - def inspect # :nodoc: - attr = case rw - when 'RW' then :attr_accessor - when 'R' then :attr_reader - when 'W' then :attr_writer - else - " (#{rw})" - end - - "#<%s:0x%x %s.%s :%s>" % [ - self.class, object_id, - parent_name, attr, @name, - ] - end - - ## - # Dumps this Attr for use by ri. See also #marshal_load - - def marshal_dump - [ MARSHAL_VERSION, - @name, - full_name, - @rw, - @visibility, - parse(@comment), - ] - end - - ## - # Loads this AnyMethod from +array+. For a loaded AnyMethod the following - # methods will return cached values: - # - # * #full_name - # * #parent_name - - def marshal_load array - @name = array[1] - @full_name = array[2] - @rw = array[3] - @visibility = array[4] - @comment = array[5] - - @parent_name = @full_name - end - - ## - # Name of our parent with special handling for un-marshaled methods - - def parent_name - @parent_name || super - end - - ## - # For duck typing with RDoc::AnyMethod, returns nil - - def params - nil - end - - ## - # URL path for this attribute - - def path - "#{@parent.path}##{@name}" - end - - ## - # For duck typing with RDoc::AnyMethod - - def singleton - false - end - - def to_s # :nodoc: - "#{type} #{name}\n#{comment}" - end - - ## - # Returns attr_reader, attr_writer or attr_accessor as appropriate - - def type - case @rw - when 'RW' then 'attr_accessor' - when 'R' then 'attr_reader' - when 'W' then 'attr_writer' - end - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/class_module.rb b/Src/StdLib/ruby/1.9.1/rdoc/class_module.rb deleted file mode 100644 index ae1cc82fb..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/class_module.rb +++ /dev/null @@ -1,215 +0,0 @@ -require 'rdoc/context' - -## -# ClassModule is the base class for objects representing either a class or a -# module. - -class RDoc::ClassModule < RDoc::Context - - MARSHAL_VERSION = 0 # :nodoc: - - attr_accessor :diagram - - ## - # Creates a new ClassModule with +name+ with optional +superclass+ - - def initialize(name, superclass = 'Object') - @diagram = nil - @full_name = nil - @name = name - @superclass = superclass - super() - end - - ## - # Ancestors list for this ClassModule (abstract) - - def ancestors - raise NotImplementedError - end - - ## - # Appends +comment+ to the current comment, but separated by a rule. Works - # more like +=. - - def comment=(comment) - return if comment.empty? - - comment = "#{@comment}\n---\n#{normalize_comment comment}" unless - @comment.empty? - - super - end - - ## - # Finds a class or module with +name+ in this namespace or its descendents - - def find_class_named(name) - return self if full_name == name - return self if @name == name - - @classes.values.find do |klass| - next if klass == self - klass.find_class_named name - end - end - - ## - # Return the fully qualified name of this class or module - - def full_name - @full_name ||= if RDoc::ClassModule === @parent then - "#{@parent.full_name}::#{@name}" - else - @name - end - end - - ## - # 'module' or 'class' - - def type - module? ? 'module' : 'class' - end - - def marshal_dump # :nodoc: - attrs = attributes.sort.map do |attr| - [attr.name, attr.rw] - end - - method_types = methods_by_type.map do |type, visibilities| - visibilities = visibilities.map do |visibility, methods| - method_names = methods.map do |method| - method.name - end - - [visibility, method_names.uniq] - end - - [type, visibilities] - end - - [ MARSHAL_VERSION, - @name, - full_name, - @superclass, - parse(@comment), - attrs, - constants.map do |const| - [const.name, parse(const.comment)] - end, - includes.map do |incl| - [incl.name, parse(incl.comment)] - end, - method_types, - ] - end - - def marshal_load array # :nodoc: - initialize_methods_etc - @document_self = true - @done_documenting = false - @current_section = nil - - @name = array[1] - @full_name = array[2] - @superclass = array[3] - @comment = array[4] - - array[5].each do |name, rw| - add_attribute RDoc::Attr.new(nil, name, rw, nil) - end - - array[6].each do |name, comment| - add_constant RDoc::Constant.new(name, nil, comment) - end - - array[7].each do |name, comment| - add_include RDoc::Include.new(name, comment) - end - - array[8].each do |type, visibilities| - visibilities.each do |visibility, methods| - @visibility = visibility - - methods.each do |name| - method = RDoc::AnyMethod.new nil, name - method.singleton = true if type == 'class' - add_method method - end - end - end - end - - ## - # Merges +class_module+ into this ClassModule - - def merge class_module - comment = class_module.comment - - if comment then - document = parse @comment - - comment.parts.concat document.parts - - @comment = comment - end - - class_module.each_attribute do |attr| - if match = attributes.find { |a| a.name == attr.name } then - match.rw = [match.rw, attr.rw].compact.join - else - add_attribute attr - end - end - - class_module.each_constant do |const| - add_constant const - end - - class_module.each_include do |incl| - add_include incl - end - - class_module.each_method do |meth| - add_method meth - end - end - - ## - # Does this object represent a module? - - def module? - false - end - - ## - # Path to this class or module - - def path - http_url RDoc::RDoc.current.generator.class_dir - end - - ## - # Get the superclass of this class. Attempts to retrieve the superclass - # object, returns the name if it is not known. - - def superclass - RDoc::TopLevel.find_class_named_from(@superclass, parent) || @superclass - end - - ## - # Set the superclass of this class to +superclass+ - - def superclass=(superclass) - raise NoMethodError, "#{full_name} is a module" if module? - - @superclass = superclass if @superclass.nil? or @superclass == 'Object' - end - - def to_s # :nodoc: - "#{self.class}: #{full_name} #{@comment} #{super}" - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/code_object.rb b/Src/StdLib/ruby/1.9.1/rdoc/code_object.rb deleted file mode 100644 index 7a57fd41f..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/code_object.rb +++ /dev/null @@ -1,180 +0,0 @@ -require 'rdoc' -require 'rdoc/text' - -## -# Base class for the RDoc code tree. -# -# We contain the common stuff for contexts (which are containers) and other -# elements (methods, attributes and so on) -# -# Here's the tree of the CodeObject subclasses: -# -# * RDoc::Context -# * RDoc::TopLevel -# * RDoc::ClassModule -# * RDoc::AnonClass -# * RDoc::NormalClass -# * RDoc::NormalModule -# * RDoc::SingleClass -# * RDoc::AnyMethod -# * RDoc::GhostMethod -# * RDoc::MetaMethod -# * RDoc::Alias -# * RDoc::Attr -# * RDoc::Constant -# * RDoc::Require -# * RDoc::Include - -class RDoc::CodeObject - - include RDoc::Text - - ## - # Our comment - - attr_reader :comment - - ## - # Do we document our children? - - attr_reader :document_children - - ## - # Do we document ourselves? - - attr_reader :document_self - - ## - # Are we done documenting (ie, did we come across a :enddoc:)? - - attr_accessor :done_documenting - - ## - # Force documentation of this CodeObject - - attr_accessor :force_documentation - - ## - # Hash of arbitrary metadata for this CodeObject - - attr_reader :metadata - - ## - # Our parent CodeObject - - attr_accessor :parent - - ## - # Which section are we in - - attr_accessor :section - - ## - # We are the model of the code, but we know that at some point we will be - # worked on by viewers. By implementing the Viewable protocol, viewers can - # associated themselves with these objects. - - attr_accessor :viewer - - ## - # Creates a new CodeObject that will document itself and its children - - def initialize - @metadata = {} - @comment = '' - - @document_children = true - @document_self = true - @done_documenting = false - @force_documentation = false - - @parent = nil - end - - ## - # Replaces our comment with +comment+, unless it is empty. - - def comment=(comment) - @comment = case comment - when NilClass then '' - when RDoc::Markup::Document then comment - else - if comment and not comment.empty? then - normalize_comment comment - else - @comment - end - end - end - - ## - # Enables or disables documentation of this CodeObject's children. Calls - # remove_classes_and_modules when disabling. - - def document_children=(document_children) - @document_children = document_children - remove_classes_and_modules unless document_children - end - - ## - # Enables or disables documentation of this CodeObject. Calls - # remove_methods_etc when disabling. - - def document_self=(document_self) - @document_self = document_self - remove_methods_etc unless document_self - end - - ## - # Does this class have a comment with content or is document_self false. - - def documented? - !(@document_self and @comment.empty?) - end - - ## - # File name of our parent - - def parent_file_name - @parent ? @parent.base_name : '(unknown)' - end - - ## - # Name of our parent - - def parent_name - @parent ? @parent.full_name : '(unknown)' - end - - ## - # Callback called upon disabling documentation of children. See - # #document_children= - - def remove_classes_and_modules - end - - ## - # Callback called upon disabling documentation of ourself. See - # #document_self= - - def remove_methods_etc - end - - ## - # Enable capture of documentation - - def start_doc - @document_self = true - @document_children = true - end - - ## - # Disable capture of documentation - - def stop_doc - @document_self = false - @document_children = false - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/code_objects.rb b/Src/StdLib/ruby/1.9.1/rdoc/code_objects.rb deleted file mode 100644 index 6dd3b4f79..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/code_objects.rb +++ /dev/null @@ -1,23 +0,0 @@ -# We represent the various high-level code constructs that appear in Ruby -# programs: classes, modules, methods, and so on. - -require 'rdoc/code_object' -require 'rdoc/context' -require 'rdoc/top_level' - -require 'rdoc/class_module' -require 'rdoc/normal_class' -require 'rdoc/normal_module' -require 'rdoc/anon_class' -require 'rdoc/single_class' - -require 'rdoc/any_method' -require 'rdoc/alias' -require 'rdoc/ghost_method' -require 'rdoc/meta_method' - -require 'rdoc/attr' -require 'rdoc/constant' -require 'rdoc/require' -require 'rdoc/include' - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/constant.rb b/Src/StdLib/ruby/1.9.1/rdoc/constant.rb deleted file mode 100644 index 2fb01ceed..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/constant.rb +++ /dev/null @@ -1,58 +0,0 @@ -require 'rdoc/code_object' - -## -# A constant - -class RDoc::Constant < RDoc::CodeObject - - ## - # The constant's name - - attr_accessor :name - - ## - # The constant's value - - attr_accessor :value - - ## - # Creates a new constant with +name+, +value+ and +comment+ - - def initialize(name, value, comment) - super() - @name = name - @value = value - self.comment = comment - end - - ## - # Constants are ordered by name - - def <=> other - return unless self.class === other - - [parent_name, name] <=> [other.parent_name, other.name] - end - - def == other - self.class == other.class and - @parent == other.parent and - @name == other.name - end - - def inspect # :nodoc: - "#<%s:0x%x %s::%s>" % [ - self.class, object_id, - parent_name, @name, - ] - end - - ## - # Path to this constant - - def path - "#{@parent.path}##{@name}" - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/context.rb b/Src/StdLib/ruby/1.9.1/rdoc/context.rb deleted file mode 100644 index 4abd5fe62..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/context.rb +++ /dev/null @@ -1,767 +0,0 @@ -require 'rdoc/code_object' - -## -# A Context is something that can hold modules, classes, methods, attributes, -# aliases, requires, and includes. Classes, modules, and files are all -# Contexts. - -class RDoc::Context < RDoc::CodeObject - - include Comparable - - ## - # Types of methods - - TYPES = %w[class instance] - - ## - # Method visibilities - - VISIBILITIES = [:public, :protected, :private] - - ## - # Aliased methods - - attr_reader :aliases - - ## - # attr* methods - - attr_reader :attributes - - ## - # Constants defined - - attr_reader :constants - - ## - # Current section of documentation - - attr_reader :current_section - - ## - # Files this context is found in - - attr_reader :in_files - - ## - # Modules this context includes - - attr_reader :includes - - ## - # Methods defined in this context - - attr_reader :method_list - - ## - # Name of this class excluding namespace. See also full_name - - attr_reader :name - - ## - # Files this context requires - - attr_reader :requires - - ## - # Sections in this context - - attr_reader :sections - - ## - # Aliases that haven't been resolved to a method - - attr_accessor :unmatched_alias_lists - - ## - # Current visibility of this context - - attr_reader :visibility - - ## - # A per-comment section of documentation like: - # - # # :SECTION: The title - # # The body - - class Section - - ## - # Section comment - - attr_reader :comment - - ## - # Context this Section lives in - - attr_reader :parent - - ## - # Section sequence number (for linking) - - attr_reader :sequence - - ## - # Section title - - attr_reader :title - - @@sequence = "SEC00000" - - ## - # Creates a new section with +title+ and +comment+ - - def initialize(parent, title, comment) - @parent = parent - @title = title - - @@sequence.succ! - @sequence = @@sequence.dup - - set_comment comment - end - - ## - # Sections are equal when they have the same #sequence - - def ==(other) - self.class === other and @sequence == other.sequence - end - - def inspect # :nodoc: - "#<%s:0x%x %s %p>" % [ - self.class, object_id, - @sequence, title - ] - end - - ## - # 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 those lines again at the end and remove them. This lets us write - # - # # blah blah blah - # # - # # :SECTION: The title - # # The body - - def set_comment(comment) - return unless comment - - if comment =~ /^#[ \t]*:section:.*\n/ then - start = $` - rest = $' - - if start.empty? - @comment = rest - else - @comment = rest.sub(/#{start.chomp}\Z/, '') - end - else - @comment = comment - end - - @comment = nil if @comment.empty? - end - - end - - ## - # Creates an unnamed empty context with public visibility - - def initialize - super - - @in_files = [] - - @name ||= "unknown" - @comment ||= "" - @parent = nil - @visibility = :public - - @current_section = Section.new self, nil, nil - @sections = [@current_section] - - initialize_methods_etc - initialize_classes_and_modules - end - - ## - # Sets the defaults for classes and modules - - def initialize_classes_and_modules - @classes = {} - @modules = {} - end - - ## - # Sets the defaults for methods and so-forth - - def initialize_methods_etc - @method_list = [] - @attributes = [] - @aliases = [] - @requires = [] - @includes = [] - @constants = [] - - # This Hash maps a method name to a list of unmatched aliases (aliases of - # a method not yet encountered). - @unmatched_alias_lists = {} - end - - ## - # Contexts are sorted by full_name - - def <=>(other) - full_name <=> other.full_name - end - - ## - # Adds +an_alias+ that is automatically resolved - - def add_alias(an_alias) - meth = find_instance_method_named(an_alias.old_name) - - if meth then - add_alias_impl an_alias, meth - else - add_to @aliases, an_alias - unmatched_alias_list = @unmatched_alias_lists[an_alias.old_name] ||= [] - unmatched_alias_list.push an_alias - end - - an_alias - end - - ## - # Turns +an_alias+ into an AnyMethod that points to +meth+ - - def add_alias_impl(an_alias, meth) - new_meth = RDoc::AnyMethod.new an_alias.text, an_alias.new_name - new_meth.is_alias_for = meth - new_meth.singleton = meth.singleton - new_meth.params = meth.params - - new_meth.comment = an_alias.comment - - meth.add_alias new_meth - - add_method new_meth - - # aliases don't use ongoing visibility - new_meth.visibility = meth.visibility - - new_meth - end - - ## - # Adds +attribute+ - - def add_attribute(attribute) - add_to @attributes, attribute - end - - ## - # Adds a class named +name+ with +superclass+. - # - # Given class Container::Item RDoc assumes +Container+ is a module - # unless it later sees class Container. add_class automatically - # upgrades +name+ to a class in this case. - - def add_class(class_type, name, superclass = 'Object') - klass = add_class_or_module @classes, class_type, name, superclass - - existing = klass.superclass - existing = existing.name if existing and not String === existing - - if superclass != existing and superclass != 'Object' then - klass.superclass = superclass - end - - # If the parser encounters Container::Item before encountering - # Container, then it assumes that Container is a module. This may not - # be the case, so remove Container from the module list if present and - # transfer any contained classes and modules to the new class. - - mod = RDoc::TopLevel.modules_hash.delete klass.full_name - - if mod then - klass.classes_hash.update mod.classes_hash - klass.modules_hash.update mod.modules_hash - klass.method_list.concat mod.method_list - - @modules.delete klass.name - end - - RDoc::TopLevel.classes_hash[klass.full_name] = klass - - klass - end - - ## - # Instantiates a +class_type+ named +name+ and adds it the modules or - # classes Hash +collection+. - - def add_class_or_module(collection, class_type, name, superclass = nil) - full_name = child_name name - - mod = collection[name] - - if mod then - mod.superclass = superclass unless mod.module? - else - all = if class_type == RDoc::NormalModule then - RDoc::TopLevel.modules_hash - else - RDoc::TopLevel.classes_hash - end - - mod = all[full_name] - - unless mod then - mod = class_type.new name, superclass - else - # If the class has been encountered already, check that its - # superclass has been set (it may not have been, depending on the - # context in which it was encountered). - if class_type == RDoc::NormalClass then - mod.superclass = superclass unless mod.superclass - end - end - - unless @done_documenting then - all[full_name] = mod - collection[name] = mod - end - - mod.section = @current_section - mod.parent = self - end - - mod - end - - ## - # Adds +constant+ - - def add_constant(constant) - add_to @constants, constant - end - - ## - # Adds included module +include+ - - def add_include(include) - add_to @includes, include - end - - ## - # Adds +method+ - - def add_method(method) - method.visibility = @visibility - add_to @method_list, method - - unmatched_alias_list = @unmatched_alias_lists[method.name] - if unmatched_alias_list then - unmatched_alias_list.each do |unmatched_alias| - add_alias_impl unmatched_alias, method - @aliases.delete unmatched_alias - end - - @unmatched_alias_lists.delete method.name - end - end - - ## - # Adds a module named +name+. If RDoc already knows +name+ is a class then - # that class is returned instead. See also #add_class - - def add_module(class_type, name) - return @classes[name] if @classes.key? name - - add_class_or_module @modules, class_type, name, nil - end - - ## - # Adds an alias from +from+ to +name+ - - def add_module_alias from, name - to_name = child_name name - - unless @done_documenting then - if from.module? then - RDoc::TopLevel.modules_hash - else - RDoc::TopLevel.classes_hash - end[to_name] = from - - if from.module? then - @modules - else - @classes - end[name] = from - end - - from - end - - ## - # Adds +require+ to this context's top level - - def add_require(require) - if RDoc::TopLevel === self then - add_to @requires, require - else - parent.add_require require - end - end - - ## - # Adds +thing+ to the collection +array+ - - def add_to(array, thing) - array << thing if @document_self and not @done_documenting - thing.parent = self - thing.section = @current_section - end - - ## - # Creates the full name for a child with +name+ - - def child_name name - if RDoc::TopLevel === self then - name - else - "#{self.full_name}::#{name}" - end - end - - ## - # Array of classes in this context - - def classes - @classes.values - end - - ## - # All classes and modules in this namespace - - def classes_and_modules - classes + modules - end - - ## - # Hash of classes keyed by class name - - def classes_hash - @classes - end - - ## - # Is part of this thing was defined in +file+? - - def defined_in?(file) - @in_files.include?(file) - end - - ## - # Iterator for attributes - - def each_attribute # :yields: attribute - @attributes.each { |a| yield a } - end - - ## - # Iterator for classes and modules - - def each_classmodule(&block) # :yields: module - classes_and_modules.sort.each(&block) - end - - ## - # Iterator for constants - - def each_constant # :yields: constant - @constants.each {|c| yield c} - end - - ## - # Iterator for included modules - - def each_include # :yields: include - @includes.each do |i| yield i end - end - - ## - # Iterator for methods - - def each_method # :yields: method - @method_list.sort.each {|m| yield m} - end - - ## - # Finds an attribute with +name+ in this context - - def find_attribute_named(name) - @attributes.find { |m| m.name == name } - end - - ## - # Finds a class method with +name+ in this context - - def find_class_method_named(name) - @method_list.find { |meth| meth.singleton && meth.name == name } - end - - ## - # Finds a constant with +name+ in this context - - def find_constant_named(name) - @constants.find {|m| m.name == name} - end - - ## - # Find a module at a higher scope - - def find_enclosing_module_named(name) - parent && parent.find_module_named(name) - end - - ## - # Finds a file with +name+ in this context - - def find_file_named(name) - top_level.class.find_file_named(name) - end - - ## - # Finds an instance method with +name+ in this context - - def find_instance_method_named(name) - @method_list.find { |meth| !meth.singleton && meth.name == name } - end - - ## - # Finds a method, constant, attribute, module or files named +symbol+ in - # this context - - def find_local_symbol(symbol) - find_method_named(symbol) or - find_constant_named(symbol) or - find_attribute_named(symbol) or - find_module_named(symbol) or - find_file_named(symbol) - end - - ## - # Finds a instance or module method with +name+ in this context - - def find_method_named(name) - case name - when /\A#/ then - find_instance_method_named name[1..-1] - when /\A::/ then - find_class_method_named name[2..-1] - else - @method_list.find { |meth| meth.name == name } - end - end - - ## - # Find a module with +name+ using ruby's scoping rules - - def find_module_named(name) - res = @modules[name] || @classes[name] - return res if res - return self if self.name == name - find_enclosing_module_named name - end - - ## - # Look up +symbol+. If +method+ is non-nil, then we assume the symbol - # references a module that contains that method. - - def find_symbol(symbol, method = nil) - result = nil - - case symbol - when /^::([A-Z].*)/ then - result = top_level.find_symbol($1) - when /::/ then - modules = symbol.split(/::/) - - unless modules.empty? then - module_name = modules.shift - result = find_module_named(module_name) - - if result then - modules.each do |name| - result = result.find_module_named name - break unless result - end - end - end - end - - unless result then - # if a method is specified, then we're definitely looking for - # a module, otherwise it could be any symbol - if method then - result = find_module_named symbol - else - result = find_local_symbol symbol - if result.nil? then - if symbol =~ /^[A-Z]/ then - result = parent - while result && result.name != symbol do - result = result.parent - end - end - end - end - end - - result = result.find_local_symbol method if result and method - - result - end - - ## - # The full name for this context. This method is overridden by subclasses. - - def full_name - '(unknown)' - end - - ## - # URL for this with a +prefix+ - - def http_url(prefix) - path = full_name - path = path.gsub(/<<\s*(\w*)/, 'from-\1') if path =~ /< $DEBUG_RDOC, :noop => $DARKFISH_DRYRUN } - - FileUtils.cp @template_dir + 'rdoc.css', '.', options - - Dir[(@template_dir + "{js,images}/**/*").to_s].each do |path| - next if File.directory? path - next if path =~ /#{File::SEPARATOR}\./ - - dst = Pathname.new(path).relative_path_from @template_dir - - # I suck at glob - dst_dir = dst.dirname - FileUtils.mkdir_p dst_dir, options unless File.exist? dst_dir - - FileUtils.cp @template_dir + path, dst, options - end - end - - ### Build the initial indices and output objects - ### based on an array of TopLevel objects containing - ### the extracted information. - def generate( top_levels ) - @outputdir = Pathname.new( @options.op_dir ).expand_path( @basedir ) - - @files = top_levels.sort - @classes = RDoc::TopLevel.all_classes_and_modules.sort - @methods = @classes.map { |m| m.method_list }.flatten.sort - @modsort = get_sorted_module_list( @classes ) - - # Now actually write the output - write_style_sheet - generate_index - generate_class_files - generate_file_files - - rescue StandardError => err - debug_msg "%s: %s\n %s" % [ err.class.name, err.message, err.backtrace.join("\n ") ] - raise - end - - ######### - protected - ######### - - ### Return a list of the documented modules sorted by salience first, then - ### by name. - def get_sorted_module_list( classes ) - nscounts = classes.inject({}) do |counthash, klass| - top_level = klass.full_name.gsub( /::.*/, '' ) - counthash[top_level] ||= 0 - counthash[top_level] += 1 - - counthash - end - - # Sort based on how often the top level namespace occurs, and then on the - # name of the module -- this works for projects that put their stuff into - # a namespace, of course, but doesn't hurt if they don't. - classes.sort_by do |klass| - top_level = klass.full_name.gsub( /::.*/, '' ) - [ - nscounts[ top_level ] * -1, - klass.full_name - ] - end.select do |klass| - klass.document_self - end - end - - ### Generate an index page which lists all the classes which - ### are documented. - def generate_index - template_file = @template_dir + 'index.rhtml' - return unless template_file.exist? - - debug_msg "Rendering the index page..." - - template_src = template_file.read - template = ERB.new( template_src, trim_mode: '<>' ) - template.filename = template_file.to_s - context = binding() - - output = nil - - begin - output = template.result( context ) - rescue NoMethodError => err - raise RDoc::Error, "Error while evaluating %s: %s (at %p)" % [ - template_file, - err.message, - eval( "_erbout[-50,50]", context ) - ], err.backtrace - end - - outfile = @basedir + @options.op_dir + 'index.html' - unless $DARKFISH_DRYRUN - debug_msg "Outputting to %s" % [outfile.expand_path] - outfile.open( 'w', 0644 ) do |fh| - fh.print( output ) - end - else - debug_msg "Would have output to %s" % [outfile.expand_path] - end - end - - ### Generate a documentation file for each class - def generate_class_files - template_file = @template_dir + 'classpage.rhtml' - return unless template_file.exist? - debug_msg "Generating class documentation in #@outputdir" - - @classes.each do |klass| - debug_msg " working on %s (%s)" % [ klass.full_name, klass.path ] - outfile = @outputdir + klass.path - rel_prefix = @outputdir.relative_path_from( outfile.dirname ) - svninfo = self.get_svninfo( klass ) - - debug_msg " rendering #{outfile}" - self.render_template( template_file, binding(), outfile ) - end - end - - ### Generate a documentation file for each file - def generate_file_files - template_file = @template_dir + 'filepage.rhtml' - return unless template_file.exist? - debug_msg "Generating file documentation in #@outputdir" - - @files.each do |file| - outfile = @outputdir + file.path - debug_msg " working on %s (%s)" % [ file.full_name, outfile ] - rel_prefix = @outputdir.relative_path_from( outfile.dirname ) - context = binding() - - debug_msg " rendering #{outfile}" - self.render_template( template_file, binding(), outfile ) - end - end - - - ### Return a string describing the amount of time in the given number of - ### seconds in terms a human can understand easily. - def time_delta_string( seconds ) - return 'less than a minute' if seconds < 1.minute - return (seconds / 1.minute).to_s + ' minute' + (seconds/60 == 1 ? '' : 's') if seconds < 50.minutes - return 'about one hour' if seconds < 90.minutes - return (seconds / 1.hour).to_s + ' hours' if seconds < 18.hours - return 'one day' if seconds < 1.day - return 'about one day' if seconds < 2.days - return (seconds / 1.day).to_s + ' days' if seconds < 1.week - return 'about one week' if seconds < 2.week - return (seconds / 1.week).to_s + ' weeks' if seconds < 3.months - return (seconds / 1.month).to_s + ' months' if seconds < 1.year - return (seconds / 1.year).to_s + ' years' - end - - - # %q$Id: darkfish.rb 52 2009-01-07 02:08:11Z deveiant $" - SVNID_PATTERN = / - \$Id:\s - (\S+)\s # filename - (\d+)\s # rev - (\d{4}-\d{2}-\d{2})\s # Date (YYYY-MM-DD) - (\d{2}:\d{2}:\d{2}Z)\s # Time (HH:MM:SSZ) - (\w+)\s # committer - \$$ - /x - - ### Try to extract Subversion information out of the first constant whose value looks like - ### a subversion Id tag. If no matching constant is found, and empty hash is returned. - def get_svninfo( klass ) - constants = klass.constants or return {} - - constants.find {|c| c.value =~ SVNID_PATTERN } or return {} - - filename, rev, date, time, committer = $~.captures - commitdate = Time.parse( date + ' ' + time ) - - return { - :filename => filename, - :rev => Integer( rev ), - :commitdate => commitdate, - :commitdelta => time_delta_string( Time.now.to_i - commitdate.to_i ), - :committer => committer, - } - end - - - ### Load and render the erb template in the given +template_file+ within the - ### specified +context+ (a Binding object) and write it out to +outfile+. - ### Both +template_file+ and +outfile+ should be Pathname-like objects. - - def render_template( template_file, context, outfile ) - template_src = template_file.read - template = ERB.new( template_src, trim_mode: '<>' ) - template.filename = template_file.to_s - - output = begin - template.result( context ) - rescue NoMethodError => err - raise RDoc::Error, "Error while evaluating %s: %s (at %p)" % [ - template_file.to_s, - err.message, - eval( "_erbout[-50,50]", context ) - ], err.backtrace - end - - unless $DARKFISH_DRYRUN - outfile.dirname.mkpath - outfile.open( 'w', 0644 ) do |ofh| - ofh.print( output ) - end - else - debug_msg " would have written %d bytes to %s" % - [ output.length, outfile ] - end - end - -end # Roc::Generator::Darkfish - -# :stopdoc: - -### Time constants -module TimeConstantMethods # :nodoc: - - ### Number of seconds (returns receiver unmodified) - def seconds - return self - end - alias_method :second, :seconds - - ### Returns number of seconds in minutes - def minutes - return self * 60 - end - alias_method :minute, :minutes - - ### Returns the number of seconds in hours - def hours - return self * 60.minutes - end - alias_method :hour, :hours - - ### Returns the number of seconds in days - def days - return self * 24.hours - end - alias_method :day, :days - - ### Return the number of seconds in weeks - def weeks - return self * 7.days - end - alias_method :week, :weeks - - ### Returns the number of seconds in fortnights - def fortnights - return self * 2.weeks - end - alias_method :fortnight, :fortnights - - ### Returns the number of seconds in months (approximate) - def months - return self * 30.days - end - alias_method :month, :months - - ### Returns the number of seconds in years (approximate) - def years - return (self * 365.25.days).to_i - end - alias_method :year, :years - - - ### Returns the Time number of seconds before the - ### specified +time+. E.g., 2.hours.before( header.expiration ) - def before( time ) - return time - self - end - - - ### Returns the Time number of seconds ago. (e.g., - ### expiration > 2.hours.ago ) - def ago - return self.before( ::Time.now ) - end - - - ### Returns the Time number of seconds after the given +time+. - ### E.g., 10.minutes.after( header.expiration ) - def after( time ) - return time + self - end - - # Reads best without arguments: 10.minutes.from_now - def from_now - return self.after( ::Time.now ) - end -end # module TimeConstantMethods - - -# Extend Numeric with time constants -class Numeric # :nodoc: - include TimeConstantMethods -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/generator/markup.rb b/Src/StdLib/ruby/1.9.1/rdoc/generator/markup.rb deleted file mode 100644 index 3c803f186..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/generator/markup.rb +++ /dev/null @@ -1,171 +0,0 @@ -require 'rdoc/text' -require 'rdoc/code_objects' -require 'rdoc/generator' -require 'rdoc/markup/to_html_crossref' - -## -# Handle common RDoc::Markup tasks for various CodeObjects - -module RDoc::Generator::Markup - - ## - # Generates a relative URL from this object's path to +target_path+ - - def aref_to(target_path) - RDoc::Markup::ToHtml.gen_relative_url path, target_path - end - - ## - # Generates a relative URL from +from_path+ to this object's path - - def as_href(from_path) - RDoc::Markup::ToHtml.gen_relative_url from_path, path - end - - ## - # Handy wrapper for marking up this object's comment - - def description - markup @comment - end - - ## - # Creates an RDoc::Markup::ToHtmlCrossref formatter - - def formatter - return @formatter if defined? @formatter - - show_hash = RDoc::RDoc.current.options.show_hash - this = RDoc::Context === self ? self : @parent - @formatter = RDoc::Markup::ToHtmlCrossref.new this.path, this, show_hash - end - - ## - # Build a webcvs URL starting for the given +url+ with +full_path+ appended - # as the destination path. If +url+ contains '%s' +full_path+ will be - # sprintf'd into +url+ instead. - - def cvs_url(url, full_path) - if /%s/ =~ url then - sprintf url, full_path - else - url + full_path - end - end - -end - -class RDoc::AnyMethod - - include RDoc::Generator::Markup - - ## - # Prepend +src+ with line numbers. Relies on the first line of a source - # code listing having: - # - # # File xxxxx, line dddd - - def add_line_numbers(src) - if src =~ /\A.*, line (\d+)/ then - first = $1.to_i - 1 - last = first + src.count("\n") - size = last.to_s.length - - line = first - src.gsub!(/^/) do - res = if line == first then - " " * (size + 2) - else - "%2$*1$d: " % [size, line] - end - - line += 1 - res - end - end - end - - ## - # Turns the method's token stream into HTML - - def markup_code - return '' unless @token_stream - - src = "" - - @token_stream.each do |t| - next unless t - # style = STYLE_MAP[t.class] - style = case t - when RDoc::RubyToken::TkCONSTANT then "ruby-constant" - when RDoc::RubyToken::TkKW then "ruby-keyword kw" - when RDoc::RubyToken::TkIVAR then "ruby-ivar" - when RDoc::RubyToken::TkOp then "ruby-operator" - when RDoc::RubyToken::TkId then "ruby-identifier" - when RDoc::RubyToken::TkNode then "ruby-node" - when RDoc::RubyToken::TkCOMMENT then "ruby-comment cmt" - when RDoc::RubyToken::TkREGEXP then "ruby-regexp re" - when RDoc::RubyToken::TkSTRING then "ruby-value str" - when RDoc::RubyToken::TkVal then "ruby-value" - else - nil - end - - text = CGI.escapeHTML t.text - - if style - src << "#{text}" - else - src << text - end - end - - add_line_numbers src - - src - end - -end - -class RDoc::Attr - - include RDoc::Generator::Markup - -end - -class RDoc::Constant - - include RDoc::Generator::Markup - -end - -class RDoc::Context - - include RDoc::Generator::Markup - -end - -class RDoc::Context::Section - - include RDoc::Generator::Markup - -end - -class RDoc::TopLevel - - ## - # Returns a URL for this source file on some web repository. Use the -W - # command line option to set. - - def cvs_url - url = RDoc::RDoc.current.options.webcvs - - if /%s/ =~ url then - url % @absolute_name - else - url + @absolute_name - end - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/generator/ri.rb b/Src/StdLib/ruby/1.9.1/rdoc/generator/ri.rb deleted file mode 100644 index 83bd3e696..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/generator/ri.rb +++ /dev/null @@ -1,82 +0,0 @@ -require 'rdoc/generator' -require 'rdoc/ri' - -## -# Generates ri data files - -class RDoc::Generator::RI - - RDoc::RDoc.add_generator self - - def self.for options - new options - end - - ## - # Set up a new ri generator - - def initialize options #:not-new: - @options = options - @store = RDoc::RI::Store.new '.' - @old_siginfo = nil - @current = nil - end - - ## - # Build the initial indices and output objects based on an array of TopLevel - # objects containing the extracted information. - - def generate top_levels - install_siginfo_handler - - @store.load_cache - - RDoc::TopLevel.all_classes_and_modules.each do |klass| - @current = "#{klass.class}: #{klass.full_name}" - - @store.save_class klass - - klass.each_method do |method| - @current = "#{method.class}: #{method.full_name}" - @store.save_method klass, method - end - - klass.each_attribute do |attribute| - @store.save_method klass, attribute - end - end - - @current = 'saving cache' - - @store.save_cache - - ensure - @current = nil - - remove_siginfo_handler - end - - ## - # Installs a siginfo handler that prints the current filename. - - def install_siginfo_handler - return unless Signal.list.key? 'INFO' - - @old_siginfo = trap 'INFO' do - puts @current if @current - end - end - - ## - # Removes a siginfo handler and replaces the previous - - def remove_siginfo_handler - return unless Signal.list.key? 'INFO' - - handler = @old_siginfo || 'DEFAULT' - - trap 'INFO', handler - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/classpage.rhtml b/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/classpage.rhtml deleted file mode 100644 index 0edee13d5..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/classpage.rhtml +++ /dev/null @@ -1,297 +0,0 @@ -"?> - - - - - - <%= klass.type.capitalize %>: <%= klass.full_name %> - - - - - - - - - - - -
-
-
-

- Home - Classes - Methods -

-
-
- -
-
-

In Files

-
- -
-
- - <% if !svninfo.empty? %> -
-

Subversion Info

-
-
-
Rev
-
<%= svninfo[:rev] %>
- -
Last Checked In
-
<%= svninfo[:commitdate].strftime('%Y-%m-%d %H:%M:%S') %> - (<%= svninfo[:commitdelta] %> ago)
- -
Checked in by
-
<%= svninfo[:committer] %>
-
-
-
- <% end %> -
- -
- - - <% if klass.type == 'class' %> -
-

Parent

- <% unless String === klass.superclass %> - - <% else %> - - <% end %> -
- <% end %> - - - <% unless klass.classes_and_modules.empty? %> -
-

Namespace

- -
- <% end %> - - - <% unless klass.method_list.empty? %> -
-

Methods

- -
- <% end %> - - - <% unless klass.includes.empty? %> -
-

Included Modules

- -
- <% end %> -
- -
- <% simple_files = @files.select {|tl| tl.parser == RDoc::Parser::Simple } %> - <% unless simple_files.empty? then %> -
-

Files

- -
- <% end %> - -
-

Class Index - [+]

-
-
- Quicksearch - -
-
- - - -
- - <% if $DEBUG_RDOC %> -
toggle debugging
- <% end %> -
-
- -
-

<%= klass.full_name %>

- -
- <%= klass.description %> -
- - - <% unless klass.constants.empty? %> -
-

Constants

-
- <% klass.each_constant do |const| %> -
<%= const.name %>
- <% if const.comment %> -
<%= const.description.strip %>
- <% else %> -
(Not documented)
- <% end %> - <% end %> -
-
- <% end %> - - - <% unless klass.attributes.empty? %> -
-

Attributes

- - <% klass.each_attribute do |attrib| %> -
- - <% if attrib.rw =~ /w/i %> - - <% end %> -
- <%= h attrib.name %>[<%= attrib.rw %>] -
- -
- <% if attrib.comment %> - <%= attrib.description.strip %> - <% else %> -

(Not documented)

- <% end %> -
-
- <% end %> -
- <% end %> - - - <% klass.methods_by_type.each do |type, visibilities| - next if visibilities.empty? - visibilities.each do |visibility, methods| - next if methods.empty? %> -
-

<%= visibility.to_s.capitalize %> <%= type.capitalize %> Methods

- - <% methods.each do |method| %> -
"> - - -
- <% if method.call_seq %> - <%= method.call_seq.strip.gsub(/->/, '→').gsub( /^\w.+\./m, '') %> - click to toggle source - <% else %> - <%= h method.name %><%= method.params %> - click to toggle source - <% end %> -
- -
- <% if method.comment %> - <%= method.description.strip %> - <% else %> -

(Not documented)

- <% end %> - - <% if method.token_stream %> -
-
-<%= method.markup_code %>
-
-
- <% end %> -
- - <% unless method.aliases.empty? %> -
- Also aliased as: <%= method.aliases.map do |aka| - %{#{h aka.name}} - end.join(", ") %> -
- <% end %> - - <% if method.is_alias_for then %> - - <% end %> -
- - <% end %> -
- <% end - end %> - -
- - -
- <% if $DEBUG_RDOC - require 'pp' %> -
<%= h PP.pp(klass, _erbout) %>
-
- <% else %> -

Disabled; run with --debug to generate this.

- <% end %> - - -
-

[Validate]

-

Generated with the Darkfish - Rdoc Generator <%= RDoc::Generator::Darkfish::VERSION %>.

-
- - - - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/filepage.rhtml b/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/filepage.rhtml deleted file mode 100644 index 65482fa71..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/filepage.rhtml +++ /dev/null @@ -1,124 +0,0 @@ - - - - - - - - File: <%= file.base_name %> [<%= @options.title %>] - - - - - - - - - -<% if file.parser == RDoc::Parser::Simple %> - -
-
-
-

- Home - Classes - Methods -

-
-
- -
- <% simple_files = @files.select { |f| f.parser == RDoc::Parser::Simple } %> - <% unless simple_files.empty? then %> -
-

Files

- -
- <% end %> - -
-

Class Index - [+]

-
-
- Quicksearch - -
-
- - - -
- - <% if $DEBUG_RDOC %> -
toggle debugging
- <% end %> -
-
- -
- <%= file.description %> -
- -
-

[Validate]

-

Generated with the Darkfish - Rdoc Generator <%= RDoc::Generator::Darkfish::VERSION %>.

-
- -<% else %> - -
-
-
Last Modified
-
<%= file.last_modified %>
- - <% if file.requires %> -
Requires
-
-
    - <% file.requires.each do |require| %> -
  • <%= require.name %>
  • - <% end %> -
-
- <% end %> - - <% if @options.webcvs %> -
Trac URL
-
<%= file.cvs_url %>
- <% end %> -
-
- -
- <% if file.comment %> -
-

Description

- <%= file.description %> -
- <% end %> -
- -<% end %> - - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/brick.png b/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/brick.png deleted file mode 100644 index 7851cf34c..000000000 Binary files a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/brick.png and /dev/null differ diff --git a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/brick_link.png b/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/brick_link.png deleted file mode 100644 index 9ebf013a2..000000000 Binary files a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/brick_link.png and /dev/null differ diff --git a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/bug.png b/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/bug.png deleted file mode 100644 index 2d5fb90ec..000000000 Binary files a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/bug.png and /dev/null differ diff --git a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/bullet_black.png b/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/bullet_black.png deleted file mode 100644 index 57619706d..000000000 Binary files a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/bullet_black.png and /dev/null differ diff --git a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/bullet_toggle_minus.png b/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/bullet_toggle_minus.png deleted file mode 100644 index b47ce55f6..000000000 Binary files a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/bullet_toggle_minus.png and /dev/null differ diff --git a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/bullet_toggle_plus.png b/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/bullet_toggle_plus.png deleted file mode 100644 index 9ab4a8966..000000000 Binary files a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/bullet_toggle_plus.png and /dev/null differ diff --git a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/date.png b/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/date.png deleted file mode 100644 index 783c83357..000000000 Binary files a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/date.png and /dev/null differ diff --git a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/find.png b/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/find.png deleted file mode 100644 index 154747964..000000000 Binary files a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/find.png and /dev/null differ diff --git a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/loadingAnimation.gif b/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/loadingAnimation.gif deleted file mode 100644 index 82290f483..000000000 Binary files a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/loadingAnimation.gif and /dev/null differ diff --git a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/macFFBgHack.png b/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/macFFBgHack.png deleted file mode 100644 index c6473b324..000000000 Binary files a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/macFFBgHack.png and /dev/null differ diff --git a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/package.png b/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/package.png deleted file mode 100644 index da3c2a2d7..000000000 Binary files a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/package.png and /dev/null differ diff --git a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/page_green.png b/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/page_green.png deleted file mode 100644 index de8e003f9..000000000 Binary files a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/page_green.png and /dev/null differ diff --git a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/page_white_text.png b/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/page_white_text.png deleted file mode 100644 index 813f712f7..000000000 Binary files a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/page_white_text.png and /dev/null differ diff --git a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/page_white_width.png b/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/page_white_width.png deleted file mode 100644 index 1eb880947..000000000 Binary files a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/page_white_width.png and /dev/null differ diff --git a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/plugin.png b/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/plugin.png deleted file mode 100644 index 6187b15ae..000000000 Binary files a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/plugin.png and /dev/null differ diff --git a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/ruby.png b/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/ruby.png deleted file mode 100644 index f763a1688..000000000 Binary files a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/ruby.png and /dev/null differ diff --git a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/tag_green.png b/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/tag_green.png deleted file mode 100644 index 83ec984bd..000000000 Binary files a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/tag_green.png and /dev/null differ diff --git a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/wrench.png b/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/wrench.png deleted file mode 100644 index 5c8213fef..000000000 Binary files a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/wrench.png and /dev/null differ diff --git a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/wrench_orange.png b/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/wrench_orange.png deleted file mode 100644 index 565a9330e..000000000 Binary files a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/wrench_orange.png and /dev/null differ diff --git a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/zoom.png b/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/zoom.png deleted file mode 100644 index 908612e39..000000000 Binary files a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/images/zoom.png and /dev/null differ diff --git a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/index.rhtml b/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/index.rhtml deleted file mode 100644 index c5564ea85..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/index.rhtml +++ /dev/null @@ -1,64 +0,0 @@ - - - - - - - - <%= h @options.title %> - - - - - - - - - - - - <% $stderr.sync = true %> -

<%= h @options.title %>

- - <% if @options.main_page && main_page = @files.find { |f| f.full_name == @options.main_page } %> -
- <%= main_page.description.sub(%r{^\s*}i, '') %> -
- <% else %> -

This is the API documentation for '<%= @options.title %>'.

- <% end %> - - <% simple_files = @files.select {|tl| tl.parser == RDoc::Parser::Simple } %> - <% unless simple_files.empty? then %> -

Files

- - <% end %> - -

Classes/Modules

- - -

Methods

- - -
-

[Validate]

-

Generated with the Darkfish - Rdoc Generator <%= RDoc::Generator::Darkfish::VERSION %>.

-
- - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/js/darkfish.js b/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/js/darkfish.js deleted file mode 100644 index 5a471e8b9..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/js/darkfish.js +++ /dev/null @@ -1,116 +0,0 @@ -/** - * - * Darkfish Page Functions - * $Id: darkfish.js 53 2009-01-07 02:52:03Z deveiant $ - * - * Author: Michael Granger - * - */ - -/* Provide console simulation for firebug-less environments */ -if (!("console" in window) || !("firebug" in console)) { - var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", - "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"]; - - window.console = {}; - for (var i = 0; i < names.length; ++i) - window.console[names[i]] = function() {}; -}; - - -/** - * Unwrap the first element that matches the given @expr@ from the targets and return them. - */ -$.fn.unwrap = function( expr ) { - return this.each( function() { - $(this).parents( expr ).eq( 0 ).after( this ).remove(); - }); -}; - - -function showSource( e ) { - var target = e.target; - var codeSections = $(target). - parents('.method-detail'). - find('.method-source-code'); - - $(target). - parents('.method-detail'). - find('.method-source-code'). - slideToggle(); -}; - -function hookSourceViews() { - $('.method-description,.method-heading').click( showSource ); -}; - -function toggleDebuggingSection() { - $('.debugging-section').slideToggle(); -}; - -function hookDebuggingToggle() { - $('#debugging-toggle img').click( toggleDebuggingSection ); -}; - -function hookQuickSearch() { - $('.quicksearch-field').each( function() { - var searchElems = $(this).parents('.section').find( 'li' ); - var toggle = $(this).parents('.section').find('h3 .search-toggle'); - // console.debug( "Toggle is: %o", toggle ); - var qsbox = $(this).parents('form').get( 0 ); - - $(this).quicksearch( this, searchElems, { - noSearchResultsIndicator: 'no-class-search-results', - focusOnLoad: false - }); - $(toggle).click( function() { - // console.debug( "Toggling qsbox: %o", qsbox ); - $(qsbox).toggle(); - }); - }); -}; - -function highlightTarget( anchor ) { - console.debug( "Highlighting target '%s'.", anchor ); - - $("a[name=" + anchor + "]").each( function() { - if ( !$(this).parent().parent().hasClass('target-section') ) { - console.debug( "Wrapping the target-section" ); - $('div.method-detail').unwrap( 'div.target-section' ); - $(this).parent().wrap( '
' ); - } else { - console.debug( "Already wrapped." ); - } - }); -}; - -function highlightLocationTarget() { - console.debug( "Location hash: %s", window.location.hash ); - if ( ! window.location.hash || window.location.hash.length == 0 ) return; - - var anchor = window.location.hash.substring(1); - console.debug( "Found anchor: %s; matching %s", anchor, "a[name=" + anchor + "]" ); - - highlightTarget( anchor ); -}; - -function highlightClickTarget( event ) { - console.debug( "Highlighting click target for event %o", event.target ); - try { - var anchor = $(event.target).attr( 'href' ).substring(1); - console.debug( "Found target anchor: %s", anchor ); - highlightTarget( anchor ); - } catch ( err ) { - console.error( "Exception while highlighting: %o", err ); - }; -}; - - -$(document).ready( function() { - hookSourceViews(); - hookDebuggingToggle(); - hookQuickSearch(); - highlightLocationTarget(); - - $('ul.link-list a').bind( "click", highlightClickTarget ); -}); diff --git a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/js/jquery.js b/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/js/jquery.js deleted file mode 100644 index eae453a7b..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/js/jquery.js +++ /dev/null @@ -1,32 +0,0 @@ -/* - * jQuery 1.2.6 - New Wave Javascript - * - * Copyright (c) 2008 John Resig (jquery.com) - * Dual licensed under the MIT (MIT-LICENSE.txt) - * and GPL (GPL-LICENSE.txt) licenses. - * - * $Date: 2008-09-25 09:50:52 -0700 (Thu, 25 Sep 2008) $ - * $Rev: 38 $ - */ -(function(){var _jQuery=window.jQuery,_$=window.$;var jQuery=window.jQuery=window.$=function(selector,context){return new jQuery.fn.init(selector,context);};var quickExpr=/^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/,isSimple=/^.[^:#\[\.]*$/,undefined;jQuery.fn=jQuery.prototype={init:function(selector,context){selector=selector||document;if(selector.nodeType){this[0]=selector;this.length=1;return this;}if(typeof selector=="string"){var match=quickExpr.exec(selector);if(match&&(match[1]||!context)){if(match[1])selector=jQuery.clean([match[1]],context);else{var elem=document.getElementById(match[3]);if(elem){if(elem.id!=match[3])return jQuery().find(selector);return jQuery(elem);}selector=[];}}else -return jQuery(context).find(selector);}else if(jQuery.isFunction(selector))return jQuery(document)[jQuery.fn.ready?"ready":"load"](selector);return this.setArray(jQuery.makeArray(selector));},jquery:"1.2.6",size:function(){return this.length;},length:0,get:function(num){return num==undefined?jQuery.makeArray(this):this[num];},pushStack:function(elems){var ret=jQuery(elems);ret.prevObject=this;return ret;},setArray:function(elems){this.length=0;Array.prototype.push.apply(this,elems);return this;},each:function(callback,args){return jQuery.each(this,callback,args);},index:function(elem){var ret=-1;return jQuery.inArray(elem&&elem.jquery?elem[0]:elem,this);},attr:function(name,value,type){var options=name;if(name.constructor==String)if(value===undefined)return this[0]&&jQuery[type||"attr"](this[0],name);else{options={};options[name]=value;}return this.each(function(i){for(name in options)jQuery.attr(type?this.style:this,name,jQuery.prop(this,options[name],type,i,name));});},css:function(key,value){if((key=='width'||key=='height')&&parseFloat(value)<0)value=undefined;return this.attr(key,value,"curCSS");},text:function(text){if(typeof text!="object"&&text!=null)return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(text));var ret="";jQuery.each(text||this,function(){jQuery.each(this.childNodes,function(){if(this.nodeType!=8)ret+=this.nodeType!=1?this.nodeValue:jQuery.fn.text([this]);});});return ret;},wrapAll:function(html){if(this[0])jQuery(html,this[0].ownerDocument).clone().insertBefore(this[0]).map(function(){var elem=this;while(elem.firstChild)elem=elem.firstChild;return elem;}).append(this);return this;},wrapInner:function(html){return this.each(function(){jQuery(this).contents().wrapAll(html);});},wrap:function(html){return this.each(function(){jQuery(this).wrapAll(html);});},append:function(){return this.domManip(arguments,true,false,function(elem){if(this.nodeType==1)this.appendChild(elem);});},prepend:function(){return this.domManip(arguments,true,true,function(elem){if(this.nodeType==1)this.insertBefore(elem,this.firstChild);});},before:function(){return this.domManip(arguments,false,false,function(elem){this.parentNode.insertBefore(elem,this);});},after:function(){return this.domManip(arguments,false,true,function(elem){this.parentNode.insertBefore(elem,this.nextSibling);});},end:function(){return this.prevObject||jQuery([]);},find:function(selector){var elems=jQuery.map(this,function(elem){return jQuery.find(selector,elem);});return this.pushStack(/[^+>] [^+>]/.test(selector)||selector.indexOf("..")>-1?jQuery.unique(elems):elems);},clone:function(events){var ret=this.map(function(){if(jQuery.browser.msie&&!jQuery.isXMLDoc(this)){var clone=this.cloneNode(true),container=document.createElement("div");container.appendChild(clone);return jQuery.clean([container.innerHTML])[0];}else -return this.cloneNode(true);});var clone=ret.find("*").andSelf().each(function(){if(this[expando]!=undefined)this[expando]=null;});if(events===true)this.find("*").andSelf().each(function(i){if(this.nodeType==3)return;var events=jQuery.data(this,"events");for(var type in events)for(var handler in events[type])jQuery.event.add(clone[i],type,events[type][handler],events[type][handler].data);});return ret;},filter:function(selector){return this.pushStack(jQuery.isFunction(selector)&&jQuery.grep(this,function(elem,i){return selector.call(elem,i);})||jQuery.multiFilter(selector,this));},not:function(selector){if(selector.constructor==String)if(isSimple.test(selector))return this.pushStack(jQuery.multiFilter(selector,this,true));else -selector=jQuery.multiFilter(selector,this);var isArrayLike=selector.length&&selector[selector.length-1]!==undefined&&!selector.nodeType;return this.filter(function(){return isArrayLike?jQuery.inArray(this,selector)<0:this!=selector;});},add:function(selector){return this.pushStack(jQuery.unique(jQuery.merge(this.get(),typeof selector=='string'?jQuery(selector):jQuery.makeArray(selector))));},is:function(selector){return!!selector&&jQuery.multiFilter(selector,this).length>0;},hasClass:function(selector){return this.is("."+selector);},val:function(value){if(value==undefined){if(this.length){var elem=this[0];if(jQuery.nodeName(elem,"select")){var index=elem.selectedIndex,values=[],options=elem.options,one=elem.type=="select-one";if(index<0)return null;for(var i=one?index:0,max=one?index+1:options.length;i=0||jQuery.inArray(this.name,value)>=0);else if(jQuery.nodeName(this,"select")){var values=jQuery.makeArray(value);jQuery("option",this).each(function(){this.selected=(jQuery.inArray(this.value,values)>=0||jQuery.inArray(this.text,values)>=0);});if(!values.length)this.selectedIndex=-1;}else -this.value=value;});},html:function(value){return value==undefined?(this[0]?this[0].innerHTML:null):this.empty().append(value);},replaceWith:function(value){return this.after(value).remove();},eq:function(i){return this.slice(i,i+1);},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments));},map:function(callback){return this.pushStack(jQuery.map(this,function(elem,i){return callback.call(elem,i,elem);}));},andSelf:function(){return this.add(this.prevObject);},data:function(key,value){var parts=key.split(".");parts[1]=parts[1]?"."+parts[1]:"";if(value===undefined){var data=this.triggerHandler("getData"+parts[1]+"!",[parts[0]]);if(data===undefined&&this.length)data=jQuery.data(this[0],key);return data===undefined&&parts[1]?this.data(parts[0]):data;}else -return this.trigger("setData"+parts[1]+"!",[parts[0],value]).each(function(){jQuery.data(this,key,value);});},removeData:function(key){return this.each(function(){jQuery.removeData(this,key);});},domManip:function(args,table,reverse,callback){var clone=this.length>1,elems;return this.each(function(){if(!elems){elems=jQuery.clean(args,this.ownerDocument);if(reverse)elems.reverse();}var obj=this;if(table&&jQuery.nodeName(this,"table")&&jQuery.nodeName(elems[0],"tr"))obj=this.getElementsByTagName("tbody")[0]||this.appendChild(this.ownerDocument.createElement("tbody"));var scripts=jQuery([]);jQuery.each(elems,function(){var elem=clone?jQuery(this).clone(true)[0]:this;if(jQuery.nodeName(elem,"script"))scripts=scripts.add(elem);else{if(elem.nodeType==1)scripts=scripts.add(jQuery("script",elem).remove());callback.call(obj,elem);}});scripts.each(evalScript);});}};jQuery.fn.init.prototype=jQuery.fn;function evalScript(i,elem){if(elem.src)jQuery.ajax({url:elem.src,async:false,dataType:"script"});else -jQuery.globalEval(elem.text||elem.textContent||elem.innerHTML||"");if(elem.parentNode)elem.parentNode.removeChild(elem);}function now(){return+new Date;}jQuery.extend=jQuery.fn.extend=function(){var target=arguments[0]||{},i=1,length=arguments.length,deep=false,options;if(target.constructor==Boolean){deep=target;target=arguments[1]||{};i=2;}if(typeof target!="object"&&typeof target!="function")target={};if(length==i){target=this;--i;}for(;i-1;}},swap:function(elem,options,callback){var old={};for(var name in options){old[name]=elem.style[name];elem.style[name]=options[name];}callback.call(elem);for(var name in options)elem.style[name]=old[name];},css:function(elem,name,force){if(name=="width"||name=="height"){var val,props={position:"absolute",visibility:"hidden",display:"block"},which=name=="width"?["Left","Right"]:["Top","Bottom"];function getWH(){val=name=="width"?elem.offsetWidth:elem.offsetHeight;var padding=0,border=0;jQuery.each(which,function(){padding+=parseFloat(jQuery.curCSS(elem,"padding"+this,true))||0;border+=parseFloat(jQuery.curCSS(elem,"border"+this+"Width",true))||0;});val-=Math.round(padding+border);}if(jQuery(elem).is(":visible"))getWH();else -jQuery.swap(elem,props,getWH);return Math.max(0,val);}return jQuery.curCSS(elem,name,force);},curCSS:function(elem,name,force){var ret,style=elem.style;function color(elem){if(!jQuery.browser.safari)return false;var ret=defaultView.getComputedStyle(elem,null);return!ret||ret.getPropertyValue("color")=="";}if(name=="opacity"&&jQuery.browser.msie){ret=jQuery.attr(style,"opacity");return ret==""?"1":ret;}if(jQuery.browser.opera&&name=="display"){var save=style.outline;style.outline="0 solid black";style.outline=save;}if(name.match(/float/i))name=styleFloat;if(!force&&style&&style[name])ret=style[name];else if(defaultView.getComputedStyle){if(name.match(/float/i))name="float";name=name.replace(/([A-Z])/g,"-$1").toLowerCase();var computedStyle=defaultView.getComputedStyle(elem,null);if(computedStyle&&!color(elem))ret=computedStyle.getPropertyValue(name);else{var swap=[],stack=[],a=elem,i=0;for(;a&&color(a);a=a.parentNode)stack.unshift(a);for(;i]*?)\/>/g,function(all,front,tag){return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?all:front+">";});var tags=jQuery.trim(elem).toLowerCase(),div=context.createElement("div");var wrap=!tags.indexOf("",""]||!tags.indexOf("",""]||tags.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"","
"]||!tags.indexOf("",""]||(!tags.indexOf("",""]||!tags.indexOf("",""]||jQuery.browser.msie&&[1,"div
","
"]||[0,"",""];div.innerHTML=wrap[1]+elem+wrap[2];while(wrap[0]--)div=div.lastChild;if(jQuery.browser.msie){var tbody=!tags.indexOf(""&&tags.indexOf("=0;--j)if(jQuery.nodeName(tbody[j],"tbody")&&!tbody[j].childNodes.length)tbody[j].parentNode.removeChild(tbody[j]);if(/^\s/.test(elem))div.insertBefore(context.createTextNode(elem.match(/^\s*/)[0]),div.firstChild);}elem=jQuery.makeArray(div.childNodes);}if(elem.length===0&&(!jQuery.nodeName(elem,"form")&&!jQuery.nodeName(elem,"select")))return;if(elem[0]==undefined||jQuery.nodeName(elem,"form")||elem.options)ret.push(elem);else -ret=jQuery.merge(ret,elem);});return ret;},attr:function(elem,name,value){if(!elem||elem.nodeType==3||elem.nodeType==8)return undefined;var notxml=!jQuery.isXMLDoc(elem),set=value!==undefined,msie=jQuery.browser.msie;name=notxml&&jQuery.props[name]||name;if(elem.tagName){var special=/href|src|style/.test(name);if(name=="selected"&&jQuery.browser.safari)elem.parentNode.selectedIndex;if(name in elem&¬xml&&!special){if(set){if(name=="type"&&jQuery.nodeName(elem,"input")&&elem.parentNode)throw"type property can't be changed";elem[name]=value;}if(jQuery.nodeName(elem,"form")&&elem.getAttributeNode(name))return elem.getAttributeNode(name).nodeValue;return elem[name];}if(msie&¬xml&&name=="style")return jQuery.attr(elem.style,"cssText",value);if(set)elem.setAttribute(name,""+value);var attr=msie&¬xml&&special?elem.getAttribute(name,2):elem.getAttribute(name);return attr===null?undefined:attr;}if(msie&&name=="opacity"){if(set){elem.zoom=1;elem.filter=(elem.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(value)+''=="NaN"?"":"alpha(opacity="+value*100+")");}return elem.filter&&elem.filter.indexOf("opacity=")>=0?(parseFloat(elem.filter.match(/opacity=([^)]*)/)[1])/100)+'':"";}name=name.replace(/-([a-z])/ig,function(all,letter){return letter.toUpperCase();});if(set)elem[name]=value;return elem[name];},trim:function(text){return(text||"").replace(/^\s+|\s+$/g,"");},makeArray:function(array){var ret=[];if(array!=null){var i=array.length;if(i==null||array.split||array.setInterval||array.call)ret[0]=array;else -while(i)ret[--i]=array[i];}return ret;},inArray:function(elem,array){for(var i=0,length=array.length;i*",this).remove();while(this.firstChild)this.removeChild(this.firstChild);}},function(name,fn){jQuery.fn[name]=function(){return this.each(fn,arguments);};});jQuery.each(["Height","Width"],function(i,name){var type=name.toLowerCase();jQuery.fn[type]=function(size){return this[0]==window?jQuery.browser.opera&&document.body["client"+name]||jQuery.browser.safari&&window["inner"+name]||document.compatMode=="CSS1Compat"&&document.documentElement["client"+name]||document.body["client"+name]:this[0]==document?Math.max(Math.max(document.body["scroll"+name],document.documentElement["scroll"+name]),Math.max(document.body["offset"+name],document.documentElement["offset"+name])):size==undefined?(this.length?jQuery.css(this[0],type):null):this.css(type,size.constructor==String?size:size+"px");};});function num(elem,prop){return elem[0]&&parseInt(jQuery.curCSS(elem[0],prop,true),10)||0;}var chars=jQuery.browser.safari&&parseInt(jQuery.browser.version)<417?"(?:[\\w*_-]|\\\\.)":"(?:[\\w\u0128-\uFFFF*_-]|\\\\.)",quickChild=new RegExp("^>\\s*("+chars+"+)"),quickID=new RegExp("^("+chars+"+)(#)("+chars+"+)"),quickClass=new RegExp("^([#.]?)("+chars+"*)");jQuery.extend({expr:{"":function(a,i,m){return m[2]=="*"||jQuery.nodeName(a,m[2]);},"#":function(a,i,m){return a.getAttribute("id")==m[2];},":":{lt:function(a,i,m){return im[3]-0;},nth:function(a,i,m){return m[3]-0==i;},eq:function(a,i,m){return m[3]-0==i;},first:function(a,i){return i==0;},last:function(a,i,m,r){return i==r.length-1;},even:function(a,i){return i%2==0;},odd:function(a,i){return i%2;},"first-child":function(a){return a.parentNode.getElementsByTagName("*")[0]==a;},"last-child":function(a){return jQuery.nth(a.parentNode.lastChild,1,"previousSibling")==a;},"only-child":function(a){return!jQuery.nth(a.parentNode.lastChild,2,"previousSibling");},parent:function(a){return a.firstChild;},empty:function(a){return!a.firstChild;},contains:function(a,i,m){return(a.textContent||a.innerText||jQuery(a).text()||"").indexOf(m[3])>=0;},visible:function(a){return"hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden";},hidden:function(a){return"hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden";},enabled:function(a){return!a.disabled;},disabled:function(a){return a.disabled;},checked:function(a){return a.checked;},selected:function(a){return a.selected||jQuery.attr(a,"selected");},text:function(a){return"text"==a.type;},radio:function(a){return"radio"==a.type;},checkbox:function(a){return"checkbox"==a.type;},file:function(a){return"file"==a.type;},password:function(a){return"password"==a.type;},submit:function(a){return"submit"==a.type;},image:function(a){return"image"==a.type;},reset:function(a){return"reset"==a.type;},button:function(a){return"button"==a.type||jQuery.nodeName(a,"button");},input:function(a){return/input|select|textarea|button/i.test(a.nodeName);},has:function(a,i,m){return jQuery.find(m[3],a).length;},header:function(a){return/h\d/i.test(a.nodeName);},animated:function(a){return jQuery.grep(jQuery.timers,function(fn){return a==fn.elem;}).length;}}},parse:[/^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,/^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,new RegExp("^([:.#]*)("+chars+"+)")],multiFilter:function(expr,elems,not){var old,cur=[];while(expr&&expr!=old){old=expr;var f=jQuery.filter(expr,elems,not);expr=f.t.replace(/^\s*,\s*/,"");cur=not?elems=f.r:jQuery.merge(cur,f.r);}return cur;},find:function(t,context){if(typeof t!="string")return[t];if(context&&context.nodeType!=1&&context.nodeType!=9)return[];context=context||document;var ret=[context],done=[],last,nodeName;while(t&&last!=t){var r=[];last=t;t=jQuery.trim(t);var foundToken=false,re=quickChild,m=re.exec(t);if(m){nodeName=m[1].toUpperCase();for(var i=0;ret[i];i++)for(var c=ret[i].firstChild;c;c=c.nextSibling)if(c.nodeType==1&&(nodeName=="*"||c.nodeName.toUpperCase()==nodeName))r.push(c);ret=r;t=t.replace(re,"");if(t.indexOf(" ")==0)continue;foundToken=true;}else{re=/^([>+~])\s*(\w*)/i;if((m=re.exec(t))!=null){r=[];var merge={};nodeName=m[2].toUpperCase();m=m[1];for(var j=0,rl=ret.length;j=0;if(!not&&pass||not&&!pass)tmp.push(r[i]);}return tmp;},filter:function(t,r,not){var last;while(t&&t!=last){last=t;var p=jQuery.parse,m;for(var i=0;p[i];i++){m=p[i].exec(t);if(m){t=t.substring(m[0].length);m[2]=m[2].replace(/\\/g,"");break;}}if(!m)break;if(m[1]==":"&&m[2]=="not")r=isSimple.test(m[3])?jQuery.filter(m[3],r,true).r:jQuery(r).not(m[3]);else if(m[1]==".")r=jQuery.classFilter(r,m[2],not);else if(m[1]=="["){var tmp=[],type=m[3];for(var i=0,rl=r.length;i=0)^not)tmp.push(a);}r=tmp;}else if(m[1]==":"&&m[2]=="nth-child"){var merge={},tmp=[],test=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(m[3]=="even"&&"2n"||m[3]=="odd"&&"2n+1"||!/\D/.test(m[3])&&"0n+"+m[3]||m[3]),first=(test[1]+(test[2]||1))-0,last=test[3]-0;for(var i=0,rl=r.length;i=0)add=true;if(add^not)tmp.push(node);}r=tmp;}else{var fn=jQuery.expr[m[1]];if(typeof fn=="object")fn=fn[m[2]];if(typeof fn=="string")fn=eval("false||function(a,i){return "+fn+";}");r=jQuery.grep(r,function(elem,i){return fn(elem,i,m,r);},not);}}return{r:r,t:t};},dir:function(elem,dir){var matched=[],cur=elem[dir];while(cur&&cur!=document){if(cur.nodeType==1)matched.push(cur);cur=cur[dir];}return matched;},nth:function(cur,result,dir,elem){result=result||1;var num=0;for(;cur;cur=cur[dir])if(cur.nodeType==1&&++num==result)break;return cur;},sibling:function(n,elem){var r=[];for(;n;n=n.nextSibling){if(n.nodeType==1&&n!=elem)r.push(n);}return r;}});jQuery.event={add:function(elem,types,handler,data){if(elem.nodeType==3||elem.nodeType==8)return;if(jQuery.browser.msie&&elem.setInterval)elem=window;if(!handler.guid)handler.guid=this.guid++;if(data!=undefined){var fn=handler;handler=this.proxy(fn,function(){return fn.apply(this,arguments);});handler.data=data;}var events=jQuery.data(elem,"events")||jQuery.data(elem,"events",{}),handle=jQuery.data(elem,"handle")||jQuery.data(elem,"handle",function(){if(typeof jQuery!="undefined"&&!jQuery.event.triggered)return jQuery.event.handle.apply(arguments.callee.elem,arguments);});handle.elem=elem;jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];handler.type=parts[1];var handlers=events[type];if(!handlers){handlers=events[type]={};if(!jQuery.event.special[type]||jQuery.event.special[type].setup.call(elem)===false){if(elem.addEventListener)elem.addEventListener(type,handle,false);else if(elem.attachEvent)elem.attachEvent("on"+type,handle);}}handlers[handler.guid]=handler;jQuery.event.global[type]=true;});elem=null;},guid:1,global:{},remove:function(elem,types,handler){if(elem.nodeType==3||elem.nodeType==8)return;var events=jQuery.data(elem,"events"),ret,index;if(events){if(types==undefined||(typeof types=="string"&&types.charAt(0)=="."))for(var type in events)this.remove(elem,type+(types||""));else{if(types.type){handler=types.handler;types=types.type;}jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];if(events[type]){if(handler)delete events[type][handler.guid];else -for(handler in events[type])if(!parts[1]||events[type][handler].type==parts[1])delete events[type][handler];for(ret in events[type])break;if(!ret){if(!jQuery.event.special[type]||jQuery.event.special[type].teardown.call(elem)===false){if(elem.removeEventListener)elem.removeEventListener(type,jQuery.data(elem,"handle"),false);else if(elem.detachEvent)elem.detachEvent("on"+type,jQuery.data(elem,"handle"));}ret=null;delete events[type];}}});}for(ret in events)break;if(!ret){var handle=jQuery.data(elem,"handle");if(handle)handle.elem=null;jQuery.removeData(elem,"events");jQuery.removeData(elem,"handle");}}},trigger:function(type,data,elem,donative,extra){data=jQuery.makeArray(data);if(type.indexOf("!")>=0){type=type.slice(0,-1);var exclusive=true;}if(!elem){if(this.global[type])jQuery("*").add([window,document]).trigger(type,data);}else{if(elem.nodeType==3||elem.nodeType==8)return undefined;var val,ret,fn=jQuery.isFunction(elem[type]||null),event=!data[0]||!data[0].preventDefault;if(event){data.unshift({type:type,target:elem,preventDefault:function(){},stopPropagation:function(){},timeStamp:now()});data[0][expando]=true;}data[0].type=type;if(exclusive)data[0].exclusive=true;var handle=jQuery.data(elem,"handle");if(handle)val=handle.apply(elem,data);if((!fn||(jQuery.nodeName(elem,'a')&&type=="click"))&&elem["on"+type]&&elem["on"+type].apply(elem,data)===false)val=false;if(event)data.shift();if(extra&&jQuery.isFunction(extra)){ret=extra.apply(elem,val==null?data:data.concat(val));if(ret!==undefined)val=ret;}if(fn&&donative!==false&&val!==false&&!(jQuery.nodeName(elem,'a')&&type=="click")){this.triggered=true;try{elem[type]();}catch(e){}}this.triggered=false;}return val;},handle:function(event){var val,ret,namespace,all,handlers;event=arguments[0]=jQuery.event.fix(event||window.event);namespace=event.type.split(".");event.type=namespace[0];namespace=namespace[1];all=!namespace&&!event.exclusive;handlers=(jQuery.data(this,"events")||{})[event.type];for(var j in handlers){var handler=handlers[j];if(all||handler.type==namespace){event.handler=handler;event.data=handler.data;ret=handler.apply(this,arguments);if(val!==false)val=ret;if(ret===false){event.preventDefault();event.stopPropagation();}}}return val;},fix:function(event){if(event[expando]==true)return event;var originalEvent=event;event={originalEvent:originalEvent};var props="altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target timeStamp toElement type view wheelDelta which".split(" ");for(var i=props.length;i;i--)event[props[i]]=originalEvent[props[i]];event[expando]=true;event.preventDefault=function(){if(originalEvent.preventDefault)originalEvent.preventDefault();originalEvent.returnValue=false;};event.stopPropagation=function(){if(originalEvent.stopPropagation)originalEvent.stopPropagation();originalEvent.cancelBubble=true;};event.timeStamp=event.timeStamp||now();if(!event.target)event.target=event.srcElement||document;if(event.target.nodeType==3)event.target=event.target.parentNode;if(!event.relatedTarget&&event.fromElement)event.relatedTarget=event.fromElement==event.target?event.toElement:event.fromElement;if(event.pageX==null&&event.clientX!=null){var doc=document.documentElement,body=document.body;event.pageX=event.clientX+(doc&&doc.scrollLeft||body&&body.scrollLeft||0)-(doc.clientLeft||0);event.pageY=event.clientY+(doc&&doc.scrollTop||body&&body.scrollTop||0)-(doc.clientTop||0);}if(!event.which&&((event.charCode||event.charCode===0)?event.charCode:event.keyCode))event.which=event.charCode||event.keyCode;if(!event.metaKey&&event.ctrlKey)event.metaKey=event.ctrlKey;if(!event.which&&event.button)event.which=(event.button&1?1:(event.button&2?3:(event.button&4?2:0)));return event;},proxy:function(fn,proxy){proxy.guid=fn.guid=fn.guid||proxy.guid||this.guid++;return proxy;},special:{ready:{setup:function(){bindReady();return;},teardown:function(){return;}},mouseenter:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseover",jQuery.event.special.mouseenter.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseover",jQuery.event.special.mouseenter.handler);return true;},handler:function(event){if(withinElement(event,this))return true;event.type="mouseenter";return jQuery.event.handle.apply(this,arguments);}},mouseleave:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseout",jQuery.event.special.mouseleave.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseout",jQuery.event.special.mouseleave.handler);return true;},handler:function(event){if(withinElement(event,this))return true;event.type="mouseleave";return jQuery.event.handle.apply(this,arguments);}}}};jQuery.fn.extend({bind:function(type,data,fn){return type=="unload"?this.one(type,data,fn):this.each(function(){jQuery.event.add(this,type,fn||data,fn&&data);});},one:function(type,data,fn){var one=jQuery.event.proxy(fn||data,function(event){jQuery(this).unbind(event,one);return(fn||data).apply(this,arguments);});return this.each(function(){jQuery.event.add(this,type,one,fn&&data);});},unbind:function(type,fn){return this.each(function(){jQuery.event.remove(this,type,fn);});},trigger:function(type,data,fn){return this.each(function(){jQuery.event.trigger(type,data,this,true,fn);});},triggerHandler:function(type,data,fn){return this[0]&&jQuery.event.trigger(type,data,this[0],false,fn);},toggle:function(fn){var args=arguments,i=1;while(i=0){var selector=url.slice(off,url.length);url=url.slice(0,off);}callback=callback||function(){};var type="GET";if(params)if(jQuery.isFunction(params)){callback=params;params=null;}else{params=jQuery.param(params);type="POST";}var self=this;jQuery.ajax({url:url,type:type,dataType:"html",data:params,complete:function(res,status){if(status=="success"||status=="notmodified")self.html(selector?jQuery("
").append(res.responseText.replace(//g,"")).find(selector):res.responseText);self.each(callback,[res.responseText,status,res]);}});return this;},serialize:function(){return jQuery.param(this.serializeArray());},serializeArray:function(){return this.map(function(){return jQuery.nodeName(this,"form")?jQuery.makeArray(this.elements):this;}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password/i.test(this.type));}).map(function(i,elem){var val=jQuery(this).val();return val==null?null:val.constructor==Array?jQuery.map(val,function(val,i){return{name:elem.name,value:val};}):{name:elem.name,value:val};}).get();}});jQuery.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(i,o){jQuery.fn[o]=function(f){return this.bind(o,f);};});var jsc=now();jQuery.extend({get:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data=null;}return jQuery.ajax({type:"GET",url:url,data:data,success:callback,dataType:type});},getScript:function(url,callback){return jQuery.get(url,null,callback,"script");},getJSON:function(url,data,callback){return jQuery.get(url,data,callback,"json");},post:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data={};}return jQuery.ajax({type:"POST",url:url,data:data,success:callback,dataType:type});},ajaxSetup:function(settings){jQuery.extend(jQuery.ajaxSettings,settings);},ajaxSettings:{url:location.href,global:true,type:"GET",timeout:0,contentType:"application/x-www-form-urlencoded",processData:true,async:true,data:null,username:null,password:null,accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(s){s=jQuery.extend(true,s,jQuery.extend(true,{},jQuery.ajaxSettings,s));var jsonp,jsre=/=\?(&|$)/g,status,data,type=s.type.toUpperCase();if(s.data&&s.processData&&typeof s.data!="string")s.data=jQuery.param(s.data);if(s.dataType=="jsonp"){if(type=="GET"){if(!s.url.match(jsre))s.url+=(s.url.match(/\?/)?"&":"?")+(s.jsonp||"callback")+"=?";}else if(!s.data||!s.data.match(jsre))s.data=(s.data?s.data+"&":"")+(s.jsonp||"callback")+"=?";s.dataType="json";}if(s.dataType=="json"&&(s.data&&s.data.match(jsre)||s.url.match(jsre))){jsonp="jsonp"+jsc++;if(s.data)s.data=(s.data+"").replace(jsre,"="+jsonp+"$1");s.url=s.url.replace(jsre,"="+jsonp+"$1");s.dataType="script";window[jsonp]=function(tmp){data=tmp;success();complete();window[jsonp]=undefined;try{delete window[jsonp];}catch(e){}if(head)head.removeChild(script);};}if(s.dataType=="script"&&s.cache==null)s.cache=false;if(s.cache===false&&type=="GET"){var ts=now();var ret=s.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+ts+"$2");s.url=ret+((ret==s.url)?(s.url.match(/\?/)?"&":"?")+"_="+ts:"");}if(s.data&&type=="GET"){s.url+=(s.url.match(/\?/)?"&":"?")+s.data;s.data=null;}if(s.global&&!jQuery.active++)jQuery.event.trigger("ajaxStart");var remote=/^(?:\w+:)?\/\/([^\/?#]+)/;if(s.dataType=="script"&&type=="GET"&&remote.test(s.url)&&remote.exec(s.url)[1]!=location.host){var head=document.getElementsByTagName("head")[0];var script=document.createElement("script");script.src=s.url;if(s.scriptCharset)script.charset=s.scriptCharset;if(!jsonp){var done=false;script.onload=script.onreadystatechange=function(){if(!done&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){done=true;success();complete();head.removeChild(script);}};}head.appendChild(script);return undefined;}var requestDone=false;var xhr=window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();if(s.username)xhr.open(type,s.url,s.async,s.username,s.password);else -xhr.open(type,s.url,s.async);try{if(s.data)xhr.setRequestHeader("Content-Type",s.contentType);if(s.ifModified)xhr.setRequestHeader("If-Modified-Since",jQuery.lastModified[s.url]||"Thu, 01 Jan 1970 00:00:00 GMT");xhr.setRequestHeader("X-Requested-With","XMLHttpRequest");xhr.setRequestHeader("Accept",s.dataType&&s.accepts[s.dataType]?s.accepts[s.dataType]+", */*":s.accepts._default);}catch(e){}if(s.beforeSend&&s.beforeSend(xhr,s)===false){s.global&&jQuery.active--;xhr.abort();return false;}if(s.global)jQuery.event.trigger("ajaxSend",[xhr,s]);var onreadystatechange=function(isTimeout){if(!requestDone&&xhr&&(xhr.readyState==4||isTimeout=="timeout")){requestDone=true;if(ival){clearInterval(ival);ival=null;}status=isTimeout=="timeout"&&"timeout"||!jQuery.httpSuccess(xhr)&&"error"||s.ifModified&&jQuery.httpNotModified(xhr,s.url)&&"notmodified"||"success";if(status=="success"){try{data=jQuery.httpData(xhr,s.dataType,s.dataFilter);}catch(e){status="parsererror";}}if(status=="success"){var modRes;try{modRes=xhr.getResponseHeader("Last-Modified");}catch(e){}if(s.ifModified&&modRes)jQuery.lastModified[s.url]=modRes;if(!jsonp)success();}else -jQuery.handleError(s,xhr,status);complete();if(s.async)xhr=null;}};if(s.async){var ival=setInterval(onreadystatechange,13);if(s.timeout>0)setTimeout(function(){if(xhr){xhr.abort();if(!requestDone)onreadystatechange("timeout");}},s.timeout);}try{xhr.send(s.data);}catch(e){jQuery.handleError(s,xhr,null,e);}if(!s.async)onreadystatechange();function success(){if(s.success)s.success(data,status);if(s.global)jQuery.event.trigger("ajaxSuccess",[xhr,s]);}function complete(){if(s.complete)s.complete(xhr,status);if(s.global)jQuery.event.trigger("ajaxComplete",[xhr,s]);if(s.global&&!--jQuery.active)jQuery.event.trigger("ajaxStop");}return xhr;},handleError:function(s,xhr,status,e){if(s.error)s.error(xhr,status,e);if(s.global)jQuery.event.trigger("ajaxError",[xhr,s,e]);},active:0,httpSuccess:function(xhr){try{return!xhr.status&&location.protocol=="file:"||(xhr.status>=200&&xhr.status<300)||xhr.status==304||xhr.status==1223||jQuery.browser.safari&&xhr.status==undefined;}catch(e){}return false;},httpNotModified:function(xhr,url){try{var xhrRes=xhr.getResponseHeader("Last-Modified");return xhr.status==304||xhrRes==jQuery.lastModified[url]||jQuery.browser.safari&&xhr.status==undefined;}catch(e){}return false;},httpData:function(xhr,type,filter){var ct=xhr.getResponseHeader("content-type"),xml=type=="xml"||!type&&ct&&ct.indexOf("xml")>=0,data=xml?xhr.responseXML:xhr.responseText;if(xml&&data.documentElement.tagName=="parsererror")throw"parsererror";if(filter)data=filter(data,type);if(type=="script")jQuery.globalEval(data);if(type=="json")data=eval("("+data+")");return data;},param:function(a){var s=[];if(a.constructor==Array||a.jquery)jQuery.each(a,function(){s.push(encodeURIComponent(this.name)+"="+encodeURIComponent(this.value));});else -for(var j in a)if(a[j]&&a[j].constructor==Array)jQuery.each(a[j],function(){s.push(encodeURIComponent(j)+"="+encodeURIComponent(this));});else -s.push(encodeURIComponent(j)+"="+encodeURIComponent(jQuery.isFunction(a[j])?a[j]():a[j]));return s.join("&").replace(/%20/g,"+");}});jQuery.fn.extend({show:function(speed,callback){return speed?this.animate({height:"show",width:"show",opacity:"show"},speed,callback):this.filter(":hidden").each(function(){this.style.display=this.oldblock||"";if(jQuery.css(this,"display")=="none"){var elem=jQuery("<"+this.tagName+" />").appendTo("body");this.style.display=elem.css("display");if(this.style.display=="none")this.style.display="block";elem.remove();}}).end();},hide:function(speed,callback){return speed?this.animate({height:"hide",width:"hide",opacity:"hide"},speed,callback):this.filter(":visible").each(function(){this.oldblock=this.oldblock||jQuery.css(this,"display");this.style.display="none";}).end();},_toggle:jQuery.fn.toggle,toggle:function(fn,fn2){return jQuery.isFunction(fn)&&jQuery.isFunction(fn2)?this._toggle.apply(this,arguments):fn?this.animate({height:"toggle",width:"toggle",opacity:"toggle"},fn,fn2):this.each(function(){jQuery(this)[jQuery(this).is(":hidden")?"show":"hide"]();});},slideDown:function(speed,callback){return this.animate({height:"show"},speed,callback);},slideUp:function(speed,callback){return this.animate({height:"hide"},speed,callback);},slideToggle:function(speed,callback){return this.animate({height:"toggle"},speed,callback);},fadeIn:function(speed,callback){return this.animate({opacity:"show"},speed,callback);},fadeOut:function(speed,callback){return this.animate({opacity:"hide"},speed,callback);},fadeTo:function(speed,to,callback){return this.animate({opacity:to},speed,callback);},animate:function(prop,speed,easing,callback){var optall=jQuery.speed(speed,easing,callback);return this[optall.queue===false?"each":"queue"](function(){if(this.nodeType!=1)return false;var opt=jQuery.extend({},optall),p,hidden=jQuery(this).is(":hidden"),self=this;for(p in prop){if(prop[p]=="hide"&&hidden||prop[p]=="show"&&!hidden)return opt.complete.call(this);if(p=="height"||p=="width"){opt.display=jQuery.css(this,"display");opt.overflow=this.style.overflow;}}if(opt.overflow!=null)this.style.overflow="hidden";opt.curAnim=jQuery.extend({},prop);jQuery.each(prop,function(name,val){var e=new jQuery.fx(self,opt,name);if(/toggle|show|hide/.test(val))e[val=="toggle"?hidden?"show":"hide":val](prop);else{var parts=val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),start=e.cur(true)||0;if(parts){var end=parseFloat(parts[2]),unit=parts[3]||"px";if(unit!="px"){self.style[name]=(end||1)+unit;start=((end||1)/e.cur(true))*start;self.style[name]=start+unit;}if(parts[1])end=((parts[1]=="-="?-1:1)*end)+start;e.custom(start,end,unit);}else -e.custom(start,val,"");}});return true;});},queue:function(type,fn){if(jQuery.isFunction(type)||(type&&type.constructor==Array)){fn=type;type="fx";}if(!type||(typeof type=="string"&&!fn))return queue(this[0],type);return this.each(function(){if(fn.constructor==Array)queue(this,type,fn);else{queue(this,type).push(fn);if(queue(this,type).length==1)fn.call(this);}});},stop:function(clearQueue,gotoEnd){var timers=jQuery.timers;if(clearQueue)this.queue([]);this.each(function(){for(var i=timers.length-1;i>=0;i--)if(timers[i].elem==this){if(gotoEnd)timers[i](true);timers.splice(i,1);}});if(!gotoEnd)this.dequeue();return this;}});var queue=function(elem,type,array){if(elem){type=type||"fx";var q=jQuery.data(elem,type+"queue");if(!q||array)q=jQuery.data(elem,type+"queue",jQuery.makeArray(array));}return q;};jQuery.fn.dequeue=function(type){type=type||"fx";return this.each(function(){var q=queue(this,type);q.shift();if(q.length)q[0].call(this);});};jQuery.extend({speed:function(speed,easing,fn){var opt=speed&&speed.constructor==Object?speed:{complete:fn||!fn&&easing||jQuery.isFunction(speed)&&speed,duration:speed,easing:fn&&easing||easing&&easing.constructor!=Function&&easing};opt.duration=(opt.duration&&opt.duration.constructor==Number?opt.duration:jQuery.fx.speeds[opt.duration])||jQuery.fx.speeds.def;opt.old=opt.complete;opt.complete=function(){if(opt.queue!==false)jQuery(this).dequeue();if(jQuery.isFunction(opt.old))opt.old.call(this);};return opt;},easing:{linear:function(p,n,firstNum,diff){return firstNum+diff*p;},swing:function(p,n,firstNum,diff){return((-Math.cos(p*Math.PI)/2)+0.5)*diff+firstNum;}},timers:[],timerId:null,fx:function(elem,options,prop){this.options=options;this.elem=elem;this.prop=prop;if(!options.orig)options.orig={};}});jQuery.fx.prototype={update:function(){if(this.options.step)this.options.step.call(this.elem,this.now,this);(jQuery.fx.step[this.prop]||jQuery.fx.step._default)(this);if(this.prop=="height"||this.prop=="width")this.elem.style.display="block";},cur:function(force){if(this.elem[this.prop]!=null&&this.elem.style[this.prop]==null)return this.elem[this.prop];var r=parseFloat(jQuery.css(this.elem,this.prop,force));return r&&r>-10000?r:parseFloat(jQuery.curCSS(this.elem,this.prop))||0;},custom:function(from,to,unit){this.startTime=now();this.start=from;this.end=to;this.unit=unit||this.unit||"px";this.now=this.start;this.pos=this.state=0;this.update();var self=this;function t(gotoEnd){return self.step(gotoEnd);}t.elem=this.elem;jQuery.timers.push(t);if(jQuery.timerId==null){jQuery.timerId=setInterval(function(){var timers=jQuery.timers;for(var i=0;ithis.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var done=true;for(var i in this.options.curAnim)if(this.options.curAnim[i]!==true)done=false;if(done){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(jQuery.css(this.elem,"display")=="none")this.elem.style.display="block";}if(this.options.hide)this.elem.style.display="none";if(this.options.hide||this.options.show)for(var p in this.options.curAnim)jQuery.attr(this.elem.style,p,this.options.orig[p]);}if(done)this.options.complete.call(this.elem);return false;}else{var n=t-this.startTime;this.state=n/this.options.duration;this.pos=jQuery.easing[this.options.easing||(jQuery.easing.swing?"swing":"linear")](this.state,n,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update();}return true;}};jQuery.extend(jQuery.fx,{speeds:{slow:600,fast:200,def:400},step:{scrollLeft:function(fx){fx.elem.scrollLeft=fx.now;},scrollTop:function(fx){fx.elem.scrollTop=fx.now;},opacity:function(fx){jQuery.attr(fx.elem.style,"opacity",fx.now);},_default:function(fx){fx.elem.style[fx.prop]=fx.now+fx.unit;}}});jQuery.fn.offset=function(){var left=0,top=0,elem=this[0],results;if(elem)with(jQuery.browser){var parent=elem.parentNode,offsetChild=elem,offsetParent=elem.offsetParent,doc=elem.ownerDocument,safari2=safari&&parseInt(version)<522&&!/adobeair/i.test(userAgent),css=jQuery.curCSS,fixed=css(elem,"position")=="fixed";if(elem.getBoundingClientRect){var box=elem.getBoundingClientRect();add(box.left+Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),box.top+Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));add(-doc.documentElement.clientLeft,-doc.documentElement.clientTop);}else{add(elem.offsetLeft,elem.offsetTop);while(offsetParent){add(offsetParent.offsetLeft,offsetParent.offsetTop);if(mozilla&&!/^t(able|d|h)$/i.test(offsetParent.tagName)||safari&&!safari2)border(offsetParent);if(!fixed&&css(offsetParent,"position")=="fixed")fixed=true;offsetChild=/^body$/i.test(offsetParent.tagName)?offsetChild:offsetParent;offsetParent=offsetParent.offsetParent;}while(parent&&parent.tagName&&!/^body|html$/i.test(parent.tagName)){if(!/^inline|table.*$/i.test(css(parent,"display")))add(-parent.scrollLeft,-parent.scrollTop);if(mozilla&&css(parent,"overflow")!="visible")border(parent);parent=parent.parentNode;}if((safari2&&(fixed||css(offsetChild,"position")=="absolute"))||(mozilla&&css(offsetChild,"position")!="absolute"))add(-doc.body.offsetLeft,-doc.body.offsetTop);if(fixed)add(Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));}results={top:top,left:left};}function border(elem){add(jQuery.curCSS(elem,"borderLeftWidth",true),jQuery.curCSS(elem,"borderTopWidth",true));}function add(l,t){left+=parseInt(l,10)||0;top+=parseInt(t,10)||0;}return results;};jQuery.fn.extend({position:function(){var left=0,top=0,results;if(this[0]){var offsetParent=this.offsetParent(),offset=this.offset(),parentOffset=/^body|html$/i.test(offsetParent[0].tagName)?{top:0,left:0}:offsetParent.offset();offset.top-=num(this,'marginTop');offset.left-=num(this,'marginLeft');parentOffset.top+=num(offsetParent,'borderTopWidth');parentOffset.left+=num(offsetParent,'borderLeftWidth');results={top:offset.top-parentOffset.top,left:offset.left-parentOffset.left};}return results;},offsetParent:function(){var offsetParent=this[0].offsetParent;while(offsetParent&&(!/^body|html$/i.test(offsetParent.tagName)&&jQuery.css(offsetParent,'position')=='static'))offsetParent=offsetParent.offsetParent;return jQuery(offsetParent);}});jQuery.each(['Left','Top'],function(i,name){var method='scroll'+name;jQuery.fn[method]=function(val){if(!this[0])return;return val!=undefined?this.each(function(){this==window||this==document?window.scrollTo(!i?val:jQuery(window).scrollLeft(),i?val:jQuery(window).scrollTop()):this[method]=val;}):this[0]==window||this[0]==document?self[i?'pageYOffset':'pageXOffset']||jQuery.boxModel&&document.documentElement[method]||document.body[method]:this[0][method];};});jQuery.each(["Height","Width"],function(i,name){var tl=i?"Left":"Top",br=i?"Right":"Bottom";jQuery.fn["inner"+name]=function(){return this[name.toLowerCase()]()+num(this,"padding"+tl)+num(this,"padding"+br);};jQuery.fn["outer"+name]=function(margin){return this["inner"+name]()+num(this,"border"+tl+"Width")+num(this,"border"+br+"Width")+(margin?num(this,"margin"+tl)+num(this,"margin"+br):0);};});})(); \ No newline at end of file diff --git a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/js/quicksearch.js b/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/js/quicksearch.js deleted file mode 100644 index ef9343c7c..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/js/quicksearch.js +++ /dev/null @@ -1,114 +0,0 @@ -/** - * - * JQuery QuickSearch - Hook up a form field to hide non-matching elements. - * $Id: quicksearch.js 53 2009-01-07 02:52:03Z deveiant $ - * - * Author: Michael Granger - * - */ -jQuery.fn.quicksearch = function( target, searchElems, options ) { - // console.debug( "Quicksearch fn" ); - - var settings = { - delay: 250, - clearButton: false, - highlightMatches: false, - focusOnLoad: false, - noSearchResultsIndicator: null - }; - if ( options ) $.extend( settings, options ); - - return jQuery(this).each( function() { - // console.debug( "Creating a new quicksearch on %o for %o", this, searchElems ); - new jQuery.quicksearch( this, searchElems, settings ); - }); -}; - - -jQuery.quicksearch = function( searchBox, searchElems, settings ) { - var timeout; - var boxdiv = $(searchBox).parents('div').eq(0); - - function init() { - setupKeyEventHandlers(); - focusOnLoad(); - }; - - function setupKeyEventHandlers() { - // console.debug( "Hooking up the 'keypress' event to %o", searchBox ); - $(searchBox). - unbind( 'keyup' ). - keyup( function(e) { return onSearchKey( e.keyCode ); }); - $(searchBox). - unbind( 'keypress' ). - keypress( function(e) { - switch( e.which ) { - // Execute the search on Enter, Tab, or Newline - case 9: - case 13: - case 10: - clearTimeout( timeout ); - e.preventDefault(); - doQuickSearch(); - break; - - // Allow backspace - case 8: - return true; - break; - - // Only allow valid search characters - default: - return validQSChar( e.charCode ); - } - }); - }; - - function focusOnLoad() { - if ( !settings.focusOnLoad ) return false; - $(searchBox).focus(); - }; - - function onSearchKey ( code ) { - clearTimeout( timeout ); - // console.debug( "...scheduling search." ); - timeout = setTimeout( doQuickSearch, settings.delay ); - }; - - function validQSChar( code ) { - var c = String.fromCharCode( code ); - return ( - (c == ':') || - (c >= 'a' && c <= 'z') || - (c >= 'A' && c <= 'Z') - ); - }; - - function doQuickSearch() { - var searchText = searchBox.value; - var pat = new RegExp( searchText, "im" ); - var shownCount = 0; - - if ( settings.noSearchResultsIndicator ) { - $('#' + settings.noSearchResultsIndicator).hide(); - } - - // All elements start out hidden - $(searchElems).each( function(index) { - var str = $(this).text(); - - if ( pat.test(str) ) { - shownCount += 1; - $(this).fadeIn(); - } else { - $(this).hide(); - } - }); - - if ( shownCount == 0 && settings.noSearchResultsIndicator ) { - $('#' + settings.noSearchResultsIndicator).slideDown(); - } - }; - - init(); -}; diff --git a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/js/thickbox-compressed.js b/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/js/thickbox-compressed.js deleted file mode 100644 index e67e0872c..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/generator/template/darkfish/js/thickbox-compressed.js +++ /dev/null @@ -1,10 +0,0 @@ -/* - * Thickbox 3 - One Box To Rule Them All. - * By Cody Lindley (http://www.codylindley.com) - * Copyright (c) 2007 cody lindley - * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php -*/ - -var tb_pathToImage = "../images/loadingAnimation.gif"; - -eval(function(p,a,c,k,e,r){e=function(c){return(c35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('$(o).2S(9(){1u(\'a.18, 3n.18, 3i.18\');1w=1p 1t();1w.L=2H});9 1u(b){$(b).s(9(){6 t=X.Q||X.1v||M;6 a=X.u||X.23;6 g=X.1N||P;19(t,a,g);X.2E();H P})}9 19(d,f,g){3m{3(2t o.v.J.2i==="2g"){$("v","11").r({A:"28%",z:"28%"});$("11").r("22","2Z");3(o.1Y("1F")===M){$("v").q("<4 5=\'B\'><4 5=\'8\'>");$("#B").s(G)}}n{3(o.1Y("B")===M){$("v").q("<4 5=\'B\'><4 5=\'8\'>");$("#B").s(G)}}3(1K()){$("#B").1J("2B")}n{$("#B").1J("2z")}3(d===M){d=""}$("v").q("<4 5=\'K\'><1I L=\'"+1w.L+"\' />");$(\'#K\').2y();6 h;3(f.O("?")!==-1){h=f.3l(0,f.O("?"))}n{h=f}6 i=/\\.2s$|\\.2q$|\\.2m$|\\.2l$|\\.2k$/;6 j=h.1C().2h(i);3(j==\'.2s\'||j==\'.2q\'||j==\'.2m\'||j==\'.2l\'||j==\'.2k\'){1D="";1G="";14="";1z="";1x="";R="";1n="";1r=P;3(g){E=$("a[@1N="+g+"]").36();25(D=0;((D&1d;&1d;2T &2R;"}n{1D=E[D].Q;1G=E[D].u;14="<1e 5=\'1U\'>&1d;&1d;&2O; 2N"}}n{1r=1b;1n="1t "+(D+1)+" 2L "+(E.1c)}}}S=1p 1t();S.1g=9(){S.1g=M;6 a=2x();6 x=a[0]-1M;6 y=a[1]-1M;6 b=S.z;6 c=S.A;3(b>x){c=c*(x/b);b=x;3(c>y){b=b*(y/c);c=y}}n 3(c>y){b=b*(y/c);c=y;3(b>x){c=c*(x/b);b=x}}13=b+30;1a=c+2G;$("#8").q("<1I 5=\'2F\' L=\'"+f+"\' z=\'"+b+"\' A=\'"+c+"\' 23=\'"+d+"\'/>"+"<4 5=\'2D\'>"+d+"<4 5=\'2C\'>"+1n+14+R+"<4 5=\'2A\'>1l 1k 1j 1s");$("#Z").s(G);3(!(14==="")){9 12(){3($(o).N("s",12)){$(o).N("s",12)}$("#8").C();$("v").q("<4 5=\'8\'>");19(1D,1G,g);H P}$("#1U").s(12)}3(!(R==="")){9 1i(){$("#8").C();$("v").q("<4 5=\'8\'>");19(1z,1x,g);H P}$("#1X").s(1i)}o.1h=9(e){3(e==M){I=2w.2v}n{I=e.2u}3(I==27){G()}n 3(I==3k){3(!(R=="")){o.1h="";1i()}}n 3(I==3j){3(!(14=="")){o.1h="";12()}}};16();$("#K").C();$("#1L").s(G);$("#8").r({Y:"T"})};S.L=f}n{6 l=f.2r(/^[^\\?]+\\??/,\'\');6 m=2p(l);13=(m[\'z\']*1)+30||3h;1a=(m[\'A\']*1)+3g||3f;W=13-30;V=1a-3e;3(f.O(\'2j\')!=-1){1E=f.1B(\'3d\');$("#15").C();3(m[\'1A\']!="1b"){$("#8").q("<4 5=\'2f\'><4 5=\'1H\'>"+d+"<4 5=\'2e\'>1l 1k 1j 1s ")}n{$("#B").N();$("#8").q(" ")}}n{3($("#8").r("Y")!="T"){3(m[\'1A\']!="1b"){$("#8").q("<4 5=\'2f\'><4 5=\'1H\'>"+d+"<4 5=\'2e\'>1l 1k 1j 1s<4 5=\'F\' J=\'z:"+W+"p;A:"+V+"p\'>")}n{$("#B").N();$("#8").q("<4 5=\'F\' 3c=\'3b\' J=\'z:"+W+"p;A:"+V+"p;\'>")}}n{$("#F")[0].J.z=W+"p";$("#F")[0].J.A=V+"p";$("#F")[0].3a=0;$("#1H").11(d)}}$("#Z").s(G);3(f.O(\'37\')!=-1){$("#F").q($(\'#\'+m[\'26\']).1T());$("#8").24(9(){$(\'#\'+m[\'26\']).q($("#F").1T())});16();$("#K").C();$("#8").r({Y:"T"})}n 3(f.O(\'2j\')!=-1){16();3($.1q.35){$("#K").C();$("#8").r({Y:"T"})}}n{$("#F").34(f+="&1y="+(1p 33().32()),9(){16();$("#K").C();1u("#F a.18");$("#8").r({Y:"T"})})}}3(!m[\'1A\']){o.21=9(e){3(e==M){I=2w.2v}n{I=e.2u}3(I==27){G()}}}}31(e){}}9 1m(){$("#K").C();$("#8").r({Y:"T"})}9 G(){$("#2Y").N("s");$("#Z").N("s");$("#8").2X("2W",9(){$(\'#8,#B,#1F\').2V("24").N().C()});$("#K").C();3(2t o.v.J.2i=="2g"){$("v","11").r({A:"1Z",z:"1Z"});$("11").r("22","")}o.1h="";o.21="";H P}9 16(){$("#8").r({2U:\'-\'+20((13/2),10)+\'p\',z:13+\'p\'});3(!(1V.1q.2Q&&1V.1q.2P<7)){$("#8").r({38:\'-\'+20((1a/2),10)+\'p\'})}}9 2p(a){6 b={};3(!a){H b}6 c=a.1B(/[;&]/);25(6 i=0;i - * - */ - -/* Base Green is: #6C8C22 */ - -*{ padding: 0; margin: 0; } - -body { - background: #efefef; - font: 14px "Helvetica Neue", Helvetica, Tahoma, sans-serif; -} -body.class, body.module, body.file { - margin-left: 40px; -} -body.file-popup { - font-size: 90%; - margin-left: 0; -} - -h1 { - font-size: 300%; - text-shadow: rgba(135,145,135,0.65) 2px 2px 3px; - color: #6C8C22; -} -h2,h3,h4 { margin-top: 1.5em; } - -:link, -:visited { - color: #6C8C22; - text-decoration: none; -} -:link:hover, -:visited:hover { - border-bottom: 1px dotted #6C8C22; -} - -pre { - background: #ddd; - padding: 0.5em 0; -} - - -/* @group Generic Classes */ - -.initially-hidden { - display: none; -} - -.quicksearch-field { - width: 98%; - background: #ddd; - border: 1px solid #aaa; - height: 1.5em; - -webkit-border-radius: 4px; -} -.quicksearch-field:focus { - background: #f1edba; -} - -.missing-docs { - font-size: 120%; - background: white url(images/wrench_orange.png) no-repeat 4px center; - color: #ccc; - line-height: 2em; - border: 1px solid #d00; - opacity: 1; - padding-left: 20px; - text-indent: 24px; - letter-spacing: 3px; - font-weight: bold; - -webkit-border-radius: 5px; - -moz-border-radius: 5px; -} - -.target-section { - border: 2px solid #dcce90; - border-left-width: 8px; - padding: 0 1em; - background: #fff3c2; -} - -/* @end */ - - -/* @group Index Page, Standalone file pages */ -body.indexpage { - margin: 1em 3em; -} -body.indexpage p, -body.indexpage div, -body.file p { - margin: 1em 0; -} - -.indexpage ul, -.file #documentation ul { - line-height: 160%; - list-style: none; -} -.indexpage ul :link, -.indexpage ul :visited { - font-size: 16px; -} - -.indexpage li, -.file #documentation li { - padding-left: 20px; - background: url(images/bullet_black.png) no-repeat left 4px; -} -.indexpage li.module { - background: url(images/package.png) no-repeat left 4px; -} -.indexpage li.class { - background: url(images/ruby.png) no-repeat left 4px; -} -.indexpage li.file { - background: url(images/page_white_text.png) no-repeat left 4px; -} -.file li p, -.indexpage li p { - margin: 0 0; -} - -/* @end */ - -/* @group Top-Level Structure */ - -.class #metadata, -.file #metadata, -.module #metadata { - float: left; - width: 260px; -} - -.class #documentation, -.file #documentation, -.module #documentation { - margin: 2em 1em 5em 300px; - min-width: 340px; -} - -.file #metadata { - margin: 0.8em; -} - -#validator-badges { - clear: both; - margin: 1em 1em 2em; -} - -/* @end */ - -/* @group Metadata Section */ -#metadata .section { - background-color: #dedede; - -moz-border-radius: 5px; - -webkit-border-radius: 5px; - border: 1px solid #aaa; - margin: 0 8px 16px; - font-size: 90%; - overflow: hidden; -} -#metadata h3.section-header { - margin: 0; - padding: 2px 8px; - background: #ccc; - color: #666; - -moz-border-radius-topleft: 4px; - -moz-border-radius-topright: 4px; - -webkit-border-top-left-radius: 4px; - -webkit-border-top-right-radius: 4px; - border-bottom: 1px solid #aaa; -} -#metadata #home-section h3.section-header { - border-bottom: 0; -} - -#metadata ul, -#metadata dl, -#metadata p { - padding: 8px; - list-style: none; -} - -#file-metadata ul { - padding-left: 28px; - list-style-image: url(images/page_green.png); -} - -dl.svninfo { - color: #666; - margin: 0; -} -dl.svninfo dt { - font-weight: bold; -} - -ul.link-list li { - white-space: nowrap; -} -ul.link-list .type { - font-size: 8px; - text-transform: uppercase; - color: white; - background: #969696; - padding: 2px 4px; - -webkit-border-radius: 5px; -} - -/* @end */ - - -/* @group Project Metadata Section */ -#project-metadata { - margin-top: 3em; -} - -.file #project-metadata { - margin-top: 0em; -} - -#project-metadata .section { - border: 1px solid #aaa; -} -#project-metadata h3.section-header { - border-bottom: 1px solid #aaa; - position: relative; -} -#project-metadata h3.section-header .search-toggle { - position: absolute; - right: 5px; -} - - -#project-metadata form { - color: #777; - background: #ccc; - padding: 8px 8px 16px; - border-bottom: 1px solid #bbb; -} -#project-metadata fieldset { - border: 0; -} - -#no-class-search-results { - margin: 0 auto 1em; - text-align: center; - font-size: 14px; - font-weight: bold; - color: #aaa; -} - -/* @end */ - - -/* @group Documentation Section */ -#description { - font-size: 100%; - color: #333; -} - -#description p { - margin: 1em 0.4em; -} - -#description li p { - margin: 0; -} - -#description ul { - margin-left: 1.5em; -} -#description ul li { - line-height: 1.4em; -} - -#description dl, -#documentation dl { - margin: 8px 1.5em; - border: 1px solid #ccc; -} -#description dl { - font-size: 14px; -} - -#description dt, -#documentation dt { - padding: 2px 4px; - font-weight: bold; - background: #ddd; -} -#description dd, -#documentation dd { - padding: 2px 12px; -} -#description dd + dt, -#documentation dd + dt { - margin-top: 0.7em; -} - -#documentation .section { - font-size: 90%; -} -#documentation h3.section-header { - margin-top: 2em; - padding: 0.75em 0.5em; - background-color: #dedede; - color: #333; - font-size: 150%; - border: 1px solid #bbb; - -moz-border-radius: 3px; - -webkit-border-radius: 3px; -} - -#constants-list > dl, -#attributes-list > dl { - margin: 1em 0 2em; - border: 0; -} -#constants-list > dl dt, -#attributes-list > dl dt { - padding-left: 0; - font-weight: bold; - font-family: Monaco, "Andale Mono"; - background: inherit; -} -#constants-list > dl dt a, -#attributes-list > dl dt a { - color: inherit; -} -#constants-list > dl dd, -#attributes-list > dl dd { - margin: 0 0 1em 0; - padding: 0; - color: #666; -} - -/* @group Method Details */ - -#documentation .method-source-code { - display: none; -} - -#documentation .method-detail { - margin: 0.5em 0; - padding: 0.5em 0; - cursor: pointer; -} -#documentation .method-detail:hover { - background-color: #f1edba; -} -#documentation .method-heading { - position: relative; - padding: 2px 4px 0 20px; - font-size: 125%; - font-weight: bold; - color: #333; - background: url(images/brick.png) no-repeat left bottom; -} -#documentation .method-heading :link, -#documentation .method-heading :visited { - color: inherit; -} -#documentation .method-click-advice { - position: absolute; - top: 2px; - right: 5px; - font-size: 10px; - color: #9b9877; - visibility: hidden; - padding-right: 20px; - line-height: 20px; - background: url(images/zoom.png) no-repeat right top; -} -#documentation .method-detail:hover .method-click-advice { - visibility: visible; -} - -#documentation .method-alias .method-heading { - color: #666; - background: url(images/brick_link.png) no-repeat left bottom; -} - -#documentation .method-description, -#documentation .aliases { - margin: 0 20px; - line-height: 1.2em; - color: #666; -} -#documentation .aliases { - padding-top: 4px; - font-style: italic; - cursor: default; -} -#documentation .method-description p { - padding: 0; -} -#documentation .method-description p + p { - margin-bottom: 0.5em; -} -#documentation .method-description ul { - margin-left: 1.5em; -} - -#documentation .attribute-method-heading { - background: url(images/tag_green.png) no-repeat left bottom; -} -#documentation #attribute-method-details .method-detail:hover { - background-color: transparent; - cursor: default; -} -#documentation .attribute-access-type { - font-size: 60%; - text-transform: uppercase; - vertical-align: super; - padding: 0 2px; -} -/* @end */ - -/* @end */ - - - -/* @group Source Code */ - -div.method-source-code { - background: #262626; - color: #efefef; - margin: 1em; - padding: 0.5em; - border: 1px dashed #999; - overflow: hidden; -} - -div.method-source-code pre { - background: inherit; - padding: 0; - color: white; - overflow: auto; -} - -/* @group Ruby keyword styles */ - -.ruby-constant { color: #7fffd4; background: transparent; } -.ruby-keyword { color: #00ffff; background: transparent; } -.ruby-ivar { color: #eedd82; background: transparent; } -.ruby-operator { color: #00ffee; background: transparent; } -.ruby-identifier { color: #ffdead; background: transparent; } -.ruby-node { color: #ffa07a; background: transparent; } -.ruby-comment { color: #b22222; font-weight: bold; background: transparent; } -.ruby-regexp { color: #ffa07a; background: transparent; } -.ruby-value { color: #7fffd4; background: transparent; } - -/* @end */ -/* @end */ - - -/* @group File Popup Contents */ - -.file #metadata, -.file-popup #metadata { -} - -.file-popup dl { - font-size: 80%; - padding: 0.75em; - background-color: #dedede; - color: #333; - border: 1px solid #bbb; - -moz-border-radius: 3px; - -webkit-border-radius: 3px; -} -.file dt { - font-weight: bold; - padding-left: 22px; - line-height: 20px; - background: url(images/page_white_width.png) no-repeat left top; -} -.file dt.modified-date { - background: url(images/date.png) no-repeat left top; -} -.file dt.requires { - background: url(images/plugin.png) no-repeat left top; -} -.file dt.scs-url { - background: url(images/wrench.png) no-repeat left top; -} - -.file dl dd { - margin: 0 0 1em 0; -} -.file #metadata dl dd ul { - list-style: circle; - margin-left: 20px; - padding-top: 0; -} -.file #metadata dl dd ul li { -} - - -.file h2 { - margin-top: 2em; - padding: 0.75em 0.5em; - background-color: #dedede; - color: #333; - font-size: 120%; - border: 1px solid #bbb; - -moz-border-radius: 3px; - -webkit-border-radius: 3px; -} - -/* @end */ - - - - -/* @group ThickBox Styles */ -#TB_window { - font: 12px Arial, Helvetica, sans-serif; - color: #333333; -} - -#TB_secondLine { - font: 10px Arial, Helvetica, sans-serif; - color:#666666; -} - -#TB_window :link, -#TB_window :visited { color: #666666; } -#TB_window :link:hover, -#TB_window :visited:hover { color: #000; } -#TB_window :link:active, -#TB_window :visited:active { color: #666666; } -#TB_window :link:focus, -#TB_window :visited:focus { color: #666666; } - -#TB_overlay { - position: fixed; - z-index:100; - top: 0px; - left: 0px; - height:100%; - width:100%; -} - -.TB_overlayMacFFBGHack {background: url(images/macFFBgHack.png) repeat;} -.TB_overlayBG { - background-color:#000; - filter:alpha(opacity=75); - -moz-opacity: 0.75; - opacity: 0.75; -} - -* html #TB_overlay { /* ie6 hack */ - position: absolute; - height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'); -} - -#TB_window { - position: fixed; - background: #ffffff; - z-index: 102; - color:#000000; - display:none; - border: 4px solid #525252; - text-align:left; - top:50%; - left:50%; -} - -* html #TB_window { /* ie6 hack */ -position: absolute; -margin-top: expression(0 - parseInt(this.offsetHeight / 2) + (TBWindowMargin = document.documentElement && document.documentElement.scrollTop || document.body.scrollTop) + 'px'); -} - -#TB_window img#TB_Image { - display:block; - margin: 15px 0 0 15px; - border-right: 1px solid #ccc; - border-bottom: 1px solid #ccc; - border-top: 1px solid #666; - border-left: 1px solid #666; -} - -#TB_caption{ - height:25px; - padding:7px 30px 10px 25px; - float:left; -} - -#TB_closeWindow{ - height:25px; - padding:11px 25px 10px 0; - float:right; -} - -#TB_closeAjaxWindow{ - padding:7px 10px 5px 0; - margin-bottom:1px; - text-align:right; - float:right; -} - -#TB_ajaxWindowTitle{ - float:left; - padding:7px 0 5px 10px; - margin-bottom:1px; - font-size: 22px; -} - -#TB_title{ - background-color: #6C8C22; - color: #dedede; - height:40px; -} -#TB_title :link, -#TB_title :visited { - color: white !important; - border-bottom: 1px dotted #dedede; -} - -#TB_ajaxContent{ - clear:both; - padding:2px 15px 15px 15px; - overflow:auto; - text-align:left; - line-height:1.4em; -} - -#TB_ajaxContent.TB_modal{ - padding:15px; -} - -#TB_ajaxContent p{ - padding:5px 0px 5px 0px; -} - -#TB_load{ - position: fixed; - display:none; - height:13px; - width:208px; - z-index:103; - top: 50%; - left: 50%; - margin: -6px 0 0 -104px; /* -height/2 0 0 -width/2 */ -} - -* html #TB_load { /* ie6 hack */ -position: absolute; -margin-top: expression(0 - parseInt(this.offsetHeight / 2) + (TBWindowMargin = document.documentElement && document.documentElement.scrollTop || document.body.scrollTop) + 'px'); -} - -#TB_HideSelect{ - z-index:99; - position:fixed; - top: 0; - left: 0; - background-color:#fff; - border:none; - filter:alpha(opacity=0); - -moz-opacity: 0; - opacity: 0; - height:100%; - width:100%; -} - -* html #TB_HideSelect { /* ie6 hack */ - position: absolute; - height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'); -} - -#TB_iframeContent{ - clear:both; - border:none; - margin-bottom:-1px; - margin-top:1px; - _margin-bottom:1px; -} - -/* @end */ - -/* @group Debugging Section */ - -#debugging-toggle { - text-align: center; -} -#debugging-toggle img { - cursor: pointer; -} - -#rdoc-debugging-section-dump { - display: none; - margin: 0 2em 2em; - background: #ccc; - border: 1px solid #999; -} - - - -/* @end */ diff --git a/Src/StdLib/ruby/1.9.1/rdoc/ghost_method.rb b/Src/StdLib/ruby/1.9.1/rdoc/ghost_method.rb deleted file mode 100644 index 2d9891321..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/ghost_method.rb +++ /dev/null @@ -1,8 +0,0 @@ -require 'rdoc/any_method' - -## -# GhostMethod represents a method referenced only by a comment - -class RDoc::GhostMethod < RDoc::AnyMethod -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/include.rb b/Src/StdLib/ruby/1.9.1/rdoc/include.rb deleted file mode 100644 index a27f5da8f..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/include.rb +++ /dev/null @@ -1,61 +0,0 @@ -require 'rdoc/code_object' - -## -# A Module include in a class with \#include - -class RDoc::Include < RDoc::CodeObject - - ## - # Name of included module - - attr_accessor :name - - ## - # Creates a new Include for +name+ with +comment+ - - def initialize(name, comment) - super() - @name = name - self.comment = comment - end - - ## - # Includes are sorted by name - - def <=> other - return unless self.class === other - - name <=> other.name - end - - def == other # :nodoc: - self.class == other.class and - self.name == other.name - end - - ## - # Full name based on #module - - def full_name - m = self.module - RDoc::ClassModule === m ? m.full_name : @name - end - - def inspect # :nodoc: - "#<%s:0x%x %s.include %s>" % [ - self.class, - object_id, - parent_name, @name, - ] - end - - ## - # Attempts to locate the included module object. Returns the name if not - # known. - - def module - RDoc::TopLevel.find_module_named(@name) || @name - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/known_classes.rb b/Src/StdLib/ruby/1.9.1/rdoc/known_classes.rb deleted file mode 100644 index a7e397c5f..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/known_classes.rb +++ /dev/null @@ -1,69 +0,0 @@ -module RDoc - - ## - # Ruby's built-in classes, modules and exceptions - - KNOWN_CLASSES = { - "rb_cArray" => "Array", - "rb_cBasicObject" => "BasicObject", - "rb_cBignum" => "Bignum", - "rb_cClass" => "Class", - "rb_cData" => "Data", - "rb_cDir" => "Dir", - "rb_cFalseClass" => "FalseClass", - "rb_cFile" => "File", - "rb_cFixnum" => "Fixnum", - "rb_cFloat" => "Float", - "rb_cHash" => "Hash", - "rb_cIO" => "IO", - "rb_cInteger" => "Integer", - "rb_cModule" => "Module", - "rb_cNilClass" => "NilClass", - "rb_cNumeric" => "Numeric", - "rb_cObject" => "Object", - "rb_cProc" => "Proc", - "rb_cRange" => "Range", - "rb_cRegexp" => "Regexp", - "rb_cRubyVM" => "RubyVM", - "rb_cString" => "String", - "rb_cStruct" => "Struct", - "rb_cSymbol" => "Symbol", - "rb_cThread" => "Thread", - "rb_cTime" => "Time", - "rb_cTrueClass" => "TrueClass", - - "rb_eArgError" => "ArgError", - "rb_eEOFError" => "EOFError", - "rb_eException" => "Exception", - "rb_eFatal" => "Fatal", - "rb_eFloatDomainError" => "FloatDomainError", - "rb_eIOError" => "IOError", - "rb_eIndexError" => "IndexError", - "rb_eInterrupt" => "Interrupt", - "rb_eLoadError" => "LoadError", - "rb_eNameError" => "NameError", - "rb_eNoMemError" => "NoMemError", - "rb_eNotImpError" => "NotImpError", - "rb_eRangeError" => "RangeError", - "rb_eRuntimeError" => "RuntimeError", - "rb_eScriptError" => "ScriptError", - "rb_eSecurityError" => "SecurityError", - "rb_eSignal" => "Signal", - "rb_eStandardError" => "StandardError", - "rb_eSyntaxError" => "SyntaxError", - "rb_eSystemCallError" => "SystemCallError", - "rb_eSystemExit" => "SystemExit", - "rb_eTypeError" => "TypeError", - "rb_eZeroDivError" => "ZeroDivError", - - "rb_mComparable" => "Comparable", - "rb_mEnumerable" => "Enumerable", - "rb_mErrno" => "Errno", - "rb_mFileTest" => "FileTest", - "rb_mGC" => "GC", - "rb_mKernel" => "Kernel", - "rb_mMath" => "Math", - "rb_mProcess" => "Process" - } - -end diff --git a/Src/StdLib/ruby/1.9.1/rdoc/markup.rb b/Src/StdLib/ruby/1.9.1/rdoc/markup.rb deleted file mode 100644 index 65fbceace..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/markup.rb +++ /dev/null @@ -1,124 +0,0 @@ -require 'rdoc' - -## -# RDoc::Markup parses plain text documents and attempts to decompose them into -# their constituent parts. Some of these parts are high-level: paragraphs, -# chunks of verbatim text, list entries and the like. Other parts happen at -# the character level: a piece of bold text, a word in code font. This markup -# is similar in spirit to that used on WikiWiki webs, where folks create web -# pages using a simple set of formatting rules. -# -# RDoc::Markup itself does no output formatting: this is left to a different -# set of classes. -# -# RDoc::Markup is extendable at runtime: you can add \new markup elements to -# be recognised in the documents that RDoc::Markup parses. -# -# RDoc::Markup is intended to be the basis for a family of tools which share -# the common requirement that simple, plain-text should be rendered in a -# variety of different output formats and media. It is envisaged that -# RDoc::Markup could be the basis for formatting RDoc style comment blocks, -# Wiki entries, and online FAQs. -# -# == Synopsis -# -# This code converts +input_string+ to HTML. The conversion takes place in -# the +convert+ method, so you can use the same RDoc::Markup converter to -# convert multiple input strings. -# -# require 'rdoc/markup/to_html' -# -# h = RDoc::Markup::ToHtml.new -# -# puts h.convert(input_string) -# -# You can extend the RDoc::Markup parser to recognise new markup -# sequences, and to add special processing for text that matches a -# regular expression. Here we make WikiWords significant to the parser, -# and also make the sequences {word} and \text... signify -# strike-through text. When then subclass the HTML output class to deal -# with these: -# -# require 'rdoc/markup' -# require 'rdoc/markup/to_html' -# -# class WikiHtml < RDoc::Markup::ToHtml -# def handle_special_WIKIWORD(special) -# "" + special.text + "" -# end -# end -# -# m = RDoc::Markup.new -# m.add_word_pair("{", "}", :STRIKE) -# m.add_html("no", :STRIKE) -# -# m.add_special(/\b([A-Z][a-z]+[A-Z]\w+)/, :WIKIWORD) -# -# wh = WikiHtml.new -# wh.add_tag(:STRIKE, "", "") -# -# puts "#{wh.convert ARGF.read}" -# -#-- -# Author:: Dave Thomas, dave@pragmaticprogrammer.com -# License:: Ruby license - -class RDoc::Markup - - attr_reader :attribute_manager - - ## - # Take a block of text and use various heuristics to determine it's - # structure (paragraphs, lists, and so on). Invoke an event handler as we - # identify significant chunks. - - def initialize - @attribute_manager = RDoc::Markup::AttributeManager.new - @output = nil - end - - ## - # Add to the sequences used to add formatting to an individual word (such - # as *bold*). Matching entries will generate attributes that the output - # formatters can recognize by their +name+. - - def add_word_pair(start, stop, name) - @attribute_manager.add_word_pair(start, stop, name) - end - - ## - # Add to the sequences recognized as general markup. - - def add_html(tag, name) - @attribute_manager.add_html(tag, name) - end - - ## - # Add to other inline sequences. For example, we could add WikiWords using - # something like: - # - # parser.add_special(/\b([A-Z][a-z]+[A-Z]\w+)/, :WIKIWORD) - # - # Each wiki word will be presented to the output formatter via the - # accept_special method. - - def add_special(pattern, name) - @attribute_manager.add_special(pattern, name) - end - - ## - # We take +text+, parse it then invoke the output +formatter+ using a - # Visitor to render the result. - - def convert text, formatter - document = RDoc::Markup::Parser.parse text - - document.accept formatter - end - -end - -require 'rdoc/markup/parser' -require 'rdoc/markup/attribute_manager' -require 'rdoc/markup/inline' - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/markup/attribute_manager.rb b/Src/StdLib/ruby/1.9.1/rdoc/markup/attribute_manager.rb deleted file mode 100644 index 03e94b0d8..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/markup/attribute_manager.rb +++ /dev/null @@ -1,318 +0,0 @@ -## -# Manages changes of attributes in a block of text - -class RDoc::Markup::AttributeManager - - ## - # The NUL character - - NULL = "\000".freeze - - #-- - # We work by substituting non-printing characters in to the text. For now - # I'm assuming that I can substitute a character in the range 0..8 for a 7 - # bit character without damaging the encoded string, but this might be - # optimistic - #++ - - A_PROTECT = 004 # :nodoc: - - PROTECT_ATTR = A_PROTECT.chr # :nodoc: - - ## - # This maps delimiters that occur around words (such as *bold* or +tt+) - # where the start and end delimiters and the same. This lets us optimize - # the regexp - - attr_reader :matching_word_pairs - - ## - # And this is used when the delimiters aren't the same. In this case the - # hash maps a pattern to the attribute character - - attr_reader :word_pair_map - - ## - # This maps HTML tags to the corresponding attribute char - - attr_reader :html_tags - - ## - # A \ in front of a character that would normally be processed turns off - # processing. We do this by turning \< into <#{PROTECT} - - attr_reader :protectable - - ## - # And this maps _special_ sequences to a name. A special sequence is - # something like a WikiWord - - attr_reader :special - - ## - # Creates a new attribute manager that understands bold, emphasized and - # teletype text. - - def initialize - @html_tags = {} - @matching_word_pairs = {} - @protectable = %w[<\\] - @special = {} - @word_pair_map = {} - - add_word_pair "*", "*", :BOLD - add_word_pair "_", "_", :EM - add_word_pair "+", "+", :TT - - add_html "em", :EM - add_html "i", :EM - add_html "b", :BOLD - add_html "tt", :TT - add_html "code", :TT - end - - - ## - # Return an attribute object with the given turn_on and turn_off bits set - - def attribute(turn_on, turn_off) - RDoc::Markup::AttrChanger.new turn_on, turn_off - end - - def change_attribute(current, new) - diff = current ^ new - attribute(new & diff, current & diff) - end - - def changed_attribute_by_name(current_set, new_set) - current = new = 0 - current_set.each do |name| - current |= RDoc::Markup::Attribute.bitmap_for(name) - end - - new_set.each do |name| - new |= RDoc::Markup::Attribute.bitmap_for(name) - end - - change_attribute(current, new) - end - - def copy_string(start_pos, end_pos) - res = @str[start_pos...end_pos] - res.gsub!(/\000/, '') - res - end - - ## - # Map attributes like textto the sequence - # \001\002\001\003, where is a per-attribute specific - # character - - def convert_attrs(str, attrs) - # first do matching ones - tags = @matching_word_pairs.keys.join("") - - re = /(^|\W)([#{tags}])([#:\\]?[\w.\/-]+?\S?)\2(\W|$)/ - - 1 while str.gsub!(re) do - attr = @matching_word_pairs[$2] - attrs.set_attrs($`.length + $1.length + $2.length, $3.length, attr) - $1 + NULL * $2.length + $3 + NULL * $2.length + $4 - end - - # then non-matching - unless @word_pair_map.empty? then - @word_pair_map.each do |regexp, attr| - str.gsub!(regexp) { - attrs.set_attrs($`.length + $1.length, $2.length, attr) - NULL * $1.length + $2 + NULL * $3.length - } - end - end - end - - ## - # Converts HTML tags to RDoc attributes - - def convert_html(str, attrs) - tags = @html_tags.keys.join '|' - - 1 while str.gsub!(/<(#{tags})>(.*?)<\/\1>/i) { - attr = @html_tags[$1.downcase] - html_length = $1.length + 2 - seq = NULL * html_length - attrs.set_attrs($`.length + html_length, $2.length, attr) - seq + $2 + seq + NULL - } - end - - ## - # Converts special sequences to RDoc attributes - - def convert_specials(str, attrs) - unless @special.empty? - @special.each do |regexp, attr| - str.scan(regexp) do - attrs.set_attrs($`.length, $&.length, - attr | RDoc::Markup::Attribute::SPECIAL) - end - end - end - end - - ## - # Escapes special sequences of text to prevent conversion to RDoc - - def mask_protected_sequences - @str.gsub!(/\\([#{Regexp.escape @protectable.join('')}])/, - "\\1#{PROTECT_ATTR}") - end - - ## - # Unescapes special sequences of text - - def unmask_protected_sequences - @str.gsub!(/(.)#{PROTECT_ATTR}/, "\\1\000") - end - - ## - # Adds a markup class with +name+ for words wrapped in the +start+ and - # +stop+ character. To make words wrapped with "*" bold: - # - # am.add_word_pair '*', '*', :BOLD - - def add_word_pair(start, stop, name) - raise ArgumentError, "Word flags may not start with '<'" if - start[0,1] == '<' - - bitmap = RDoc::Markup::Attribute.bitmap_for name - - if start == stop then - @matching_word_pairs[start] = bitmap - else - pattern = /(#{Regexp.escape start})(\S+)(#{Regexp.escape stop})/ - @word_pair_map[pattern] = bitmap - end - - @protectable << start[0,1] - @protectable.uniq! - end - - ## - # Adds a markup class with +name+ for words surrounded by HTML tag +tag+. - # To process emphasis tags: - # - # am.add_html 'em', :EM - - def add_html(tag, name) - @html_tags[tag.downcase] = RDoc::Markup::Attribute.bitmap_for name - end - - ## - # Adds a special handler for +pattern+ with +name+. A simple URL handler - # would be: - # - # @am.add_special(/((https?:)\S+\w)/, :HYPERLINK) - - def add_special(pattern, name) - @special[pattern] = RDoc::Markup::Attribute.bitmap_for name - end - - ## - # Processes +str+ converting attributes, HTML and specials - - def flow(str) - @str = str - - mask_protected_sequences - - @attrs = RDoc::Markup::AttrSpan.new @str.length - - convert_attrs @str, @attrs - convert_html @str, @attrs - convert_specials @str, @attrs - - unmask_protected_sequences - - split_into_flow - end - - ## - # Debug method that prints a string along with its attributes - - def display_attributes - puts - puts @str.tr(NULL, "!") - bit = 1 - 16.times do |bno| - line = "" - @str.length.times do |i| - if (@attrs[i] & bit) == 0 - line << " " - else - if bno.zero? - line << "S" - else - line << ("%d" % (bno+1)) - end - end - end - puts(line) unless line =~ /^ *$/ - bit <<= 1 - end - end - - def split_into_flow - res = [] - current_attr = 0 - str = "" - - str_len = @str.length - - # skip leading invisible text - i = 0 - i += 1 while i < str_len and @str[i].chr == "\0" - start_pos = i - - # then scan the string, chunking it on attribute changes - while i < str_len - new_attr = @attrs[i] - if new_attr != current_attr - if i > start_pos - res << copy_string(start_pos, i) - start_pos = i - end - - res << change_attribute(current_attr, new_attr) - current_attr = new_attr - - if (current_attr & RDoc::Markup::Attribute::SPECIAL) != 0 then - i += 1 while - i < str_len and (@attrs[i] & RDoc::Markup::Attribute::SPECIAL) != 0 - - res << RDoc::Markup::Special.new(current_attr, - copy_string(start_pos, i)) - start_pos = i - next - end - end - - # move on, skipping any invisible characters - begin - i += 1 - end while i < str_len and @str[i].chr == "\0" - end - - # tidy up trailing text - if start_pos < str_len - res << copy_string(start_pos, str_len) - end - - # and reset to all attributes off - res << change_attribute(current_attr, 0) if current_attr != 0 - - res - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/markup/blank_line.rb b/Src/StdLib/ruby/1.9.1/rdoc/markup/blank_line.rb deleted file mode 100644 index 3cf97a0a0..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/markup/blank_line.rb +++ /dev/null @@ -1,19 +0,0 @@ -## -# An empty line - -class RDoc::Markup::BlankLine - - def == other # :nodoc: - self.class == other.class - end - - def accept visitor - visitor.accept_blank_line self - end - - def pretty_print q # :nodoc: - q.text 'blankline' - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/markup/document.rb b/Src/StdLib/ruby/1.9.1/rdoc/markup/document.rb deleted file mode 100644 index a7c746a0e..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/markup/document.rb +++ /dev/null @@ -1,72 +0,0 @@ -## -# A Document containing lists, headings, paragraphs, etc. - -class RDoc::Markup::Document - - ## - # The parts of the Document - - attr_reader :parts - - ## - # Creates a new Document with +parts+ - - def initialize *parts - @parts = [] - @parts.push(*parts) - end - - ## - # Appends +part+ to the document - - def << part - case part - when RDoc::Markup::Document then - unless part.empty? then - parts.push(*part.parts) - parts << RDoc::Markup::BlankLine.new - end - when String then - raise ArgumentError, - "expected RDoc::Markup::Document and friends, got String" unless - part.empty? - else - parts << part - end - end - - def == other # :nodoc: - self.class == other.class and @parts == other.parts - end - - def accept visitor - visitor.start_accepting - - @parts.each do |item| - item.accept visitor - end - - visitor.end_accepting - end - - def empty? - @parts.empty? - end - - def pretty_print q # :nodoc: - q.group 2, '[doc: ', ']' do - q.seplist @parts do |part| - q.pp part - end - end - end - - ## - # Appends +parts+ to the document - - def push *parts - self.parts.push(*parts) - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/markup/formatter.rb b/Src/StdLib/ruby/1.9.1/rdoc/markup/formatter.rb deleted file mode 100644 index 7a06ecbd6..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/markup/formatter.rb +++ /dev/null @@ -1,143 +0,0 @@ -require 'rdoc/markup' - -## -# Base class for RDoc markup formatters -# -# Formatters use a visitor pattern to convert content into output. - -class RDoc::Markup::Formatter - - InlineTag = Struct.new(:bit, :on, :off) - - ## - # Creates a new Formatter - - def initialize - @markup = RDoc::Markup.new - @am = @markup.attribute_manager - @attr_tags = [] - - @in_tt = 0 - @tt_bit = RDoc::Markup::Attribute.bitmap_for :TT - end - - ## - # Add a new set of tags for an attribute. We allow separate start and end - # tags for flexibility - - def add_tag(name, start, stop) - attr = RDoc::Markup::Attribute.bitmap_for name - @attr_tags << InlineTag.new(attr, start, stop) - end - - ## - # Allows +tag+ to be decorated with additional information. - - def annotate(tag) - tag - end - - ## - # Marks up +content+ - - def convert(content) - @markup.convert content, self - end - - ## - # Converts flow items +flow+ - - def convert_flow(flow) - res = [] - - flow.each do |item| - case item - when String then - res << convert_string(item) - when RDoc::Markup::AttrChanger then - off_tags res, item - on_tags res, item - when RDoc::Markup::Special then - res << convert_special(item) - else - raise "Unknown flow element: #{item.inspect}" - end - end - - res.join - end - - ## - # Converts added specials. See RDoc::Markup#add_special - - def convert_special(special) - handled = false - - RDoc::Markup::Attribute.each_name_of special.type do |name| - method_name = "handle_special_#{name}" - - if respond_to? method_name then - special.text = send method_name, special - handled = true - end - end - - raise "Unhandled special: #{special}" unless handled - - special.text - end - - ## - # Converts a string to be fancier if desired - - def convert_string string - string - end - - ## - # Are we currently inside tt tags? - - def in_tt? - @in_tt > 0 - end - - def on_tags res, item - attr_mask = item.turn_on - return if attr_mask.zero? - - @attr_tags.each do |tag| - if attr_mask & tag.bit != 0 then - res << annotate(tag.on) - @in_tt += 1 if tt? tag - end - end - end - - def off_tags res, item - attr_mask = item.turn_off - return if attr_mask.zero? - - @attr_tags.reverse_each do |tag| - if attr_mask & tag.bit != 0 then - @in_tt -= 1 if tt? tag - res << annotate(tag.off) - end - end - end - - ## - # Is +tag+ a tt tag? - - def tt? tag - tag.bit == @tt_bit - end - -end - -class RDoc::Markup - autoload :ToAnsi, 'rdoc/markup/to_ansi' - autoload :ToBs, 'rdoc/markup/to_bs' - autoload :ToHtml, 'rdoc/markup/to_html' - autoload :ToHtmlCrossref, 'rdoc/markup/to_html_crossref' - autoload :ToRdoc, 'rdoc/markup/to_rdoc' -end diff --git a/Src/StdLib/ruby/1.9.1/rdoc/markup/formatter_test_case.rb b/Src/StdLib/ruby/1.9.1/rdoc/markup/formatter_test_case.rb deleted file mode 100644 index e38f24e36..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/markup/formatter_test_case.rb +++ /dev/null @@ -1,353 +0,0 @@ -require 'minitest/unit' -require 'rdoc/markup/formatter' - -## -# Test case for creating new RDoc::Markup formatters. See -# test/test_rdoc_markup_to_*.rb for examples. - -class RDoc::Markup::FormatterTestCase < MiniTest::Unit::TestCase - - def setup - super - - @m = RDoc::Markup.new - @am = RDoc::Markup::AttributeManager.new - @RM = RDoc::Markup - - @bullet_list = @RM::List.new(:BULLET, - @RM::ListItem.new(nil, @RM::Paragraph.new('l1')), - @RM::ListItem.new(nil, @RM::Paragraph.new('l2'))) - - @label_list = @RM::List.new(:LABEL, - @RM::ListItem.new('cat', @RM::Paragraph.new('cats are cool')), - @RM::ListItem.new('dog', @RM::Paragraph.new('dogs are cool too'))) - - @lalpha_list = @RM::List.new(:LALPHA, - @RM::ListItem.new(nil, @RM::Paragraph.new('l1')), - @RM::ListItem.new(nil, @RM::Paragraph.new('l2'))) - - @note_list = @RM::List.new(:NOTE, - @RM::ListItem.new('cat', @RM::Paragraph.new('cats are cool')), - @RM::ListItem.new('dog', @RM::Paragraph.new('dogs are cool too'))) - - @number_list = @RM::List.new(:NUMBER, - @RM::ListItem.new(nil, @RM::Paragraph.new('l1')), - @RM::ListItem.new(nil, @RM::Paragraph.new('l2'))) - - @ualpha_list = @RM::List.new(:UALPHA, - @RM::ListItem.new(nil, @RM::Paragraph.new('l1')), - @RM::ListItem.new(nil, @RM::Paragraph.new('l2'))) - end - - def self.add_visitor_tests - self.class_eval do - def test_start_accepting - @to.start_accepting - - start_accepting - end - - def test_end_accepting - @to.start_accepting - @to.res << 'hi' - - end_accepting - end - - def test_accept_blank_line - @to.start_accepting - - @to.accept_blank_line @RM::BlankLine.new - - accept_blank_line - end - - def test_accept_heading - @to.start_accepting - - @to.accept_heading @RM::Heading.new(5, 'Hello') - - accept_heading - end - - def test_accept_paragraph - @to.start_accepting - - @to.accept_paragraph @RM::Paragraph.new('hi') - - accept_paragraph - end - - def test_accept_verbatim - @to.start_accepting - - @to.accept_verbatim @RM::Verbatim.new(' ', 'hi', "\n", - ' ', 'world', "\n") - - accept_verbatim - end - - def test_accept_raw - @to.start_accepting - - @to.accept_raw @RM::Raw.new("", - "
NameCount", - "
a1", - "
b2", - "
") - - accept_raw - end - - def test_accept_rule - @to.start_accepting - - @to.accept_rule @RM::Rule.new(4) - - accept_rule - end - - def test_accept_list_item_start_bullet - @to.start_accepting - - @to.accept_list_start @bullet_list - - @to.accept_list_item_start @bullet_list.items.first - - accept_list_item_start_bullet - end - - def test_accept_list_item_start_label - @to.start_accepting - - @to.accept_list_start @label_list - - @to.accept_list_item_start @label_list.items.first - - accept_list_item_start_label - end - - def test_accept_list_item_start_lalpha - @to.start_accepting - - @to.accept_list_start @lalpha_list - - @to.accept_list_item_start @lalpha_list.items.first - - accept_list_item_start_lalpha - end - - def test_accept_list_item_start_note - @to.start_accepting - - @to.accept_list_start @note_list - - @to.accept_list_item_start @note_list.items.first - - accept_list_item_start_note - end - - def test_accept_list_item_start_number - @to.start_accepting - - @to.accept_list_start @number_list - - @to.accept_list_item_start @number_list.items.first - - accept_list_item_start_number - end - - def test_accept_list_item_start_ualpha - @to.start_accepting - - @to.accept_list_start @ualpha_list - - @to.accept_list_item_start @ualpha_list.items.first - - accept_list_item_start_ualpha - end - - def test_accept_list_item_end_bullet - @to.start_accepting - - @to.accept_list_start @bullet_list - - @to.accept_list_item_start @bullet_list.items.first - - @to.accept_list_item_end @bullet_list.items.first - - accept_list_item_end_bullet - end - - def test_accept_list_item_end_label - @to.start_accepting - - @to.accept_list_start @label_list - - @to.accept_list_item_start @label_list.items.first - - @to.accept_list_item_end @label_list.items.first - - accept_list_item_end_label - end - - def test_accept_list_item_end_lalpha - @to.start_accepting - - @to.accept_list_start @lalpha_list - - @to.accept_list_item_start @lalpha_list.items.first - - @to.accept_list_item_end @lalpha_list.items.first - - accept_list_item_end_lalpha - end - - def test_accept_list_item_end_note - @to.start_accepting - - @to.accept_list_start @note_list - - @to.accept_list_item_start @note_list.items.first - - @to.accept_list_item_end @note_list.items.first - - accept_list_item_end_note - end - - def test_accept_list_item_end_number - @to.start_accepting - - @to.accept_list_start @number_list - - @to.accept_list_item_start @number_list.items.first - - @to.accept_list_item_end @number_list.items.first - - accept_list_item_end_number - end - - def test_accept_list_item_end_ualpha - @to.start_accepting - - @to.accept_list_start @ualpha_list - - @to.accept_list_item_start @ualpha_list.items.first - - @to.accept_list_item_end @ualpha_list.items.first - - accept_list_item_end_ualpha - end - - def test_accept_list_start_bullet - @to.start_accepting - - @to.accept_list_start @bullet_list - - accept_list_start_bullet - end - - def test_accept_list_start_label - @to.start_accepting - - @to.accept_list_start @label_list - - accept_list_start_label - end - - def test_accept_list_start_lalpha - @to.start_accepting - - @to.accept_list_start @lalpha_list - - accept_list_start_lalpha - end - - def test_accept_list_start_note - @to.start_accepting - - @to.accept_list_start @note_list - - accept_list_start_note - end - - def test_accept_list_start_number - @to.start_accepting - - @to.accept_list_start @number_list - - accept_list_start_number - end - - def test_accept_list_start_ualpha - @to.start_accepting - - @to.accept_list_start @ualpha_list - - accept_list_start_ualpha - end - - def test_accept_list_end_bullet - @to.start_accepting - - @to.accept_list_start @bullet_list - - @to.accept_list_end @bullet_list - - accept_list_end_bullet - end - - def test_accept_list_end_label - @to.start_accepting - - @to.accept_list_start @label_list - - @to.accept_list_end @label_list - - accept_list_end_label - end - - def test_accept_list_end_lalpha - @to.start_accepting - - @to.accept_list_start @lalpha_list - - @to.accept_list_end @lalpha_list - - accept_list_end_lalpha - end - - def test_accept_list_end_number - @to.start_accepting - - @to.accept_list_start @number_list - - @to.accept_list_end @number_list - - accept_list_end_number - end - - def test_accept_list_end_note - @to.start_accepting - - @to.accept_list_start @note_list - - @to.accept_list_end @note_list - - accept_list_end_note - end - - def test_accept_list_end_ualpha - @to.start_accepting - - @to.accept_list_start @ualpha_list - - @to.accept_list_end @ualpha_list - - accept_list_end_ualpha - end - end - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/markup/heading.rb b/Src/StdLib/ruby/1.9.1/rdoc/markup/heading.rb deleted file mode 100644 index 9df39b228..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/markup/heading.rb +++ /dev/null @@ -1,17 +0,0 @@ -## -# A heading with a level (1-6) and text - -class RDoc::Markup::Heading < Struct.new :level, :text - - def accept visitor - visitor.accept_heading self - end - - def pretty_print q # :nodoc: - q.group 2, "[head: #{level} ", ']' do - q.pp text - end - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/markup/inline.rb b/Src/StdLib/ruby/1.9.1/rdoc/markup/inline.rb deleted file mode 100644 index 5174ab0b5..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/markup/inline.rb +++ /dev/null @@ -1,127 +0,0 @@ -class RDoc::Markup - - ## - # We manage a set of attributes. Each attribute has a symbol name and a bit - # value. - - class Attribute - - ## - # Special attribute type. See RDoc::Markup#add_special - - SPECIAL = 1 - - @@name_to_bitmap = { :_SPECIAL_ => SPECIAL } - @@next_bitmap = 2 - - def self.bitmap_for(name) - bitmap = @@name_to_bitmap[name] - unless bitmap then - bitmap = @@next_bitmap - @@next_bitmap <<= 1 - @@name_to_bitmap[name] = bitmap - end - bitmap - end - - def self.as_string(bitmap) - return "none" if bitmap.zero? - res = [] - @@name_to_bitmap.each do |name, bit| - res << name if (bitmap & bit) != 0 - end - res.join(",") - end - - def self.each_name_of(bitmap) - @@name_to_bitmap.each do |name, bit| - next if bit == SPECIAL - yield name.to_s if (bitmap & bit) != 0 - end - end - - end - - AttrChanger = Struct.new :turn_on, :turn_off # :nodoc: - - ## - # An AttrChanger records a change in attributes. It contains a bitmap of the - # attributes to turn on, and a bitmap of those to turn off. - - class AttrChanger - def to_s # :nodoc: - "Attr: +#{Attribute.as_string turn_on}/-#{Attribute.as_string turn_on}" - end - end - - ## - # An array of attributes which parallels the characters in a string. - - class AttrSpan - - ## - # Creates a new AttrSpan for +length+ characters - - def initialize(length) - @attrs = Array.new(length, 0) - end - - ## - # Toggles +bits+ from +start+ to +length+ - def set_attrs(start, length, bits) - for i in start ... (start+length) - @attrs[i] |= bits - end - end - - ## - # Acccesses flags for character +n+ - - def [](n) - @attrs[n] - end - - end - - ## - # Hold details of a special sequence - - class Special - - ## - # Special type - - attr_reader :type - - ## - # Special text - - attr_accessor :text - - ## - # Creates a new special sequence of +type+ with +text+ - - def initialize(type, text) - @type, @text = type, text - end - - ## - # Specials are equal when the have the same text and type - - def ==(o) - self.text == o.text && self.type == o.type - end - - def inspect # :nodoc: - "#" % [ - object_id, @type, RDoc::Markup::Attribute.as_string(type), text.dump] - end - - def to_s # :nodoc: - "Special: type=#{type}, name=#{RDoc::Markup::Attribute.as_string type}, text=#{text.dump}" - end - - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/markup/list.rb b/Src/StdLib/ruby/1.9.1/rdoc/markup/list.rb deleted file mode 100644 index 74cb2f552..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/markup/list.rb +++ /dev/null @@ -1,78 +0,0 @@ -## -# A List of ListItems - -class RDoc::Markup::List - - ## - # The list's type - - attr_accessor :type - - ## - # Items in the list - - attr_reader :items - - ## - # Creates a new list of +type+ with +items+ - - def initialize type = nil, *items - @type = type - @items = [] - @items.push(*items) - end - - ## - # Appends +item+ to the list - - def << item - @items << item - end - - def == other # :nodoc: - self.class == other.class and - @type == other.type and - @items == other.items - end - - def accept visitor - visitor.accept_list_start self - - @items.each do |item| - item.accept visitor - end - - visitor.accept_list_end self - end - - ## - # Is the list empty? - - def empty? - @items.empty? - end - - ## - # Returns the last item in the list - - def last - @items.last - end - - def pretty_print q # :nodoc: - q.group 2, "[list: #{@type} ", ']' do - q.seplist @items do |item| - q.pp item - end - end - end - - ## - # Appends +items+ to the list - - def push *items - @items.push(*items) - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/markup/list_item.rb b/Src/StdLib/ruby/1.9.1/rdoc/markup/list_item.rb deleted file mode 100644 index cf58a39a4..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/markup/list_item.rb +++ /dev/null @@ -1,83 +0,0 @@ -## -# An item within a List that contains paragraphs, headings, etc. - -class RDoc::Markup::ListItem - - ## - # The label for the ListItem - - attr_accessor :label - - ## - # Parts of the ListItem - - attr_reader :parts - - ## - # Creates a new ListItem with an optional +label+ containing +parts+ - - def initialize label = nil, *parts - @label = label - @parts = [] - @parts.push(*parts) - end - - ## - # Appends +part+ to the ListItem - - def << part - @parts << part - end - - def == other # :nodoc: - self.class == other.class and - @label == other.label and - @parts == other.parts - end - - def accept visitor - visitor.accept_list_item_start self - - @parts.each do |part| - part.accept visitor - end - - visitor.accept_list_item_end self - end - - ## - # Is the ListItem empty? - - def empty? - @parts.empty? - end - - ## - # Length of parts in the ListItem - - def length - @parts.length - end - - def pretty_print q # :nodoc: - q.group 2, '[item: ', ']' do - if @label then - q.text @label - q.breakable - end - - q.seplist @parts do |part| - q.pp part - end - end - end - - ## - # Adds +parts+ to the ListItem - - def push *parts - @parts.push(*parts) - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/markup/paragraph.rb b/Src/StdLib/ruby/1.9.1/rdoc/markup/paragraph.rb deleted file mode 100644 index 02f4bf076..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/markup/paragraph.rb +++ /dev/null @@ -1,11 +0,0 @@ -## -# A Paragraph of text - -class RDoc::Markup::Paragraph < RDoc::Markup::Raw - - def accept visitor - visitor.accept_paragraph self - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/markup/parser.rb b/Src/StdLib/ruby/1.9.1/rdoc/markup/parser.rb deleted file mode 100644 index 921b2dad1..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/markup/parser.rb +++ /dev/null @@ -1,529 +0,0 @@ -require 'strscan' -require 'rdoc/text' - -## -# A recursive-descent parser for RDoc markup. -# -# The parser tokenizes an input string then parses the tokens into a Document. -# Documents can be converted into output formats by writing a visitor like -# RDoc::Markup::ToHTML. -# -# The parser only handles the block-level constructs Paragraph, List, -# ListItem, Heading, Verbatim, BlankLine and Rule. Inline markup such as -# \+blah\+ is handled separately by RDoc::Markup::AttributeManager. -# -# To see what markup the Parser implements read RDoc. To see how to use -# RDoc markup to format text in your program read RDoc::Markup. - -class RDoc::Markup::Parser - - include RDoc::Text - - ## - # List token types - - LIST_TOKENS = [ - :BULLET, - :LABEL, - :LALPHA, - :NOTE, - :NUMBER, - :UALPHA, - ] - - ## - # Parser error subclass - - class Error < RuntimeError; end - - ## - # Raised when the parser is unable to handle the given markup - - class ParseError < Error; end - - ## - # Enables display of debugging information - - attr_accessor :debug - - ## - # Token accessor - - attr_reader :tokens - - ## - # Parsers +str+ into a Document - - def self.parse str - parser = new - #parser.debug = true - parser.tokenize str - RDoc::Markup::Document.new(*parser.parse) - end - - ## - # Returns a token stream for +str+, for testing - - def self.tokenize str - parser = new - parser.tokenize str - parser.tokens - end - - ## - # Creates a new Parser. See also ::parse - - def initialize - @tokens = [] - @current_token = nil - @debug = false - - @line = 0 - @line_pos = 0 - end - - ## - # Builds a Heading of +level+ - - def build_heading level - heading = RDoc::Markup::Heading.new level, text - skip :NEWLINE - - heading - end - - ## - # Builds a List flush to +margin+ - - def build_list margin - p :list_start => margin if @debug - - list = RDoc::Markup::List.new - - until @tokens.empty? do - type, data, column, = get - - case type - when :BULLET, :LABEL, :LALPHA, :NOTE, :NUMBER, :UALPHA then - list_type = type - - if column < margin then - unget - break - end - - if list.type and list.type != list_type then - unget - break - end - - list.type = list_type - - case type - when :NOTE, :LABEL then - _, indent, = get # SPACE - if :NEWLINE == peek_token.first then - get - peek_type, new_indent, peek_column, = peek_token - indent = new_indent if - peek_type == :INDENT and peek_column >= column - unget - end - else - data = nil - _, indent, = get - end - - list_item = build_list_item(margin + indent, data) - - list << list_item if list_item - else - unget - break - end - end - - p :list_end => margin if @debug - - return nil if list.empty? - - list - end - - ## - # Builds a ListItem that is flush to +indent+ with type +item_type+ - - def build_list_item indent, item_type = nil - p :list_item_start => [indent, item_type] if @debug - - list_item = RDoc::Markup::ListItem.new item_type - - until @tokens.empty? do - type, data, column = get - - if column < indent and - not type == :NEWLINE and - (type != :INDENT or data < indent) then - unget - break - end - - case type - when :INDENT then - unget - list_item.push(*parse(indent)) - when :TEXT then - unget - list_item << build_paragraph(indent) - when :HEADER then - list_item << build_heading(data) - when :NEWLINE then - list_item << RDoc::Markup::BlankLine.new - when *LIST_TOKENS then - unget - list_item << build_list(column) - else - raise ParseError, "Unhandled token #{@current_token.inspect}" - end - end - - p :list_item_end => [indent, item_type] if @debug - - return nil if list_item.empty? - - list_item.parts.shift if - RDoc::Markup::BlankLine === list_item.parts.first and - list_item.length > 1 - - list_item - end - - ## - # Builds a Paragraph that is flush to +margin+ - - def build_paragraph margin - p :paragraph_start => margin if @debug - - paragraph = RDoc::Markup::Paragraph.new - - until @tokens.empty? do - type, data, column, = get - - case type - when :INDENT then - next if data == margin and peek_token[0] == :TEXT - - unget - break - when :TEXT then - if column != margin then - unget - break - end - - paragraph << data - skip :NEWLINE - else - unget - break - end - end - - p :paragraph_end => margin if @debug - - paragraph - end - - ## - # Builds a Verbatim that is flush to +margin+ - - def build_verbatim margin - p :verbatim_begin => margin if @debug - verbatim = RDoc::Markup::Verbatim.new - - until @tokens.empty? do - type, data, column, = get - - case type - when :INDENT then - if margin >= data then - unget - break - end - - indent = data - margin - - verbatim << ' ' * indent - when :HEADER then - verbatim << '=' * data - - _, _, peek_column, = peek_token - peek_column ||= column + data - verbatim << ' ' * (peek_column - column - data) - when :RULE then - width = 2 + data - verbatim << '-' * width - - _, _, peek_column, = peek_token - peek_column ||= column + data + 2 - verbatim << ' ' * (peek_column - column - width) - when :TEXT then - verbatim << data - when *LIST_TOKENS then - if column <= margin then - unget - break - end - - list_marker = case type - when :BULLET then '*' - when :LABEL then "[#{data}]" - when :LALPHA, :NUMBER, :UALPHA then "#{data}." - when :NOTE then "#{data}::" - end - - verbatim << list_marker - - _, data, = get - - verbatim << ' ' * (data - list_marker.length) - when :NEWLINE then - verbatim << data - break unless [:INDENT, :NEWLINE].include? peek_token[0] - else - unget - break - end - end - - verbatim.normalize - - p :verbatim_end => margin if @debug - - verbatim - end - - ## - # Pulls the next token from the stream. - - def get - @current_token = @tokens.shift - p :get => @current_token if @debug - @current_token - end - - ## - # Parses the tokens into a Document - - def parse indent = 0 - p :parse_start => indent if @debug - - document = [] - - until @tokens.empty? do - type, data, column, = get - - if type != :INDENT and column < indent then - unget - break - end - - case type - when :HEADER then - document << build_heading(data) - when :INDENT then - if indent > data then - unget - break - elsif indent == data then - next - end - - unget - document << build_verbatim(indent) - when :NEWLINE then - document << RDoc::Markup::BlankLine.new - skip :NEWLINE, false - when :RULE then - document << RDoc::Markup::Rule.new(data) - skip :NEWLINE - when :TEXT then - unget - document << build_paragraph(indent) - - # we're done with this paragraph (indent mismatch) - break if peek_token[0] == :TEXT - when *LIST_TOKENS then - unget - - list = build_list(indent) - - document << list if list - - # we're done with this list (indent mismatch) - break if LIST_TOKENS.include? peek_token.first and indent > 0 - else - type, data, column, line = @current_token - raise ParseError, - "Unhandled token #{type} (#{data.inspect}) at #{line}:#{column}" - end - end - - p :parse_end => indent if @debug - - document - end - - ## - # Returns the next token on the stream without modifying the stream - - def peek_token - token = @tokens.first || [] - p :peek => token if @debug - token - end - - ## - # Skips a token of +token_type+, optionally raising an error. - - def skip token_type, error = true - type, data, = get - - return unless type # end of stream - - return @current_token if token_type == type - - unget - - raise ParseError, "expected #{token_type} got #{@current_token.inspect}" if - error - end - - ## - # Consumes tokens until NEWLINE and turns them back into text - - def text - text = '' - - loop do - type, data, = get - - text << case type - when :BULLET then - _, space, = get # SPACE - "*#{' ' * (space - 1)}" - when :LABEL then - _, space, = get # SPACE - "[#{data}]#{' ' * (space - data.length - 2)}" - when :LALPHA, :NUMBER, :UALPHA then - _, space, = get # SPACE - "#{data}.#{' ' * (space - 2)}" - when :NOTE then - _, space = get # SPACE - "#{data}::#{' ' * (space - data.length - 2)}" - when :TEXT then - data - when :NEWLINE then - unget - break - when nil then - break - else - raise ParseError, "unhandled token #{@current_token.inspect}" - end - end - - text - end - - ## - # Calculates the column and line of the current token based on +offset+. - - def token_pos offset - [offset - @line_pos, @line] - end - - ## - # Turns text +input+ into a stream of tokens - - def tokenize input - s = StringScanner.new input - - @line = 0 - @line_pos = 0 - - until s.eos? do - pos = s.pos - - @tokens << case - when s.scan(/\r?\n/) then - token = [:NEWLINE, s.matched, *token_pos(pos)] - @line_pos = s.pos - @line += 1 - token - when s.scan(/ +/) then - [:INDENT, s.matched_size, *token_pos(pos)] - when s.scan(/(=+)\s*/) then - level = s[1].length - level = 6 if level > 6 - @tokens << [:HEADER, level, *token_pos(pos)] - - pos = s.pos - s.scan(/.*/) - [:TEXT, s.matched, *token_pos(pos)] - when s.scan(/^(-{3,}) *$/) then - [:RULE, s[1].length - 2, *token_pos(pos)] - when s.scan(/([*-])\s+/) then - @tokens << [:BULLET, :BULLET, *token_pos(pos)] - [:SPACE, s.matched_size, *token_pos(pos)] - when s.scan(/([a-z]|\d+)\.[ \t]+\S/i) then - list_label = s[1] - width = s.matched_size - 1 - - s.pos -= 1 # unget \S - - list_type = case list_label - when /[a-z]/ then :LALPHA - when /[A-Z]/ then :UALPHA - when /\d/ then :NUMBER - else - raise ParseError, "BUG token #{list_label}" - end - - @tokens << [list_type, list_label, *token_pos(pos)] - [:SPACE, width, *token_pos(pos)] - when s.scan(/\[(.*?)\]( +|$)/) then - @tokens << [:LABEL, s[1], *token_pos(pos)] - [:SPACE, s.matched_size, *token_pos(pos)] - when s.scan(/(.*?)::( +|$)/) then - @tokens << [:NOTE, s[1], *token_pos(pos)] - [:SPACE, s.matched_size, *token_pos(pos)] - else s.scan(/.*/) - [:TEXT, s.matched, *token_pos(pos)] - end - end - - self - end - - ## - # Returns the current token or +token+ to the token stream - - def unget token = @current_token - p :unget => token if @debug - raise Error, 'too many #ungets' if token == @tokens.first - @tokens.unshift token if token - end - -end - -require 'rdoc/markup/blank_line' -require 'rdoc/markup/document' -require 'rdoc/markup/heading' -require 'rdoc/markup/list' -require 'rdoc/markup/list_item' -require 'rdoc/markup/raw' -require 'rdoc/markup/paragraph' -require 'rdoc/markup/rule' -require 'rdoc/markup/verbatim' - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/markup/preprocess.rb b/Src/StdLib/ruby/1.9.1/rdoc/markup/preprocess.rb deleted file mode 100644 index d516513c8..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/markup/preprocess.rb +++ /dev/null @@ -1,130 +0,0 @@ -require 'rdoc/markup' - -## -# Handle common directives that can occur in a block of text: -# -# : include : filename -# -# RDoc plugin authors can register additional directives to be handled through -# RDoc::Markup::PreProcess::register - -class RDoc::Markup::PreProcess - - @registered = {} - - ## - # Registers +directive+ as one handled by RDoc. If a block is given the - # directive will be replaced by the result of the block, otherwise the - # directive will be removed from the processed text. - - def self.register directive, &block - @registered[directive] = block - end - - ## - # Registered directives - - def self.registered - @registered - end - - ## - # Creates a new pre-processor for +input_file_name+ that will look for - # included files in +include_path+ - - def initialize(input_file_name, include_path) - @input_file_name = input_file_name - @include_path = include_path - end - - ## - # Look for directives in a chunk of +text+. - # - # Options that we don't handle are yielded. If the block returns false the - # directive is restored to the text. If the block returns nil or no block - # was given the directive is handled according to the registered directives. - # If a String was returned the directive is replaced with the string. - # - # If no matching directive was registered the directive is restored to the - # text. - # - # If +code_object+ is given and the param is set as metadata on the - # +code_object+. See RDoc::CodeObject#metadata - - def handle text, code_object = nil - text.gsub!(/^([ \t]*#?[ \t]*):(\w+):([ \t]*)(.+)?\n/) do - next $& if $3.empty? and $4 and $4[0, 1] == ':' - - prefix = $1 - directive = $2.downcase - param = $4 - - case directive - when 'include' then - filename = param.split[0] - include_file filename, prefix - - else - result = yield directive, param if block_given? - - case result - when nil then - code_object.metadata[directive] = param if code_object - if RDoc::Markup::PreProcess.registered.include? directive then - handler = RDoc::Markup::PreProcess.registered[directive] - result = handler.call directive, param if handler - else - result = "#{prefix}:#{directive}: #{param}\n" - end - when false then - result = "#{prefix}:#{directive}: #{param}\n" - end - - result - end - end - - text - end - - ## - # Include a file, indenting it correctly. - - def include_file(name, indent) - if full_name = find_include_file(name) then - content = if defined?(Encoding) then - File.binread full_name - else - File.read full_name - end - # HACK determine content type and force encoding - content = content.sub(/\A# .*coding[=:].*$/, '').lstrip - - # strip leading '#'s, but only if all lines start with them - if content =~ /^[^#]/ then - content.gsub(/^/, indent) - else - content.gsub(/^#?/, indent) - end - else - warn "Couldn't find file to include '#{name}' from #{@input_file_name}" - '' - end - end - - ## - # Look for the given file in the directory containing the current file, - # and then in each of the directories specified in the RDOC_INCLUDE path - - def find_include_file(name) - to_search = [File.dirname(@input_file_name)].concat @include_path - to_search.each do |dir| - full_name = File.join(dir, name) - stat = File.stat(full_name) rescue next - return full_name if stat.readable? - end - nil - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/markup/raw.rb b/Src/StdLib/ruby/1.9.1/rdoc/markup/raw.rb deleted file mode 100644 index cd6696974..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/markup/raw.rb +++ /dev/null @@ -1,65 +0,0 @@ -## -# A section of text that is added to the output document as-is - -class RDoc::Markup::Raw - - ## - # The component parts of the list - - attr_reader :parts - - ## - # Creates a new Raw containing +parts+ - - def initialize *parts - @parts = [] - @parts.push(*parts) - end - - ## - # Appends +text+ - - def << text - @parts << text - end - - def == other # :nodoc: - self.class == other.class and text == other.text - end - - def accept visitor - visitor.accept_raw self - end - - ## - # Appends +other+'s parts - - def merge other - @parts.push(*other.parts) - end - - def pretty_print q # :nodoc: - self.class.name =~ /.*::(\w{4})/i - - q.group 2, "[#{$1.downcase}: ", ']' do - q.seplist @parts do |part| - q.pp part - end - end - end - - ## - # Appends +texts+ onto this Paragraph - - def push *texts - self.parts.push(*texts) - end - - ## - # The raw text - - def text - @parts.join ' ' - end - -end diff --git a/Src/StdLib/ruby/1.9.1/rdoc/markup/rule.rb b/Src/StdLib/ruby/1.9.1/rdoc/markup/rule.rb deleted file mode 100644 index a337b7d3c..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/markup/rule.rb +++ /dev/null @@ -1,17 +0,0 @@ -## -# A horizontal rule with a weight - -class RDoc::Markup::Rule < Struct.new :weight - - def accept visitor - visitor.accept_rule self - end - - def pretty_print q # :nodoc: - q.group 2, '[rule:', ']' do - q.pp weight - end - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/markup/to_ansi.rb b/Src/StdLib/ruby/1.9.1/rdoc/markup/to_ansi.rb deleted file mode 100644 index 11a21989b..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/markup/to_ansi.rb +++ /dev/null @@ -1,72 +0,0 @@ -require 'rdoc/markup/inline' - -## -# Outputs RDoc markup with vibrant ANSI color! - -class RDoc::Markup::ToAnsi < RDoc::Markup::ToRdoc - - def initialize - super - - @headings.clear - @headings[1] = ["\e[1;32m", "\e[m"] - @headings[2] = ["\e[4;32m", "\e[m"] - @headings[3] = ["\e[32m", "\e[m"] - end - - ## - # Maps attributes to ANSI sequences - - def init_tags - add_tag :BOLD, "\e[1m", "\e[m" - add_tag :TT, "\e[7m", "\e[m" - add_tag :EM, "\e[4m", "\e[m" - end - - def accept_list_item_end list_item - width = case @list_type.last - when :BULLET then - 2 - when :NOTE, :LABEL then - @res << "\n" - 2 - else - bullet = @list_index.last.to_s - @list_index[-1] = @list_index.last.succ - bullet.length + 2 - end - - @indent -= width - end - - def accept_list_item_start list_item - bullet = case @list_type.last - when :BULLET then - '*' - when :NOTE, :LABEL then - attributes(list_item.label) + ":\n" - else - @list_index.last.to_s + '.' - end - - case @list_type.last - when :NOTE, :LABEL then - @indent += 2 - @prefix = bullet + (' ' * @indent) - else - @prefix = (' ' * @indent) + bullet.ljust(bullet.length + 1) - - width = bullet.gsub(/\e\[[\d;]*m/, '').length + 1 - - @indent += width - end - end - - def start_accepting - super - - @res = ["\e[0m"] - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/markup/to_bs.rb b/Src/StdLib/ruby/1.9.1/rdoc/markup/to_bs.rb deleted file mode 100644 index af448ae05..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/markup/to_bs.rb +++ /dev/null @@ -1,74 +0,0 @@ -require 'rdoc/markup/inline' - -## -# Outputs RDoc markup with hot backspace action! You will probably need a -# pager to use this output format. -# -# This formatter won't work on 1.8.6 because it lacks String#chars. - -class RDoc::Markup::ToBs < RDoc::Markup::ToRdoc - - def initialize - super - - @in_b = false - @in_em = false - end - - ## - # Sets a flag that is picked up by #annotate to do the right thing in - # #convert_string - - def init_tags - add_tag :BOLD, '+b', '-b' - add_tag :EM, '+_', '-_' - end - - def accept_heading heading - use_prefix or @res << ' ' * @indent - @res << @headings[heading.level][0] - @in_b = true - @res << attributes(heading.text) - @in_b = false - @res << @headings[heading.level][1] - @res << "\n" - end - - ## - # Turns on or off special handling for +convert_string+ - - def annotate tag - case tag - when '+b' then @in_b = true - when '-b' then @in_b = false - when '+_' then @in_em = true - when '-_' then @in_em = false - end - - '' - end - - ## - # Calls convert_string on the result of convert_special - - def convert_special special - convert_string super - end - - ## - # Adds bold or underline mixed with backspaces - - def convert_string string - return string unless string.respond_to? :chars # your ruby is lame - return string unless @in_b or @in_em - chars = if @in_b then - string.chars.map do |char| "#{char}\b#{char}" end - elsif @in_em then - string.chars.map do |char| "_\b#{char}" end - end - - chars.join - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/markup/to_html.rb b/Src/StdLib/ruby/1.9.1/rdoc/markup/to_html.rb deleted file mode 100644 index 1337c5d27..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/markup/to_html.rb +++ /dev/null @@ -1,344 +0,0 @@ -require 'rdoc/markup/formatter' -require 'rdoc/markup/inline' - -require 'cgi' - -## -# Outputs RDoc markup as HTML - -class RDoc::Markup::ToHtml < RDoc::Markup::Formatter - - ## - # Maps RDoc::Markup::Parser::LIST_TOKENS types to HTML tags - - LIST_TYPE_TO_HTML = { - :BULLET => ['
    ', '
'], - :LABEL => ['
', '
'], - :LALPHA => ['
    ', '
'], - :NOTE => ['', '
'], - :NUMBER => ['
    ', '
'], - :UALPHA => ['
    ', '
'], - } - - attr_reader :res # :nodoc: - attr_reader :in_list_entry # :nodoc: - attr_reader :list # :nodoc: - - ## - # Converts a target url to one that is relative to a given path - - def self.gen_relative_url(path, target) - from = File.dirname path - to, to_file = File.split target - - from = from.split "/" - to = to.split "/" - - from.delete '.' - to.delete '.' - - while from.size > 0 and to.size > 0 and from[0] == to[0] do - from.shift - to.shift - end - - from.fill ".." - from.concat to - from << to_file - File.join(*from) - end - - def initialize - super - - @th = nil - @in_list_entry = nil - @list = nil - - # external hyperlinks - @markup.add_special(/((link:|https?:|mailto:|ftp:|www\.)\S+\w)/, :HYPERLINK) - - # and links of the form [] - @markup.add_special(/(((\{.*?\})|\b\S+?)\[\S+?\.\S+?\])/, :TIDYLINK) - - init_tags - end - - ## - # Maps attributes to HTML tags - - def init_tags - add_tag :BOLD, "", "" - add_tag :TT, "", "" - add_tag :EM, "", "" - end - - ## - # Generate a hyperlink for url, labeled with text. Handle the - # special cases for img: and link: described under handle_special_HYPERLINK - - def gen_url(url, text) - if url =~ /([A-Za-z]+):(.*)/ then - type = $1 - path = $2 - else - type = "http" - path = url - url = "http://#{url}" - end - - if type == "link" then - url = if path[0, 1] == '#' then # is this meaningful? - path - else - self.class.gen_relative_url @from_path, path - end - end - - if (type == "http" or type == "link") and - url =~ /\.(gif|png|jpg|jpeg|bmp)$/ then - "" - else - "#{text.sub(%r{^#{type}:/*}, '')}" - end - end - - ## - # And we're invoked with a potential external hyperlink mailto: - # just gets inserted. http: links are checked to see if they - # reference an image. If so, that image gets inserted using an - # tag. Otherwise a conventional is used. We also - # support a special type of hyperlink, link:, which is a reference - # to a local file whose path is relative to the --op directory. - - def handle_special_HYPERLINK(special) - url = special.text - gen_url url, url - end - - ## - # Here's a hypedlink where the label is different to the URL - # #{name}" - else - name - end - - @seen[name] = out - - out - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/markup/to_rdoc.rb b/Src/StdLib/ruby/1.9.1/rdoc/markup/to_rdoc.rb deleted file mode 100644 index 2a65c7677..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/markup/to_rdoc.rb +++ /dev/null @@ -1,247 +0,0 @@ -require 'rdoc/markup/inline' - -## -# Outputs RDoc markup as RDoc markup! (mostly) - -class RDoc::Markup::ToRdoc < RDoc::Markup::Formatter - - attr_accessor :indent - attr_reader :list_index - attr_reader :list_type - attr_reader :list_width - attr_reader :prefix - attr_reader :res - - def initialize - super - - @markup.add_special(/\\[^\s]/, :SUPPRESSED_CROSSREF) - - @width = 78 - @prefix = '' - - init_tags - - @headings = {} - @headings.default = [] - - @headings[1] = ['= ', ''] - @headings[2] = ['== ', ''] - @headings[3] = ['=== ', ''] - @headings[4] = ['==== ', ''] - @headings[5] = ['===== ', ''] - @headings[6] = ['====== ', ''] - end - - ## - # Maps attributes to ANSI sequences - - def init_tags - add_tag :BOLD, "", "" - add_tag :TT, "", "" - add_tag :EM, "", "" - end - - def accept_blank_line blank_line - @res << "\n" - end - - def accept_heading heading - use_prefix or @res << ' ' * @indent - @res << @headings[heading.level][0] - @res << attributes(heading.text) - @res << @headings[heading.level][1] - @res << "\n" - end - - def accept_list_end list - @list_index.pop - @list_type.pop - @list_width.pop - end - - def accept_list_item_end list_item - width = case @list_type.last - when :BULLET then - 2 - when :NOTE, :LABEL then - @res << "\n" - 2 - else - bullet = @list_index.last.to_s - @list_index[-1] = @list_index.last.succ - bullet.length + 2 - end - - @indent -= width - end - - def accept_list_item_start list_item - bullet = case @list_type.last - when :BULLET then - '*' - when :NOTE, :LABEL then - attributes(list_item.label) + ":\n" - else - @list_index.last.to_s + '.' - end - - case @list_type.last - when :NOTE, :LABEL then - @indent += 2 - @prefix = bullet + (' ' * @indent) - else - @prefix = (' ' * @indent) + bullet.ljust(bullet.length + 1) - - width = bullet.length + 1 - - @indent += width - end - end - - def accept_list_start list - case list.type - when :BULLET then - @list_index << nil - @list_width << 1 - when :LABEL, :NOTE then - @list_index << nil - @list_width << 2 - when :LALPHA then - @list_index << 'a' - @list_width << list.items.length.to_s.length - when :NUMBER then - @list_index << 1 - @list_width << list.items.length.to_s.length - when :UALPHA then - @list_index << 'A' - @list_width << list.items.length.to_s.length - else - raise RDoc::Error, "invalid list type #{list.type}" - end - - @list_type << list.type - end - - def accept_paragraph paragraph - wrap attributes(paragraph.text) - end - - def accept_raw raw - @res << raw.parts.join("\n") - end - - def accept_rule rule - use_prefix or @res << ' ' * @indent - @res << '-' * (@width - @indent) - @res << "\n" - end - - ## - # Outputs +verbatim+ flush left and indented 2 columns - - def accept_verbatim verbatim - indent = ' ' * (@indent + 2) - - lines = [] - current_line = [] - - # split into lines - verbatim.parts.each do |part| - current_line << part - - if part == "\n" then - lines << current_line - current_line = [] - end - end - - lines << current_line unless current_line.empty? - - # calculate margin - indented = lines.select { |line| line != ["\n"] } - margin = indented.map { |line| line.first.length }.min - - # flush left - indented.each { |line| line[0][0...margin] = '' } - - # output - use_prefix or @res << indent # verbatim is unlikely to have prefix - @res << lines.shift.join - - lines.each do |line| - @res << indent unless line == ["\n"] - @res << line.join - end - - @res << "\n" - end - - def attributes text - flow = @am.flow text.dup - convert_flow flow - end - - def end_accepting - @res.join - end - - def handle_special_SUPPRESSED_CROSSREF special - special.text.sub(/\\/, '') - end - - def start_accepting - @res = [""] - @indent = 0 - @prefix = nil - - @list_index = [] - @list_type = [] - @list_width = [] - end - - def use_prefix - prefix = @prefix - @prefix = nil - @res << prefix if prefix - - prefix - end - - def wrap text - return unless text && !text.empty? - - text_len = @width - @indent - - text_len = 20 if text_len < 20 - - re = /^(.{0,#{text_len}})[ \n]/ - next_prefix = ' ' * @indent - - prefix = @prefix || next_prefix - @prefix = nil - - @res << prefix - - while text.length > text_len - if text =~ re then - @res << $1 - text.slice!(0, $&.length) - else - @res << text.slice!(0, text_len) - end - - @res << "\n" << next_prefix - end - - if text.empty? then - @res.pop - @res.pop - else - @res << text - @res << "\n" - end - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/markup/to_test.rb b/Src/StdLib/ruby/1.9.1/rdoc/markup/to_test.rb deleted file mode 100644 index b406c5d20..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/markup/to_test.rb +++ /dev/null @@ -1,64 +0,0 @@ -require 'rdoc/markup' -require 'rdoc/markup/formatter' - -## -# This Markup outputter is used for testing purposes. - -class RDoc::Markup::ToTest < RDoc::Markup::Formatter - - ## - # :section: Visitor - - def start_accepting - @res = [] - @list = [] - end - - def end_accepting - @res - end - - def accept_paragraph(paragraph) - @res << paragraph.text - end - - def accept_verbatim(verbatim) - @res << verbatim.text - end - - def accept_list_start(list) - @list << case list.type - when :BULLET then - '*' - when :NUMBER then - '1' - else - list.type - end - end - - def accept_list_end(list) - @list.pop - end - - def accept_list_item_start(list_item) - @res << "#{' ' * (@list.size - 1)}#{@list.last}: " - end - - def accept_list_item_end(list_item) - end - - def accept_blank_line(blank_line) - @res << "\n" - end - - def accept_heading(heading) - @res << "#{'=' * heading.level} #{heading.text}" - end - - def accept_rule(rule) - @res << '-' * rule.weight - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/markup/verbatim.rb b/Src/StdLib/ruby/1.9.1/rdoc/markup/verbatim.rb deleted file mode 100644 index 1daff1a9a..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/markup/verbatim.rb +++ /dev/null @@ -1,42 +0,0 @@ -## -# A section of verbatim text - -class RDoc::Markup::Verbatim < RDoc::Markup::Raw - - def accept visitor - visitor.accept_verbatim self - end - - ## - # Collapses 3+ newlines into two newlines - - def normalize - parts = [] - - newlines = 0 - - @parts.each do |part| - case part - when /\n/ then - newlines += 1 - parts << part if newlines <= 2 - else - newlines = 0 - parts << part - end - end - - parts.slice!(-1) if parts[-2..-1] == ["\n", "\n"] - - @parts = parts - end - - ## - # The text of the section - - def text - @parts.join - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/meta_method.rb b/Src/StdLib/ruby/1.9.1/rdoc/meta_method.rb deleted file mode 100644 index 4cf61e5d1..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/meta_method.rb +++ /dev/null @@ -1,8 +0,0 @@ -require 'rdoc/any_method' - -## -# MetaMethod represents a meta-programmed method - -class RDoc::MetaMethod < RDoc::AnyMethod -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/normal_class.rb b/Src/StdLib/ruby/1.9.1/rdoc/normal_class.rb deleted file mode 100644 index 5bb27cfa9..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/normal_class.rb +++ /dev/null @@ -1,55 +0,0 @@ -require 'rdoc/class_module' - -## -# A normal class, neither singleton nor anonymous - -class RDoc::NormalClass < RDoc::ClassModule - - ## - # Ancestor ClassModules - - def ancestors - includes + [superclass] - end - - def inspect # :nodoc: - superclass = @superclass ? " < #{@superclass}" : nil - "<%s:0x%x class %s%s includes: %p attributes: %p methods: %p aliases: %p>" % [ - self.class, object_id, - full_name, superclass, @includes, @attributes, @method_list, @aliases - ] - end - - def pretty_print q # :nodoc: - superclass = @superclass ? " < #{@superclass}" : nil - - q.group 2, "[class #{full_name}#{superclass} ", "]" do - q.breakable - q.text "includes:" - q.breakable - q.seplist @includes do |inc| q.pp inc end - - q.breakable - q.text "attributes:" - q.breakable - q.seplist @attributes do |inc| q.pp inc end - - q.breakable - q.text "methods:" - q.breakable - q.seplist @method_list do |inc| q.pp inc end - - q.breakable - q.text "aliases:" - q.breakable - q.seplist @aliases do |inc| q.pp inc end - - q.breakable - q.text "comment:" - q.breakable - q.pp comment - end - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/normal_module.rb b/Src/StdLib/ruby/1.9.1/rdoc/normal_module.rb deleted file mode 100644 index a67c7c500..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/normal_module.rb +++ /dev/null @@ -1,64 +0,0 @@ -require 'rdoc/class_module' - -## -# A normal module, like NormalClass - -class RDoc::NormalModule < RDoc::ClassModule - - ## - # Included NormalModules - - alias ancestors includes - - def inspect # :nodoc: - "#<%s:0x%x module %s includes: %p attributes: %p methods: %p aliases: %p>" % [ - self.class, object_id, - full_name, @includes, @attributes, @method_list, @aliases - ] - end - - ## - # This is a module, returns true - - def module? - true - end - - def pretty_print q # :nodoc: - q.group 2, "[module #{full_name}: ", "]" do - q.breakable - q.text "includes:" - q.breakable - q.seplist @includes do |inc| q.pp inc end - q.breakable - - q.text "attributes:" - q.breakable - q.seplist @attributes do |inc| q.pp inc end - q.breakable - - q.text "methods:" - q.breakable - q.seplist @method_list do |inc| q.pp inc end - q.breakable - - q.text "aliases:" - q.breakable - q.seplist @aliases do |inc| q.pp inc end - q.breakable - - q.text "comment:" - q.breakable - q.pp comment - end - end - - ## - # Modules don't have one, raises NoMethodError - - def superclass - raise NoMethodError, "#{full_name} is a module" - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/options.rb b/Src/StdLib/ruby/1.9.1/rdoc/options.rb deleted file mode 100644 index cb2d7fe5b..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/options.rb +++ /dev/null @@ -1,441 +0,0 @@ -require 'optparse' - -require 'rdoc/ri/paths' - -## -# RDoc::Options handles the parsing and storage of options - -class RDoc::Options - - ## - # Character-set - - attr_reader :charset - - ## - # Files matching this pattern will be excluded - - attr_accessor :exclude - - ## - # The list of files to be processed - - attr_accessor :files - - ## - # Scan newer sources than the flag file if true. - - attr_reader :force_update - - ## - # Description of the output generator (set with the -fmt option) - - attr_accessor :generator - - ## - # Formatter to mark up text with - - attr_accessor :formatter - - ## - # Name of the file, class or module to display in the initial index page (if - # not specified the first file we encounter is used) - - attr_accessor :main_page - - ## - # The name of the output directory - - attr_accessor :op_dir - - ## - # Is RDoc in pipe mode? - - attr_accessor :pipe - - ## - # Array of directories to search for files to satisfy an :include: - - attr_reader :rdoc_include - - ## - # Include private and protected methods in the output? - - attr_accessor :show_all - - ## - # Include the '#' at the front of hyperlinked instance method names - - attr_reader :show_hash - - ## - # The number of columns in a tab - - attr_reader :tab_width - - ## - # Template to be used when generating output - - attr_reader :template - - ## - # Documentation title - - attr_reader :title - - ## - # Verbosity, zero means quiet - - attr_accessor :verbosity - - ## - # URL of web cvs frontend - - attr_reader :webcvs - - def initialize # :nodoc: - require 'rdoc/rdoc' - @op_dir = nil - @show_all = false - @main_page = nil - @exclude = [] - @generators = RDoc::RDoc::GENERATORS - @generator = RDoc::Generator::Darkfish - @generator_name = nil - @rdoc_include = [] - @title = nil - @template = nil - @show_hash = false - @tab_width = 8 - @force_update = true - @verbosity = 1 - @pipe = false - - @webcvs = nil - - @charset = 'utf-8' - end - - ## - # Parse command line options. - - def parse(argv) - ignore_invalid = true - - opts = OptionParser.new do |opt| - opt.program_name = File.basename $0 - opt.version = RDoc::VERSION - opt.release = nil - opt.summary_indent = ' ' * 4 - opt.banner = <<-EOF -Usage: #{opt.program_name} [options] [names...] - - Files are parsed, and the information they contain collected, before any - output is produced. This allows cross references between all files to be - resolved. If a name is a directory, it is traversed. If no names are - specified, all Ruby files in the current directory (and subdirectories) are - processed. - - How RDoc generates output depends on the output formatter being used, and on - the options you give. - - - Darkfish creates frameless HTML output by Michael Granger. - - ri creates ri data files - - RDoc understands the following file formats: - - EOF - - parsers = Hash.new { |h,parser| h[parser] = [] } - - RDoc::Parser.parsers.each do |regexp, parser| - parsers[parser.name.sub('RDoc::Parser::', '')] << regexp.source - end - - parsers.sort.each do |parser, regexp| - opt.banner << " - #{parser}: #{regexp.join ', '}\n" - end - - opt.separator nil - opt.separator "Parsing Options:" - opt.separator nil - - opt.on("--all", "-a", - "Include all methods (not just public) in", - "the output.") do |value| - @show_all = value - end - - opt.separator nil - - opt.on("--exclude=PATTERN", "-x", Regexp, - "Do not process files or directories", - "matching PATTERN.") do |value| - @exclude << value - end - - opt.separator nil - - opt.on("--extension=NEW=OLD", "-E", - "Treat files ending with .new as if they", - "ended with .old. Using '-E cgi=rb' will", - "cause xxx.cgi to be parsed as a Ruby file.") do |value| - new, old = value.split(/=/, 2) - - unless new and old then - raise OptionParser::InvalidArgument, "Invalid parameter to '-E'" - end - - unless RDoc::Parser.alias_extension old, new then - raise OptionParser::InvalidArgument, "Unknown extension .#{old} to -E" - end - end - - opt.separator nil - - opt.on("--[no-]force-update", "-U", - "Forces rdoc to scan all sources even if", - "newer than the flag file.") do |value| - @force_update = value - end - - opt.separator nil - - opt.on("--pipe", - "Convert RDoc on stdin to HTML") do - @pipe = true - end - - opt.separator nil - opt.separator "Generator Options:" - opt.separator nil - - opt.on("--charset=CHARSET", "-c", - "Specifies the output HTML character-set.") do |value| - @charset = value - end - - opt.separator nil - - generator_text = @generators.keys.map { |name| " #{name}" }.sort - - opt.on("--fmt=FORMAT", "--format=FORMAT", "-f", @generators.keys, - "Set the output formatter. One of:", *generator_text) do |value| - @generator_name = value.downcase - setup_generator - end - - opt.separator nil - - opt.on("--include=DIRECTORIES", "-i", Array, - "Set (or add to) the list of directories to", - "be searched when satisfying :include:", - "requests. Can be used more than once.") do |value| - @rdoc_include.concat value.map { |dir| dir.strip } - end - - opt.separator nil - - opt.on("--main=NAME", "-m", - "NAME will be the initial page displayed.") do |value| - @main_page = value - end - - opt.separator nil - - opt.on("--output=DIR", "--op", "-o", - "Set the output directory.") do |value| - @op_dir = value - end - - opt.separator nil - - opt.on("--show-hash", "-H", - "A name of the form #name in a comment is a", - "possible hyperlink to an instance method", - "name. When displayed, the '#' is removed", - "unless this option is specified.") do |value| - @show_hash = value - end - - opt.separator nil - - opt.on("--tab-width=WIDTH", "-w", OptionParser::DecimalInteger, - "Set the width of tab characters.") do |value| - @tab_width = value - end - - opt.separator nil - - opt.on("--template=NAME", "-T", - "Set the template used when generating", - "output.") do |value| - @template = value - end - - opt.separator nil - - opt.on("--title=TITLE", "-t", - "Set TITLE as the title for HTML output.") do |value| - @title = value - end - - opt.separator nil - - opt.on("--webcvs=URL", "-W", - "Specify a URL for linking to a web frontend", - "to CVS. If the URL contains a '\%s', the", - "name of the current file will be", - "substituted; if the URL doesn't contain a", - "'\%s', the filename will be appended to it.") do |value| - @webcvs = value - end - - opt.separator nil - - opt.on("-d", "--diagram", "Prevents -d from tripping --debug") - - opt.separator nil - opt.separator "ri Generator Options:" - opt.separator nil - - opt.on("--ri", "-r", - "Generate output for use by `ri`. The files", - "are stored in the '.rdoc' directory under", - "your home directory unless overridden by a", - "subsequent --op parameter, so no special", - "privileges are needed.") do |value| - @generator_name = "ri" - @op_dir ||= RDoc::RI::Paths::HOMEDIR - setup_generator - end - - opt.separator nil - - opt.on("--ri-site", "-R", - "Generate output for use by `ri`. The files", - "are stored in a site-wide directory,", - "making them accessible to others, so", - "special privileges are needed.") do |value| - @generator_name = "ri" - @op_dir = RDoc::RI::Paths::SITEDIR - setup_generator - end - - opt.separator nil - opt.separator "Generic Options:" - opt.separator nil - - opt.on("-D", "--[no-]debug", - "Displays lots on internal stuff.") do |value| - $DEBUG_RDOC = value - end - - opt.on("--[no-]ignore-invalid", - "Ignore invalid options and continue.") do |value| - ignore_invalid = value - end - - opt.on("--quiet", "-q", - "Don't show progress as we parse.") do |value| - @verbosity = 0 - end - - opt.on("--verbose", "-v", - "Display extra progress as we parse.") do |value| - @verbosity = 2 - end - - opt.separator nil - end - - argv.insert(0, *ENV['RDOCOPT'].split) if ENV['RDOCOPT'] - ignored = [] - - begin - opts.parse! argv - rescue OptionParser::InvalidArgument, OptionParser::InvalidOption => e - if ignore_invalid then - ignored << e.args.join(' ') - retry - else - $stderr.puts opts - $stderr.puts - $stderr.puts e - exit 1 - end - end - - if @pipe and not argv.empty? then - @pipe = false - ignored << '-p (with files)' - end - - unless ignored.empty? or quiet then - $stderr.puts "invalid options: #{ignored.join ', '}" - $stderr.puts '(invalid options are ignored)' - end - - @op_dir ||= 'doc' - @files = argv.dup - - @rdoc_include << "." if @rdoc_include.empty? - - if @exclude.empty? then - @exclude = nil - else - @exclude = Regexp.new(@exclude.join("|")) - end - - check_files - - # If no template was specified, use the default template for the output - # formatter - - @template ||= @generator_name - end - - ## - # Set the title, but only if not already set. This means that a title set - # from the command line trumps one set in a source file - - def title=(string) - @title ||= string - end - - ## - # Don't display progress as we process the files - - def quiet - @verbosity.zero? - end - - def quiet=(bool) - @verbosity = bool ? 0 : 1 - end - - private - - ## - # Set up an output generator for the format in @generator_name - - def setup_generator - @generator = @generators[@generator_name] - - unless @generator then - raise OptionParser::InvalidArgument, "Invalid output formatter" - end - end - - ## - # Check that the files on the command line exist - - def check_files - @files.each do |f| - stat = File.stat f rescue next - raise RDoc::Error, "file '#{f}' not readable" unless stat.readable? - end - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/parser.rb b/Src/StdLib/ruby/1.9.1/rdoc/parser.rb deleted file mode 100644 index 80b97f8d5..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/parser.rb +++ /dev/null @@ -1,157 +0,0 @@ -require 'rdoc' -require 'rdoc/code_objects' -require 'rdoc/markup/preprocess' -require 'rdoc/stats' - -## -# A parser is simple a class that implements -# -# #initialize(file_name, body, options) -# -# and -# -# #scan -# -# The initialize method takes a file name to be used, the body of the file, -# and an RDoc::Options object. The scan method is then called to return an -# appropriately parsed TopLevel code object. -# -# The ParseFactory is used to redirect to the correct parser given a -# filename extension. This magic works because individual parsers have to -# register themselves with us as they are loaded in. The do this using the -# following incantation -# -# require "rdoc/parser" -# -# class RDoc::Parser::Xyz < RDoc::Parser -# parse_files_matching /\.xyz$/ # <<<< -# -# def initialize(file_name, body, options) -# ... -# end -# -# def scan -# ... -# end -# end -# -# Just to make life interesting, if we suspect a plain text file, we also -# look for a shebang line just in case it's a potential shell script - -class RDoc::Parser - - @parsers = [] - - class << self - attr_reader :parsers - end - - ## - # Alias an extension to another extension. After this call, files ending - # "new_ext" will be parsed using the same parser as "old_ext" - - def self.alias_extension(old_ext, new_ext) - old_ext = old_ext.sub(/^\.(.*)/, '\1') - new_ext = new_ext.sub(/^\.(.*)/, '\1') - - parser = can_parse "xxx.#{old_ext}" - return false unless parser - - RDoc::Parser.parsers.unshift [/\.#{new_ext}$/, parser] - - true - end - - ## - # Determines if the file is a "binary" file which basically means it has - # content that an RDoc parser shouldn't try to consume. - - def self.binary?(file) - s = File.read(file, 1024) or return false - - if s[0, 2] == Marshal.dump('')[0, 2] then - true - elsif file =~ /erb\.rb$/ then - false - elsif s.scan(/<%|%>/).length >= 4 || s.index("\x00") then - true - elsif 0.respond_to? :fdiv then - s.count("^ -~\t\r\n").fdiv(s.size) > 0.3 - else # HACK 1.8.6 - (s.count("^ -~\t\r\n").to_f / s.size) > 0.3 - end - end - - ## - # Checks if +file+ is a zip file in disguise. Signatures from - # http://www.garykessler.net/library/file_sigs.html - - def self.zip? file - zip_signature = File.read file, 4 - - zip_signature == "PK\x03\x04" or - zip_signature == "PK\x05\x06" or - zip_signature == "PK\x07\x08" - end - - ## - # Return a parser that can handle a particular extension - - def self.can_parse(file_name) - parser = RDoc::Parser.parsers.find { |regexp,| regexp =~ file_name }.last - - # HACK Selenium hides a jar file using a .txt extension - return if parser == RDoc::Parser::Simple and zip? file_name - - # The default parser must not parse binary files - ext_name = File.extname file_name - return parser if ext_name.empty? - return if parser == RDoc::Parser::Simple and ext_name !~ /txt|rdoc/ - - parser - end - - ## - # Find the correct parser for a particular file name. Return a SimpleParser - # for ones that we don't know - - def self.for(top_level, file_name, body, options, stats) - return if binary? file_name - - # If no extension, look for shebang - if file_name !~ /\.\w+$/ && body =~ %r{\A#!(.+)} then - shebang = $1 - case shebang - when %r{env\s+ruby}, %r{/ruby} - file_name = "dummy.rb" - end - end - - parser = can_parse file_name - - return unless parser - - parser.new top_level, file_name, body, options, stats - end - - ## - # Record which file types this parser can understand. - # - # It is ok to call this multiple times. - - def self.parse_files_matching(regexp) - RDoc::Parser.parsers.unshift [regexp, self] - end - - def initialize(top_level, file_name, content, options, stats) - @top_level = top_level - @file_name = file_name - @content = content - @options = options - @stats = stats - end - -end - -require 'rdoc/parser/simple' - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/parser/c.rb b/Src/StdLib/ruby/1.9.1/rdoc/parser/c.rb deleted file mode 100644 index c9b12ef99..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/parser/c.rb +++ /dev/null @@ -1,705 +0,0 @@ -require 'rdoc/parser' -require 'rdoc/parser/ruby' -require 'rdoc/known_classes' - -## -# We attempt to parse C extension files. Basically we look for -# the standard patterns that you find in extensions: rb_define_class, -# rb_define_method and so on. We also try to find the corresponding -# C source for the methods and extract comments, but if we fail -# we don't worry too much. -# -# The comments associated with a Ruby method are extracted from the C -# comment block associated with the routine that _implements_ that -# method, that is to say the method whose name is given in the -# rb_define_method call. For example, you might write: -# -# /* -# * Returns a new array that is a one-dimensional flattening of this -# * array (recursively). That is, for every element that is an array, -# * extract its elements into the new array. -# * -# * s = [ 1, 2, 3 ] #=> [1, 2, 3] -# * t = [ 4, 5, 6, [7, 8] ] #=> [4, 5, 6, [7, 8]] -# * a = [ s, t, 9, 10 ] #=> [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10] -# * a.flatten #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] -# */ -# static VALUE -# rb_ary_flatten(ary) -# VALUE ary; -# { -# ary = rb_obj_dup(ary); -# rb_ary_flatten_bang(ary); -# return ary; -# } -# -# ... -# -# void -# Init_Array() -# { -# ... -# rb_define_method(rb_cArray, "flatten", rb_ary_flatten, 0); -# -# Here RDoc will determine from the rb_define_method line that there's a -# method called "flatten" in class Array, and will look for the implementation -# in the method rb_ary_flatten. It will then use the comment from that -# method in the HTML output. This method must be in the same source file -# as the rb_define_method. -# -# The comment blocks may include special directives: -# -# [Document-class: name] -# This comment block is documentation for the given class. Use this -# when the Init_xxx method is not named after the class. -# -# [Document-method: name] -# This comment documents the named method. Use when RDoc cannot -# automatically find the method from it's declaration -# -# [call-seq: text up to an empty line] -# Because C source doesn't give descripive names to Ruby-level parameters, -# you need to document the calling sequence explicitly -# -# In addition, RDoc assumes by default that the C method implementing a -# Ruby function is in the same source file as the rb_define_method call. -# If this isn't the case, add the comment: -# -# rb_define_method(....); // in filename -# -# As an example, we might have an extension that defines multiple classes -# in its Init_xxx method. We could document them using -# -# /* -# * Document-class: MyClass -# * -# * Encapsulate the writing and reading of the configuration -# * file. ... -# */ -# -# /* -# * Document-method: read_value -# * -# * call-seq: -# * cfg.read_value(key) -> value -# * cfg.read_value(key} { |key| } -> value -# * -# * Return the value corresponding to +key+ from the configuration. -# * In the second form, if the key isn't found, invoke the -# * block and return its value. -# */ - -class RDoc::Parser::C < RDoc::Parser - - parse_files_matching(/\.(?:([CcHh])\1?|c([+xp])\2|y)\z/) - - include RDoc::Text - - ## - # C file the parser is parsing - - attr_accessor :content - - ## - # Resets cross-file state. Call when parsing different projects that need - # separate documentation. - - def self.reset - @@enclosure_classes = {} - @@known_bodies = {} - end - - reset - - ## - # Prepare to parse a C file - - def initialize(top_level, file_name, content, options, stats) - super - - @known_classes = RDoc::KNOWN_CLASSES.dup - @content = handle_tab_width handle_ifdefs_in(@content) - @classes = Hash.new - @file_dir = File.dirname(@file_name) - end - - def do_aliases - @content.scan(%r{rb_define_alias\s*\(\s*(\w+),\s*"([^"]+)",\s*"([^"]+)"\s*\)}m) do - |var_name, new_name, old_name| - class_name = @known_classes[var_name] || var_name - class_obj = find_class(var_name, class_name) - - as = class_obj.add_alias RDoc::Alias.new("", old_name, new_name, "") - - @stats.add_alias as - end - end - - def do_classes - @content.scan(/(\w+)\s* = \s*rb_define_module\s*\(\s*"(\w+)"\s*\)/mx) do - |var_name, class_name| - handle_class_module(var_name, "module", class_name, nil, nil) - end - - # The '.' lets us handle SWIG-generated files - @content.scan(/([\w\.]+)\s* = \s*rb_define_class\s* - \( - \s*"(\w+)", - \s*(\w+)\s* - \)/mx) do |var_name, class_name, parent| - handle_class_module(var_name, "class", class_name, parent, nil) - end - - @content.scan(/(\w+)\s*=\s*boot_defclass\s*\(\s*"(\w+?)",\s*(\w+?)\s*\)/) do - |var_name, class_name, parent| - parent = nil if parent == "0" - handle_class_module(var_name, "class", class_name, parent, nil) - end - - @content.scan(/(\w+)\s* = \s*rb_define_module_under\s* - \( - \s*(\w+), - \s*"(\w+)" - \s*\)/mx) do |var_name, in_module, class_name| - handle_class_module(var_name, "module", class_name, nil, in_module) - end - - @content.scan(/([\w\.]+)\s* = \s*rb_define_class_under\s* - \( - \s*(\w+), - \s*"(\w+)", - \s*([\w\*\s\(\)\.\->]+)\s* # for SWIG - \s*\)/mx) do |var_name, in_module, class_name, parent| - handle_class_module(var_name, "class", class_name, parent, in_module) - end - end - - def do_constants - @content.scan(%r{\Wrb_define_ - ( variable | - readonly_variable | - const | - global_const | ) - \s*\( - (?:\s*(\w+),)? - \s*"(\w+)", - \s*(.*?)\s*\)\s*; - }xm) do |type, var_name, const_name, definition| - var_name = "rb_cObject" if !var_name or var_name == "rb_mKernel" - handle_constants type, var_name, const_name, definition - end - end - - ## - # Look for includes of the form: - # - # rb_include_module(rb_cArray, rb_mEnumerable); - - def do_includes - @content.scan(/rb_include_module\s*\(\s*(\w+?),\s*(\w+?)\s*\)/) do |c,m| - if cls = @classes[c] - m = @known_classes[m] || m - cls.add_include RDoc::Include.new(m, "") - end - end - end - - def do_methods - @content.scan(%r{rb_define_ - ( - singleton_method | - method | - module_function | - private_method - ) - \s*\(\s*([\w\.]+), - \s*"([^"]+)", - \s*(?:RUBY_METHOD_FUNC\(|VALUEFUNC\()?(\w+)\)?, - \s*(-?\w+)\s*\) - (?:;\s*/[*/]\s+in\s+(\w+?\.[cy]))? - }xm) do - |type, var_name, meth_name, meth_body, param_count, source_file| - - # Ignore top-object and weird struct.c dynamic stuff - next if var_name == "ruby_top_self" - next if var_name == "nstr" - next if var_name == "envtbl" - next if var_name == "argf" # it'd be nice to handle this one - - var_name = "rb_cObject" if var_name == "rb_mKernel" - handle_method(type, var_name, meth_name, meth_body, param_count, - source_file) - end - - @content.scan(%r{rb_define_attr\( - \s*([\w\.]+), - \s*"([^"]+)", - \s*(\d+), - \s*(\d+)\s*\); - }xm) do |var_name, attr_name, attr_reader, attr_writer| - #var_name = "rb_cObject" if var_name == "rb_mKernel" - handle_attr(var_name, attr_name, - attr_reader.to_i != 0, - attr_writer.to_i != 0) - end - - @content.scan(%r{rb_define_global_function\s*\( - \s*"([^"]+)", - \s*(?:RUBY_METHOD_FUNC\(|VALUEFUNC\()?(\w+)\)?, - \s*(-?\w+)\s*\) - (?:;\s*/[*/]\s+in\s+(\w+?\.[cy]))? - }xm) do |meth_name, meth_body, param_count, source_file| - handle_method("method", "rb_mKernel", meth_name, - meth_body, param_count, source_file) - end - - @content.scan(/define_filetest_function\s*\( - \s*"([^"]+)", - \s*(?:RUBY_METHOD_FUNC\(|VALUEFUNC\()?(\w+)\)?, - \s*(-?\w+)\s*\)/xm) do - |meth_name, meth_body, param_count| - - handle_method("method", "rb_mFileTest", meth_name, meth_body, param_count) - handle_method("singleton_method", "rb_cFile", meth_name, meth_body, param_count) - end - end - - def find_attr_comment(attr_name) - if @content =~ %r{((?>/\*.*?\*/\s+)) - rb_define_attr\((?:\s*(\w+),)?\s*"#{attr_name}"\s*,.*?\)\s*;}xmi - $1 - elsif @content =~ %r{Document-attr:\s#{attr_name}\s*?\n((?>.*?\*/))}m - $1 - else - '' - end - end - - ## - # Find the C code corresponding to a Ruby method - - def find_body(class_name, meth_name, meth_obj, body, quiet = false) - case body - when %r"((?>/\*.*?\*/\s*))((?:(?:static|SWIGINTERN)\s+)?(?:intern\s+)?VALUE\s+#{meth_name} - \s*(\([^)]*\))([^;]|$))"xm - comment = $1 - body_text = $2 - params = $3 - - remove_private_comments comment if comment - - # see if we can find the whole body - - re = Regexp.escape(body_text) + '[^(]*^\{.*?^\}' - body_text = $& if /#{re}/m =~ body - - # The comment block may have been overridden with a 'Document-method' - # block. This happens in the interpreter when multiple methods are - # vectored through to the same C method but those methods are logically - # distinct (for example Kernel.hash and Kernel.object_id share the same - # implementation - - override_comment = find_override_comment class_name, meth_obj.name - comment = override_comment if override_comment - - find_modifiers comment, meth_obj if comment - - #meth_obj.params = params - meth_obj.start_collecting_tokens - tk = RDoc::RubyToken::Token.new nil, 1, 1 - tk.set_text body_text - meth_obj.add_token tk - meth_obj.comment = strip_stars comment - when %r{((?>/\*.*?\*/\s*))^\s*(\#\s*define\s+#{meth_name}\s+(\w+))}m - comment = $1 - body_text = $2 - find_body class_name, $3, meth_obj, body, true - find_modifiers comment, meth_obj - - meth_obj.start_collecting_tokens - tk = RDoc::RubyToken::Token.new nil, 1, 1 - tk.set_text body_text - meth_obj.add_token tk - meth_obj.comment = strip_stars(comment) + meth_obj.comment.to_s - when %r{^\s*\#\s*define\s+#{meth_name}\s+(\w+)}m - unless find_body(class_name, $1, meth_obj, body, true) - warn "No definition for #{meth_name}" unless @options.quiet - return false - end - else - # No body, but might still have an override comment - comment = find_override_comment(class_name, meth_obj.name) - - if comment - find_modifiers(comment, meth_obj) - meth_obj.comment = strip_stars comment - else - warn "No definition for #{meth_name}" unless @options.quiet - return false - end - end - true - end - - def find_class(raw_name, name) - unless @classes[raw_name] - if raw_name =~ /^rb_m/ - container = @top_level.add_module RDoc::NormalModule, name - else - container = @top_level.add_class RDoc::NormalClass, name - end - - container.record_location @top_level - @classes[raw_name] = container - end - @classes[raw_name] - end - - ## - # Look for class or module documentation above Init_+class_name+(void), - # in a Document-class +class_name+ (or module) comment or above an - # rb_define_class (or module). If a comment is supplied above a matching - # Init_ and a rb_define_class the Init_ comment is used. - # - # /* - # * This is a comment for Foo - # */ - # Init_Foo(void) { - # VALUE cFoo = rb_define_class("Foo", rb_cObject); - # } - # - # /* - # * Document-class: Foo - # * This is a comment for Foo - # */ - # Init_foo(void) { - # VALUE cFoo = rb_define_class("Foo", rb_cObject); - # } - # - # /* - # * This is a comment for Foo - # */ - # VALUE cFoo = rb_define_class("Foo", rb_cObject); - - def find_class_comment(class_name, class_mod) - comment = nil - - if @content =~ %r{ - ((?>/\*.*?\*/\s+)) - (static\s+)? - void\s+ - Init_#{class_name}\s*(?:_\(\s*)?\(\s*(?:void\s*)?\)}xmi then # ) - comment = $1 - elsif @content =~ %r{Document-(?:class|module):\s+#{class_name}\s*?(?:<\s+[:,\w]+)?\n((?>.*?\*/))}m then - comment = $1 - elsif @content =~ %r{((?>/\*.*?\*/\s+)) - ([\w\.\s]+\s* = \s+)?rb_define_(class|module).*?"(#{class_name})"}xm then # " - comment = $1 - end - - return unless comment - - comment = strip_stars comment - - comment = look_for_directives_in class_mod, comment - - class_mod.comment = comment - end - - ## - # Finds a comment matching +type+ and +const_name+ either above the - # comment or in the matching Document- section. - - def find_const_comment(type, const_name) - if @content =~ %r{((?>^\s*/\*.*?\*/\s+)) - rb_define_#{type}\((?:\s*(\w+),)?\s*"#{const_name}"\s*,.*?\)\s*;}xmi - $1 - elsif @content =~ %r{Document-(?:const|global|variable):\s#{const_name}\s*?\n((?>.*?\*/))}m - $1 - else - '' - end - end - - ## - # If the comment block contains a section that looks like: - # - # call-seq: - # Array.new - # Array.new(10) - # - # use it for the parameters. - - def find_modifiers(comment, meth_obj) - if comment.sub!(/:nodoc:\s*^\s*\*?\s*$/m, '') or - comment.sub!(/\A\/\*\s*:nodoc:\s*\*\/\Z/, '') - meth_obj.document_self = false - end - if comment.sub!(/call-seq:(.*?)^\s*\*?\s*$/m, '') or - comment.sub!(/\A\/\*\s*call-seq:(.*?)\*\/\Z/, '') - seq = $1 - seq.gsub!(/^\s*\*\s*/, '') - meth_obj.call_seq = seq - end - end - - def find_override_comment(class_name, meth_name) - name = Regexp.escape(meth_name) - if @content =~ %r{Document-method:\s+#{class_name}(?:\.|::|#)#{name}\s*?\n((?>.*?\*/))}m then - $1 - elsif @content =~ %r{Document-method:\s#{name}\s*?\n((?>.*?\*/))}m then - $1 - end - end - - def handle_attr(var_name, attr_name, reader, writer) - rw = '' - rw << 'R' if reader - rw << 'W' if writer - - class_name = @known_classes[var_name] - - return unless class_name - - class_obj = find_class(var_name, class_name) - - if class_obj - comment = find_attr_comment(attr_name) - comment = strip_stars comment - att = RDoc::Attr.new '', attr_name, rw, comment - @stats.add_method att - class_obj.add_attribute(att) - end - end - - def handle_class_module(var_name, type, class_name, parent, in_module) - parent_name = @known_classes[parent] || parent - - if in_module then - enclosure = @classes[in_module] || @@enclosure_classes[in_module] - - if enclosure.nil? and enclosure = @known_classes[in_module] then - type = /^rb_m/ =~ in_module ? "module" : "class" - handle_class_module in_module, type, enclosure, nil, nil - enclosure = @classes[in_module] - end - - unless enclosure then - warn "Enclosing class/module '#{in_module}' for #{type} #{class_name} not known" - return - end - else - enclosure = @top_level - end - - if type == "class" then - full_name = if RDoc::ClassModule === enclosure then - enclosure.full_name + "::#{class_name}" - else - class_name - end - - if @content =~ %r{Document-class:\s+#{full_name}\s*<\s+([:,\w]+)} then - parent_name = $1 - end - - cm = enclosure.add_class RDoc::NormalClass, class_name, parent_name - - @stats.add_class cm - else - cm = enclosure.add_module RDoc::NormalModule, class_name - @stats.add_module cm - end - - cm.record_location enclosure.top_level - - find_class_comment cm.full_name, cm - - @classes[var_name] = cm - @@enclosure_classes[var_name] = cm - @known_classes[var_name] = cm.full_name - end - - ## - # Adds constant comments. By providing some_value: at the start ofthe - # comment you can override the C value of the comment to give a friendly - # definition. - # - # /* 300: The perfect score in bowling */ - # rb_define_const(cFoo, "PERFECT", INT2FIX(300); - # - # Will override +INT2FIX(300)+ with the value +300+ in the output RDoc. - # Values may include quotes and escaped colons (\:). - - def handle_constants(type, var_name, const_name, definition) - class_name = @known_classes[var_name] - - return unless class_name - - class_obj = find_class var_name, class_name - - unless class_obj then - warn "Enclosing class/module #{const_name.inspect} not known" - return - end - - comment = find_const_comment type, const_name - comment = strip_stars comment - comment = normalize_comment comment - - # In the case of rb_define_const, the definition and comment are in - # "/* definition: comment */" form. The literal ':' and '\' characters - # can be escaped with a backslash. - if type.downcase == 'const' then - elements = comment.split ':' - - if elements.nil? or elements.empty? then - con = RDoc::Constant.new const_name, definition, comment - else - new_definition = elements[0..-2].join(':') - - if new_definition.empty? then # Default to literal C definition - new_definition = definition - else - new_definition.gsub!("\:", ":") - new_definition.gsub!("\\", '\\') - end - - new_definition.sub!(/\A(\s+)/, '') - - new_comment = if $1.nil? then - elements.last.lstrip - else - "#{$1}#{elements.last.lstrip}" - end - - con = RDoc::Constant.new const_name, new_definition, new_comment - end - else - con = RDoc::Constant.new const_name, definition, comment - end - - @stats.add_constant con - class_obj.add_constant con - end - - ## - # Removes #ifdefs that would otherwise confuse us - - def handle_ifdefs_in(body) - body.gsub(/^#ifdef HAVE_PROTOTYPES.*?#else.*?\n(.*?)#endif.*?\n/m, '\1') - end - - def handle_method(type, var_name, meth_name, meth_body, param_count, - source_file = nil) - class_name = @known_classes[var_name] - - return unless class_name - - class_obj = find_class var_name, class_name - - if class_obj then - if meth_name == "initialize" then - meth_name = "new" - type = "singleton_method" - end - - meth_obj = RDoc::AnyMethod.new '', meth_name - meth_obj.singleton = %w[singleton_method module_function].include? type - - p_count = Integer(param_count) rescue -1 - - if p_count < 0 then - meth_obj.params = "(...)" - elsif p_count == 0 - meth_obj.params = "()" - else - meth_obj.params = "(" + (1..p_count).map{|i| "p#{i}"}.join(", ") + ")" - end - - if source_file then - file_name = File.join @file_dir, source_file - - if File.exist? file_name then - body = (@@known_bodies[file_name] ||= File.read(file_name)) - else - warn "unknown source #{source_file} for #{meth_name} in #{@file_name}" - end - else - body = @content - end - - if find_body(class_name, meth_body, meth_obj, body) and meth_obj.document_self then - class_obj.add_method meth_obj - @stats.add_method meth_obj - meth_obj.visibility = :private if 'private_method' == type - end - end - end - - def handle_tab_width(body) - if /\t/ =~ body - tab_width = @options.tab_width - body.split(/\n/).map do |line| - 1 while line.gsub!(/\t+/) { ' ' * (tab_width*$&.length - $`.length % tab_width)} && $~ #` - line - end .join("\n") - else - body - end - end - - ## - # Look for directives in a normal comment block: - # - # /* - # * :title: My Awesome Project - # */ - # - # This routine modifies it's parameter - - def look_for_directives_in(context, comment) - preprocess = RDoc::Markup::PreProcess.new @file_name, @options.rdoc_include - - preprocess.handle comment, context do |directive, param| - case directive - when 'main' then - @options.main_page = param - '' - when 'title' then - @options.title = param - '' - end - end - - comment - end - ## - # Removes lines that are commented out that might otherwise get picked up - # when scanning for classes and methods - - def remove_commented_out_lines - @content.gsub!(%r{//.*rb_define_}, '//') - end - - def remove_private_comments(comment) - comment.gsub!(/\/?\*--\n(.*?)\/?\*\+\+/m, '') - comment.sub!(/\/?\*--\n.*/m, '') - end - - ## - # Extract the classes/modules and methods from a C file and return the - # corresponding top-level object - - def scan - remove_commented_out_lines - do_classes - do_constants - do_methods - do_includes - do_aliases - @top_level - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/parser/perl.rb b/Src/StdLib/ruby/1.9.1/rdoc/parser/perl.rb deleted file mode 100644 index 032a35cec..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/parser/perl.rb +++ /dev/null @@ -1,165 +0,0 @@ -require 'rdoc/parser' - -## -# -# This is an attamept to write a basic parser for Perl's -# POD (Plain old Documentation) format. Ruby code must -# co-exist with Perl, and some tasks are easier in Perl -# than Ruby because of existing libraries. -# -# One difficult is that Perl POD has no means of identifying -# the classes (packages) and methods (subs) with which it -# is associated, it is more like literate programming in so -# far as it just happens to be in the same place as the code, -# but need not be. -# -# We would like to support all the markup the POD provides -# so that it will convert happily to HTML. At the moment -# I don't think I can do that: time constraints. -# - -class RDoc::Parser::PerlPOD < RDoc::Parser - - parse_files_matching(/.p[lm]$/) - - ## - # Prepare to parse a perl file - - def initialize(top_level, file_name, content, options, stats) - super - - preprocess = RDoc::Markup::PreProcess.new @file_name, @options.rdoc_include - - preprocess.handle @content do |directive, param| - warn "Unrecognized directive '#{directive}' in #{@file_name}" - end - end - - ## - # Extract the Pod(-like) comments from the code. - # At its most basic there will ne no need to distinguish - # between the different types of header, etc. - # - # This uses a simple finite state machine, in a very - # procedural pattern. I could "replace case with polymorphism" - # but I think it would obscure the intent, scatter the - # code all over tha place. This machine is necessary - # because POD requires that directives be preceded by - # blank lines, so reading line by line is necessary, - # and preserving state about what is seen is necesary. - - def scan - - @top_level.comment ||= "" - state=:code_blank - line_number = 0 - line = nil - - # This started out as a really long nested case statement, - # which also led to repetitive code. I'd like to avoid that - # so I'm using a "table" instead. - - # Firstly we need some procs to do the transition and processing - # work. Because these are procs they are closures, and they can - # use variables in the local scope. - # - # First, the "nothing to see here" stuff. - code_noop = lambda do - if line =~ /^\s+$/ - state = :code_blank - end - end - - pod_noop = lambda do - if line =~ /^\s+$/ - state = :pod_blank - end - @top_level.comment += filter(line) - end - - begin_noop = lambda do - if line =~ /^\s+$/ - state = :begin_blank - end - @top_level.comment += filter(line) - end - - # Now for the blocks that process code and comments... - - transit_to_pod = lambda do - case line - when /^=(?:pod|head\d+)/ - state = :pod_no_blank - @top_level.comment += filter(line) - when /^=over/ - state = :over_no_blank - @top_level.comment += filter(line) - when /^=(?:begin|for)/ - state = :begin_no_blank - end - end - - process_pod = lambda do - case line - when /^\s*$/ - state = :pod_blank - @top_level.comment += filter(line) - when /^=cut/ - state = :code_no_blank - when /^=end/ - $stderr.puts "'=end' unexpected at #{line_number} in #{@file_name}" - else - @top_level.comment += filter(line) - end - end - - - process_begin = lambda do - case line - when /^\s*$/ - state = :begin_blank - @top_level.comment += filter(line) - when /^=end/ - state = :code_no_blank - when /^=cut/ - $stderr.puts "'=cut' unexpected at #{line_number} in #{@file_name}" - else - @top_level.comment += filter(line) - end - - end - - - transitions = { :code_no_blank => code_noop, - :code_blank => transit_to_pod, - :pod_no_blank => pod_noop, - :pod_blank => process_pod, - :begin_no_blank => begin_noop, - :begin_blank => process_begin} - @content.each_line do |l| - line = l - line_number += 1 - transitions[state].call - end # each line - - @top_level - end - - # Filter the perl markup that does the same as the rdoc - # filtering. Only basic for now. Will probably need a - # proper parser to cope with C<<...>> etc - def filter(comment) - return '' if comment =~ /^=pod\s*$/ - comment.gsub!(/^=pod/, '==') - comment.gsub!(/^=head(\d+)/) do - "=" * $1.to_i - end - comment.gsub!(/=item/, ''); - comment.gsub!(/C<(.*?)>/, '\1'); - comment.gsub!(/I<(.*?)>/, '\1'); - comment.gsub!(/B<(.*?)>/, '\1'); - comment - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/parser/ruby.rb b/Src/StdLib/ruby/1.9.1/rdoc/parser/ruby.rb deleted file mode 100644 index 4698fd82a..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/parser/ruby.rb +++ /dev/null @@ -1,1599 +0,0 @@ -## -# This file contains stuff stolen outright from: -# -# rtags.rb - -# ruby-lex.rb - ruby lexcal analyzer -# ruby-token.rb - ruby tokens -# by Keiju ISHITSUKA (Nippon Rational Inc.) -# - -require 'rdoc/ruby_token' -require 'rdoc/ruby_lex' - -require 'rdoc/code_objects' -require 'rdoc/tokenstream' -require 'rdoc/markup/preprocess' -require 'rdoc/parser' -require 'rdoc/parser/ruby_tools' - -$TOKEN_DEBUG ||= nil - -## -# Extracts code elements from a source file returning a TopLevel object -# containing the constituent file elements. -# -# This file is based on rtags -# -# RubyParser understands how to document: -# * classes -# * modules -# * methods -# * constants -# * aliases -# * private, public, protected -# * private_class_function, public_class_function -# * module_function -# * attr, attr_reader, attr_writer, attr_accessor -# * extra accessors given on the command line -# * metaprogrammed methods -# * require -# * include -# -# == Method Arguments -# -#-- -# NOTE: I don't think this works, needs tests, remove the paragraph following -# this block when known to work -# -# The parser extracts the arguments from the method definition. You can -# override this with a custom argument definition using the :args: directive: -# -# ## -# # This method tries over and over until it is tired -# -# def go_go_go(thing_to_try, tries = 10) # :args: thing_to_try -# puts thing_to_try -# go_go_go thing_to_try, tries - 1 -# end -# -# If you have a more-complex set of overrides you can use the :call-seq: -# directive: -#++ -# -# The parser extracts the arguments from the method definition. You can -# override this with a custom argument definition using the :call-seq: -# directive: -# -# ## -# # This method can be called with a range or an offset and length -# # -# # :call-seq: -# # my_method(Range) -# # my_method(offset, length) -# -# def my_method(*args) -# end -# -# The parser extracts +yield+ expressions from method bodies to gather the -# yielded argument names. If your method manually calls a block instead of -# yielding or you want to override the discovered argument names use -# the :yields: directive: -# -# ## -# # My method is awesome -# -# def my_method(&block) # :yields: happy, times -# block.call 1, 2 -# end -# -# == Metaprogrammed Methods -# -# To pick up a metaprogrammed method, the parser looks for a comment starting -# with '##' before an identifier: -# -# ## -# # This is a meta-programmed method! -# -# add_my_method :meta_method, :arg1, :arg2 -# -# The parser looks at the token after the identifier to determine the name, in -# this example, :meta_method. If a name cannot be found, a warning is printed -# and 'unknown is used. -# -# You can force the name of a method using the :method: directive: -# -# ## -# # :method: woo_hoo! -# -# By default, meta-methods are instance methods. To indicate that a method is -# a singleton method instead use the :singleton-method: directive: -# -# ## -# # :singleton-method: -# -# You can also use the :singleton-method: directive with a name: -# -# ## -# # :singleton-method: woo_hoo! -# -# Additionally you can mark a method as an attribute by -# using :attr:, :attr_reader:, :attr_writer: or :attr_accessor:. Just like -# for :method:, the name is optional. -# -# ## -# # :attr_reader: my_attr_name -# -# == Hidden methods and attributes -# -# You can provide documentation for methods that don't appear using -# the :method:, :singleton-method: and :attr: directives: -# -# ## -# # :attr_writer: ghost_writer -# # There is an attribute here, but you can't see it! -# -# ## -# # :method: ghost_method -# # There is a method here, but you can't see it! -# -# ## -# # this is a comment for a regular method -# -# def regular_method() end -# -# Note that by default, the :method: directive will be ignored if there is a -# standard rdocable item following it. - -class RDoc::Parser::Ruby < RDoc::Parser - - parse_files_matching(/\.rbw?$/) - - include RDoc::RubyToken - include RDoc::TokenStream - include RDoc::Parser::RubyTools - - ## - # RDoc::NormalClass type - - NORMAL = "::" - - ## - # RDoc::SingleClass type - - SINGLE = "<<" - - def initialize(top_level, file_name, content, options, stats) - super - - @size = 0 - @token_listeners = nil - @scanner = RDoc::RubyLex.new content, @options - @scanner.exception_on_syntax_error = false - @prev_seek = nil - - reset - end - - ## - # Look for the first comment in a file that isn't a shebang line. - - def collect_first_comment - skip_tkspace - comment = '' - first_line = true - - tk = get_tk - - while TkCOMMENT === tk - if first_line and tk.text =~ /\A#!/ then - skip_tkspace - tk = get_tk - elsif first_line and tk.text =~ /\A#\s*-\*-/ then - first_line = false - skip_tkspace - tk = get_tk - else - first_line = false - comment << tk.text << "\n" - tk = get_tk - - if TkNL === tk then - skip_tkspace false - tk = get_tk - end - end - end - - unget_tk tk - - comment - end - - def error(msg) - msg = make_message msg - $stderr.puts msg - exit false - end - - ## - # Look for a 'call-seq' in the comment, and override the normal parameter - # stuff - - def extract_call_seq(comment, meth) - if comment.sub!(/:?call-seq:(.*?)^\s*\#?\s*$/m, '') then - seq = $1 - seq.gsub!(/^\s*\#\s*/, '') - meth.call_seq = seq - end - - meth - end - - def get_bool - skip_tkspace - tk = get_tk - case tk - when TkTRUE - true - when TkFALSE, TkNIL - false - else - unget_tk tk - true - end - end - - ## - # Look for the name of a class of module (optionally with a leading :: or - # with :: separated named) and return the ultimate name and container - - def get_class_or_module(container) - skip_tkspace - name_t = get_tk - - # class ::A -> A is in the top level - case name_t - when TkCOLON2, TkCOLON3 then # bug - name_t = get_tk - container = @top_level - end - - skip_tkspace false - - while TkCOLON2 === peek_tk do - prev_container = container - container = container.find_module_named name_t.name - unless container then - container = prev_container.add_module RDoc::NormalModule, name_t.name - end - get_tk - name_t = get_tk - end - skip_tkspace false - return [container, name_t] - end - - ## - # Return a superclass, which can be either a constant of an expression - - def get_class_specification - tk = get_tk - return "self" if TkSELF === tk - - res = "" - while TkCOLON2 === tk or TkCOLON3 === tk or TkCONSTANT === tk do - res += tk.name - tk = get_tk - end - - unget_tk(tk) - skip_tkspace false - - get_tkread # empty out read buffer - - tk = get_tk - - case tk - when TkNL, TkCOMMENT, TkSEMICOLON then - unget_tk(tk) - return res - end - - res += parse_call_parameters(tk) - res - end - - ## - # Parse a constant, which might be qualified by one or more class or module - # names - - def get_constant - res = "" - skip_tkspace false - tk = get_tk - - while TkCOLON2 === tk or TkCOLON3 === tk or TkCONSTANT === tk do - res += tk.name - tk = get_tk - end - -# if res.empty? -# warn("Unexpected token #{tk} in constant") -# end - unget_tk(tk) - res - end - - ## - # Get a constant that may be surrounded by parens - - def get_constant_with_optional_parens - skip_tkspace false - nest = 0 - while TkLPAREN === (tk = peek_tk) or TkfLPAREN === tk do - get_tk - skip_tkspace - nest += 1 - end - - name = get_constant - - while nest > 0 - skip_tkspace - tk = get_tk - nest -= 1 if TkRPAREN === tk - end - - name - end - - def get_symbol_or_name - tk = get_tk - case tk - when TkSYMBOL then - text = tk.text.sub(/^:/, '') - - if TkASSIGN === peek_tk then - get_tk - text << '=' - end - - text - when TkId, TkOp then - tk.name - when TkSTRING, TkDSTRING then - tk.text - else - raise RDoc::Error, "Name or symbol expected (got #{tk})" - end - end - - ## - # Look for directives in a normal comment block: - # - # # :stopdoc: - # # Don't display comment from this point forward - # - # This routine modifies it's parameter - - def look_for_directives_in(context, comment) - preprocess = RDoc::Markup::PreProcess.new @file_name, @options.rdoc_include - - preprocess.handle comment, context do |directive, param| - case directive - when 'enddoc' then - throw :enddoc - when 'main' then - @options.main_page = param - '' - when 'method', 'singleton-method', - 'attr', 'attr_accessor', 'attr_reader', 'attr_writer' then - false # handled elsewhere - when 'section' then - context.set_current_section param, comment - comment.replace '' - break - when 'startdoc' then - context.start_doc - context.force_documentation = true - '' - when 'stopdoc' then - context.stop_doc - '' - when 'title' then - @options.title = param - '' - end - end - - remove_private_comments comment - end - - ## - # Adds useful info about the parser to +message+ - - def make_message message - prefix = "#{@file_name}:" - - prefix << "#{@scanner.line_no}:#{@scanner.char_no}:" if @scanner - - "#{prefix} #{message}" - end - - ## - # Creates an RDoc::Attr for the name following +tk+, setting the comment to - # +comment+. - - def parse_attr(context, single, tk, comment) - args = parse_symbol_arg 1 - if args.size > 0 - name = args[0] - rw = "R" - skip_tkspace false - tk = get_tk - if TkCOMMA === tk then - rw = "RW" if get_bool - else - unget_tk tk - end - att = RDoc::Attr.new get_tkread, name, rw, comment - read_documentation_modifiers att, RDoc::ATTR_MODIFIERS - if att.document_self - context.add_attribute(att) - end - else - warn("'attr' ignored - looks like a variable") - end - end - - ## - # Creates an RDoc::Attr for each attribute listed after +tk+, setting the - # comment for each to +comment+. - - def parse_attr_accessor(context, single, tk, comment) - args = parse_symbol_arg - read = get_tkread - rw = "?" - - # TODO If nodoc is given, don't document any of them - - tmp = RDoc::CodeObject.new - read_documentation_modifiers tmp, RDoc::ATTR_MODIFIERS - return unless tmp.document_self - - case tk.name - when "attr_reader" then rw = "R" - when "attr_writer" then rw = "W" - when "attr_accessor" then rw = "RW" - else - rw = '?' - end - - for name in args - att = RDoc::Attr.new get_tkread, name, rw, comment - context.add_attribute att - end - end - - def parse_alias(context, single, tk, comment) - skip_tkspace - if TkLPAREN === peek_tk then - get_tk - skip_tkspace - end - new_name = get_symbol_or_name - - @scanner.instance_eval { @lex_state = EXPR_FNAME } - - skip_tkspace - if TkCOMMA === peek_tk then - get_tk - skip_tkspace - end - - begin - old_name = get_symbol_or_name - rescue RDoc::Error - return - end - - al = RDoc::Alias.new get_tkread, old_name, new_name, comment - read_documentation_modifiers al, RDoc::ATTR_MODIFIERS - context.add_alias al if al.document_self - end - - def parse_call_parameters(tk) - end_token = case tk - when TkLPAREN, TkfLPAREN - TkRPAREN - when TkRPAREN - return "" - else - TkNL - end - nest = 0 - - loop do - case tk - when TkSEMICOLON - break - when TkLPAREN, TkfLPAREN - nest += 1 - when end_token - if end_token == TkRPAREN - nest -= 1 - break if @scanner.lex_state == EXPR_END and nest <= 0 - else - break unless @scanner.continue - end - when TkCOMMENT - unget_tk(tk) - break - when nil then - break - end - tk = get_tk - end - res = get_tkread.tr("\n", " ").strip - res = "" if res == ";" - res - end - - def parse_class(container, single, tk, comment) - container, name_t = get_class_or_module container - - case name_t - when TkCONSTANT - name = name_t.name - superclass = "Object" - - if TkLT === peek_tk then - get_tk - skip_tkspace - superclass = get_class_specification - superclass = "" if superclass.empty? - end - - cls_type = single == SINGLE ? RDoc::SingleClass : RDoc::NormalClass - cls = container.add_class cls_type, name, superclass - - read_documentation_modifiers cls, RDoc::CLASS_MODIFIERS - cls.record_location @top_level - cls.comment = comment - - @stats.add_class cls - - parse_statements cls - when TkLSHFT - case name = get_class_specification - when "self", container.name - parse_statements container, SINGLE - else - other = RDoc::TopLevel.find_class_named name - - unless other then - other = container.add_module RDoc::NormalModule, name - other.record_location @top_level - other.comment = comment - end - - @stats.add_class other - - read_documentation_modifiers other, RDoc::CLASS_MODIFIERS - parse_statements(other, SINGLE) - end - - else - warn("Expected class name or '<<'. Got #{name_t.class}: #{name_t.text.inspect}") - end - end - - def parse_constant(container, tk, comment) - name = tk.name - skip_tkspace false - eq_tk = get_tk - - unless TkASSIGN === eq_tk then - unget_tk eq_tk - return - end - - nest = 0 - get_tkread - - tk = get_tk - - if TkGT === tk then - unget_tk tk - unget_tk eq_tk - return - end - - rhs_name = '' - - loop do - case tk - when TkSEMICOLON then - break - when TkLPAREN, TkfLPAREN, TkLBRACE, TkLBRACK, TkDO, TkIF, TkUNLESS, - TkCASE then - nest += 1 - when TkRPAREN, TkRBRACE, TkRBRACK, TkEND then - nest -= 1 - when TkCOMMENT then - if nest <= 0 && @scanner.lex_state == EXPR_END - unget_tk tk - break - end - when TkCONSTANT then - rhs_name << tk.name - - if nest <= 0 and TkNL === peek_tk then - mod = if rhs_name =~ /^::/ then - RDoc::TopLevel.find_class_or_module rhs_name - else - container.find_module_named rhs_name - end - - container.add_module_alias mod, name if mod - get_tk # TkNL - break - end - when TkNL then - if nest <= 0 && - (@scanner.lex_state == EXPR_END || !@scanner.continue) then - unget_tk tk - break - end - when TkCOLON2, TkCOLON3 then - rhs_name << '::' - when nil then - break - end - tk = get_tk - end - - res = get_tkread.tr("\n", " ").strip - res = "" if res == ";" - - con = RDoc::Constant.new name, res, comment - read_documentation_modifiers con, RDoc::CONSTANT_MODIFIERS - - @stats.add_constant con - container.add_constant con if con.document_self - end - - ## - # Generates an RDoc::Method or RDoc::Attr from +comment+ by looking for - # :method: or :attr: directives in +comment+. - - def parse_comment(container, tk, comment) - line_no = tk.line_no - column = tk.char_no - - singleton = !!comment.sub!(/(^# +:?)(singleton-)(method:)/, '\1\3') - - # REFACTOR - if comment.sub!(/^# +:?method: *(\S*).*?\n/i, '') then - name = $1 unless $1.empty? - - meth = RDoc::GhostMethod.new get_tkread, name - meth.singleton = singleton - - meth.start_collecting_tokens - indent = TkSPACE.new nil, 1, 1 - indent.set_text " " * column - - position_comment = TkCOMMENT.new nil, line_no, 1 - position_comment.set_text "# File #{@top_level.absolute_name}, line #{line_no}" - meth.add_tokens [position_comment, NEWLINE_TOKEN, indent] - - meth.params = '' - - extract_call_seq comment, meth - - return unless meth.name - - container.add_method meth if meth.document_self - - meth.comment = comment - - @stats.add_method meth - elsif comment.sub!(/# +:?(attr(_reader|_writer|_accessor)?:) *(\S*).*?\n/i, '') then - rw = case $1 - when 'attr_reader' then 'R' - when 'attr_writer' then 'W' - else 'RW' - end - - name = $3 unless $3.empty? - - att = RDoc::Attr.new get_tkread, name, rw, comment - container.add_attribute att - - @stats.add_method att - end - end - - def parse_include(context, comment) - loop do - skip_tkspace_comment - - name = get_constant_with_optional_parens - context.add_include RDoc::Include.new(name, comment) unless name.empty? - - return unless TkCOMMA === peek_tk - get_tk - end - end - - ## - # Parses a meta-programmed attribute and creates an RDoc::Attr. - # - # To create foo and bar attributes on class C with comment "My attributes": - # - # class C - # - # ## - # # :attr: - # # - # # My attributes - # - # my_attr :foo, :bar - # - # end - # - # To create a foo attribute on class C with comment "My attribute": - # - # class C - # - # ## - # # :attr: foo - # # - # # My attribute - # - # my_attr :foo, :bar - # - # end - - def parse_meta_attr(context, single, tk, comment) - args = parse_symbol_arg - read = get_tkread - rw = "?" - - # If nodoc is given, don't document any of them - - tmp = RDoc::CodeObject.new - read_documentation_modifiers tmp, RDoc::ATTR_MODIFIERS - return unless tmp.document_self - - if comment.sub!(/^# +:?(attr(_reader|_writer|_accessor)?): *(\S*).*?\n/i, '') then - rw = case $1 - when 'attr_reader' then 'R' - when 'attr_writer' then 'W' - else 'RW' - end - name = $3 unless $3.empty? - end - - if name then - att = RDoc::Attr.new get_tkread, name, rw, comment - context.add_attribute att - else - args.each do |attr_name| - att = RDoc::Attr.new get_tkread, attr_name, rw, comment - context.add_attribute att - end - end - end - - ## - # Parses a meta-programmed method - - def parse_meta_method(container, single, tk, comment) - line_no = tk.line_no - column = tk.char_no - - start_collecting_tokens - add_token tk - add_token_listener self - - skip_tkspace false - - singleton = !!comment.sub!(/(^# +:?)(singleton-)(method:)/, '\1\3') - - if comment.sub!(/^# +:?method: *(\S*).*?\n/i, '') then - name = $1 unless $1.empty? - end - - if name.nil? then - name_t = get_tk - case name_t - when TkSYMBOL then - name = name_t.text[1..-1] - when TkSTRING then - name = name_t.value[1..-2] - when TkASSIGN then # ignore - remove_token_listener self - return - else - warn "unknown name token #{name_t.inspect} for meta-method '#{tk.name}'" - name = 'unknown' - end - end - - meth = RDoc::MetaMethod.new get_tkread, name - meth.singleton = singleton - - remove_token_listener self - - meth.start_collecting_tokens - indent = TkSPACE.new nil, 1, 1 - indent.set_text " " * column - - position_comment = TkCOMMENT.new nil, line_no, 1 - position_comment.value = "# File #{@top_level.absolute_name}, line #{line_no}" - meth.add_tokens [position_comment, NEWLINE_TOKEN, indent] - meth.add_tokens @token_stream - - token_listener meth do - meth.params = '' - - extract_call_seq comment, meth - - container.add_method meth if meth.document_self - - last_tk = tk - - while tk = get_tk do - case tk - when TkSEMICOLON then - break - when TkNL then - break unless last_tk and TkCOMMA === last_tk - when TkSPACE then - # expression continues - else - last_tk = tk - end - end - end - - meth.comment = comment - - @stats.add_method meth - end - - ## - # Parses a normal method defined by +def+ - - def parse_method(container, single, tk, comment) - added_container = nil - meth = nil - name = nil - line_no = tk.line_no - column = tk.char_no - - start_collecting_tokens - add_token tk - - token_listener self do - @scanner.instance_eval do @lex_state = EXPR_FNAME end - - skip_tkspace false - name_t = get_tk - back_tk = skip_tkspace - meth = nil - added_container = false - - dot = get_tk - if TkDOT === dot or TkCOLON2 === dot then - @scanner.instance_eval do @lex_state = EXPR_FNAME end - skip_tkspace - name_t2 = get_tk - - case name_t - when TkSELF, TkMOD then - name = name_t2.name - when TkCONSTANT then - name = name_t2.name - prev_container = container - container = container.find_module_named(name_t.name) - unless container then - added_container = true - obj = name_t.name.split("::").inject(Object) do |state, item| - state.const_get(item) - end rescue nil - - type = obj.class == Class ? RDoc::NormalClass : RDoc::NormalModule - - unless [Class, Module].include?(obj.class) then - warn("Couldn't find #{name_t.name}. Assuming it's a module") - end - - if type == RDoc::NormalClass then - sclass = obj.superclass ? obj.superclass.name : nil - container = prev_container.add_class type, name_t.name, sclass - else - container = prev_container.add_module type, name_t.name - end - - container.record_location @top_level - end - when TkIDENTIFIER, TkIVAR then - dummy = RDoc::Context.new - dummy.parent = container - skip_method dummy - return - else - warn "unexpected method name token #{name_t.inspect}" - # break - skip_method container - return - end - - meth = RDoc::AnyMethod.new(get_tkread, name) - meth.singleton = true - else - unget_tk dot - back_tk.reverse_each do |token| - unget_tk token - end - - name = case name_t - when TkSTAR, TkAMPER then - name_t.text - else - unless name_t.respond_to? :name then - warn "expected method name token, . or ::, got #{name_t.inspect}" - skip_method container - return - end - name_t.name - end - - meth = RDoc::AnyMethod.new get_tkread, name - meth.singleton = (single == SINGLE) - end - end - - meth.start_collecting_tokens - indent = TkSPACE.new nil, 1, 1 - indent.set_text " " * column - - token = TkCOMMENT.new nil, line_no, 1 - token.set_text "# File #{@top_level.absolute_name}, line #{line_no}" - meth.add_tokens [token, NEWLINE_TOKEN, indent] - meth.add_tokens @token_stream - - token_listener meth do - @scanner.instance_eval do @continue = false end - parse_method_parameters meth - - if meth.document_self then - container.add_method meth - elsif added_container then - container.document_self = false - end - - # Having now read the method parameters and documentation modifiers, we - # now know whether we have to rename #initialize to ::new - - if name == "initialize" && !meth.singleton then - if meth.dont_rename_initialize then - meth.visibility = :protected - else - meth.singleton = true - meth.name = "new" - meth.visibility = :public - end - end - - parse_statements container, single, meth - end - - extract_call_seq comment, meth - - meth.comment = comment - - @stats.add_method meth - end - - def parse_method_or_yield_parameters(method = nil, - modifiers = RDoc::METHOD_MODIFIERS) - skip_tkspace false - tk = get_tk - - # Little hack going on here. In the statement - # f = 2*(1+yield) - # We see the RPAREN as the next token, so we need - # to exit early. This still won't catch all cases - # (such as "a = yield + 1" - end_token = case tk - when TkLPAREN, TkfLPAREN - TkRPAREN - when TkRPAREN - return "" - else - TkNL - end - nest = 0 - - loop do - case tk - when TkSEMICOLON then - break - when TkLBRACE then - nest += 1 - when TkRBRACE then - # we might have a.each {|i| yield i } - unget_tk(tk) if nest.zero? - nest -= 1 - break if nest <= 0 - when TkLPAREN, TkfLPAREN then - nest += 1 - when end_token then - if end_token == TkRPAREN - nest -= 1 - break if @scanner.lex_state == EXPR_END and nest <= 0 - else - break unless @scanner.continue - end - when method && method.block_params.nil? && TkCOMMENT then - unget_tk tk - read_documentation_modifiers method, modifiers - @read.pop - when TkCOMMENT then - @read.pop - when nil then - break - end - tk = get_tk - end - - res = get_tkread.gsub(/\s+/, ' ').strip - res = '' if res == ';' - res - end - - ## - # Capture the method's parameters. Along the way, look for a comment - # containing: - # - # # yields: .... - # - # and add this as the block_params for the method - - def parse_method_parameters(method) - res = parse_method_or_yield_parameters method - - res = "(#{res})" unless res =~ /\A\(/ - method.params = res unless method.params - - if method.block_params.nil? then - skip_tkspace false - read_documentation_modifiers method, RDoc::METHOD_MODIFIERS - end - end - - def parse_module(container, single, tk, comment) - container, name_t = get_class_or_module container - - name = name_t.name - - mod = container.add_module RDoc::NormalModule, name - mod.record_location @top_level - - read_documentation_modifiers mod, RDoc::CLASS_MODIFIERS - parse_statements(mod) - mod.comment = comment - - @stats.add_module mod - end - - def parse_require(context, comment) - skip_tkspace_comment - tk = get_tk - - if TkLPAREN === tk then - skip_tkspace_comment - tk = get_tk - end - - name = tk.text if TkSTRING === tk - - if name then - context.add_require RDoc::Require.new(name, comment) - else - unget_tk tk - end - end - - ## - # The core of the ruby parser. - - def parse_statements(container, single = NORMAL, current_method = nil, - comment = '') - nest = 1 - save_visibility = container.visibility - - non_comment_seen = true - - while tk = get_tk do - keep_comment = false - - non_comment_seen = true unless TkCOMMENT === tk - - case tk - when TkNL then - skip_tkspace - tk = get_tk - - if TkCOMMENT === tk then - if non_comment_seen then - # Look for RDoc in a comment about to be thrown away - parse_comment container, tk, comment unless comment.empty? - - comment = '' - non_comment_seen = false - end - - while TkCOMMENT === tk do - comment << tk.text << "\n" - - tk = get_tk # this is the newline - skip_tkspace false # leading spaces - tk = get_tk - end - - unless comment.empty? then - look_for_directives_in container, comment - - if container.done_documenting then - container.ongoing_visibility = save_visibility - end - end - - keep_comment = true - else - non_comment_seen = true - end - - unget_tk tk - keep_comment = true - - when TkCLASS then - if container.document_children then - parse_class container, single, tk, comment - else - nest += 1 - end - - when TkMODULE then - if container.document_children then - parse_module container, single, tk, comment - else - nest += 1 - end - - when TkDEF then - if container.document_self then - parse_method container, single, tk, comment - else - nest += 1 - end - - when TkCONSTANT then - if container.document_self then - parse_constant container, tk, comment - end - - when TkALIAS then - if container.document_self and not current_method then - parse_alias container, single, tk, comment - end - - when TkYIELD then - if current_method.nil? then - warn "Warning: yield outside of method" if container.document_self - else - parse_yield container, single, tk, current_method - end - - # Until and While can have a 'do', which shouldn't increase the nesting. - # We can't solve the general case, but we can handle most occurrences by - # ignoring a do at the end of a line. - - when TkUNTIL, TkWHILE then - nest += 1 - skip_optional_do_after_expression - - # 'for' is trickier - when TkFOR then - nest += 1 - skip_for_variable - skip_optional_do_after_expression - - when TkCASE, TkDO, TkIF, TkUNLESS, TkBEGIN then - nest += 1 - - when TkIDENTIFIER then - if nest == 1 and current_method.nil? then - case tk.name - when 'private', 'protected', 'public', 'private_class_method', - 'public_class_method', 'module_function' then - parse_visibility container, single, tk - keep_comment = true - when 'attr' then - parse_attr container, single, tk, comment - when /^attr_(reader|writer|accessor)$/ then - parse_attr_accessor container, single, tk, comment - when 'alias_method' then - parse_alias container, single, tk, comment if - container.document_self - when 'require', 'include' then - # ignore - else - if container.document_self and comment =~ /\A#\#$/ then - case comment - when /^# +:?attr(_reader|_writer|_accessor)?:/ then - parse_meta_attr container, single, tk, comment - else - parse_meta_method container, single, tk, comment - end - end - end - end - - case tk.name - when "require" then - parse_require container, comment - when "include" then - parse_include container, comment - end - - when TkEND then - nest -= 1 - if nest == 0 then - read_documentation_modifiers container, RDoc::CLASS_MODIFIERS - container.ongoing_visibility = save_visibility - - parse_comment container, tk, comment unless comment.empty? - - return - end - end - - comment = '' unless keep_comment - - begin - get_tkread - skip_tkspace false - end while peek_tk == TkNL - end - end - - def parse_symbol_arg(no = nil) - args = [] - skip_tkspace_comment - case tk = get_tk - when TkLPAREN - loop do - skip_tkspace_comment - if tk1 = parse_symbol_in_arg - args.push tk1 - break if no and args.size >= no - end - - skip_tkspace_comment - case tk2 = get_tk - when TkRPAREN - break - when TkCOMMA - else - warn("unexpected token: '#{tk2.inspect}'") if $DEBUG_RDOC - break - end - end - else - unget_tk tk - if tk = parse_symbol_in_arg - args.push tk - return args if no and args.size >= no - end - - loop do - skip_tkspace false - - tk1 = get_tk - unless TkCOMMA === tk1 then - unget_tk tk1 - break - end - - skip_tkspace_comment - if tk = parse_symbol_in_arg - args.push tk - break if no and args.size >= no - end - end - end - args - end - - def parse_symbol_in_arg - case tk = get_tk - when TkSYMBOL - tk.text.sub(/^:/, '') - when TkSTRING - eval @read[-1] - else - warn("Expected symbol or string, got #{tk.inspect}") if $DEBUG_RDOC - nil - end - end - - def parse_top_level_statements(container) - comment = collect_first_comment - look_for_directives_in(container, comment) - container.comment = comment unless comment.empty? - parse_statements container, NORMAL, nil, comment - end - - def parse_visibility(container, single, tk) - singleton = (single == SINGLE) - - vis_type = tk.name - - vis = case vis_type - when 'private' then :private - when 'protected' then :protected - when 'public' then :public - when 'private_class_method' then - singleton = true - :private - when 'public_class_method' then - singleton = true - :public - when 'module_function' then - singleton = true - :public - else - raise RDoc::Error, "Invalid visibility: #{tk.name}" - end - - skip_tkspace_comment false - - case peek_tk - # Ryan Davis suggested the extension to ignore modifiers, because he - # often writes - # - # protected unless $TESTING - # - when TkNL, TkUNLESS_MOD, TkIF_MOD, TkSEMICOLON then - container.ongoing_visibility = vis - else - if vis_type == 'module_function' then - args = parse_symbol_arg - container.set_visibility_for args, :private, false - - module_functions = [] - - container.methods_matching args do |m| - s_m = m.dup - s_m.singleton = true if RDoc::AnyMethod === s_m - s_m.visibility = :public - module_functions << s_m - end - - module_functions.each do |s_m| - case s_m - when RDoc::AnyMethod then - container.add_method s_m - when RDoc::Attr then - container.add_attribute s_m - end - end - else - args = parse_symbol_arg - container.set_visibility_for args, vis, singleton - end - end - end - - def parse_yield(context, single, tk, method) - return if method.block_params - - get_tkread - @scanner.instance_eval { @continue = false } - method.block_params = parse_method_or_yield_parameters - end - - ## - # Directives are modifier comments that can appear after class, module, or - # method names. For example: - # - # def fred # :yields: a, b - # - # or: - # - # class MyClass # :nodoc: - # - # We return the directive name and any parameters as a two element array - - def read_directive(allowed) - tk = get_tk - result = nil - - if TkCOMMENT === tk then - if tk.text =~ /\s*:?(\w+):\s*(.*)/ then - directive = $1.downcase - if allowed.include? directive then - result = [directive, $2] - end - end - else - unget_tk tk - end - - result - end - - def read_documentation_modifiers(context, allow) - dir = read_directive(allow) - - case dir[0] - when "notnew", "not_new", "not-new" then - context.dont_rename_initialize = true - - when "nodoc" then - context.document_self = false - if dir[1].downcase == "all" - context.document_children = false - end - - when "doc" then - context.document_self = true - context.force_documentation = true - - when "yield", "yields" then - unless context.params.nil? - context.params.sub!(/(,|)\s*&\w+/,'') # remove parameter &proc - end - - context.block_params = dir[1] - - when "arg", "args" then - context.params = dir[1] - end if dir - end - - def remove_private_comments(comment) - comment.gsub!(/^#--\n.*?^#\+\+/m, '') - comment.sub!(/^#--\n.*/m, '') - end - - def scan - reset - - catch :eof do - catch :enddoc do - begin - parse_top_level_statements @top_level - rescue StandardError => e - bytes = '' - - 20.times do @scanner.ungetc end - count = 0 - 60.times do |i| - count = i - byte = @scanner.getc - break unless byte - bytes << byte - end - count -= 20 - count.times do @scanner.ungetc end - - $stderr.puts <<-EOF - -#{self.class} failure around line #{@scanner.line_no} of -#{@file_name} - - EOF - - unless bytes.empty? then - $stderr.puts - $stderr.puts bytes.inspect - end - - raise e - end - end - end - - @top_level - end - - ## - # while, until, and for have an optional do - - def skip_optional_do_after_expression - skip_tkspace false - tk = get_tk - case tk - when TkLPAREN, TkfLPAREN then - end_token = TkRPAREN - else - end_token = TkNL - end - - b_nest = 0 - nest = 0 - @scanner.instance_eval { @continue = false } - - loop do - case tk - when TkSEMICOLON then - break if b_nest.zero? - when TkLPAREN, TkfLPAREN then - nest += 1 - when TkBEGIN then - b_nest += 1 - when TkEND then - b_nest -= 1 - when TkDO - break if nest.zero? - when end_token then - if end_token == TkRPAREN - nest -= 1 - break if @scanner.lex_state == EXPR_END and nest.zero? - else - break unless @scanner.continue - end - when nil then - break - end - tk = get_tk - end - - skip_tkspace false - - get_tk if TkDO === peek_tk - end - - ## - # skip the var [in] part of a 'for' statement - - def skip_for_variable - skip_tkspace false - tk = get_tk - skip_tkspace false - tk = get_tk - unget_tk(tk) unless TkIN === tk - end - - def skip_method container - meth = RDoc::AnyMethod.new "", "anon" - parse_method_parameters meth - parse_statements container, false, meth - end - - ## - # Skip spaces until a comment is found - - def skip_tkspace_comment(skip_nl = true) - loop do - skip_tkspace skip_nl - return unless TkCOMMENT === peek_tk - get_tk - end - end - - def warn(msg) - return if @options.quiet - msg = make_message msg - $stderr.puts msg - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/parser/ruby_tools.rb b/Src/StdLib/ruby/1.9.1/rdoc/parser/ruby_tools.rb deleted file mode 100644 index 1866435c9..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/parser/ruby_tools.rb +++ /dev/null @@ -1,157 +0,0 @@ -## -# Collection of methods for writing parsers against RDoc::RubyLex and -# RDoc::RubyToken - -module RDoc::Parser::RubyTools - - include RDoc::RubyToken - - ## - # Adds a token listener +obj+, but you should probably use token_listener - - def add_token_listener(obj) - @token_listeners ||= [] - @token_listeners << obj - end - - ## - # Fetches the next token from the scanner - - def get_tk - tk = nil - - if @tokens.empty? then - tk = @scanner.token - @read.push @scanner.get_readed - puts "get_tk1 => #{tk.inspect}" if $TOKEN_DEBUG - else - @read.push @unget_read.shift - tk = @tokens.shift - puts "get_tk2 => #{tk.inspect}" if $TOKEN_DEBUG - end - - tk = nil if TkEND_OF_SCRIPT === tk - - if TkSYMBEG === tk then - set_token_position tk.line_no, tk.char_no - - case tk1 = get_tk - when TkId, TkOp, TkSTRING, TkDSTRING, TkSTAR, TkAMPER then - if tk1.respond_to?(:name) then - tk = Token(TkSYMBOL).set_text(":" + tk1.name) - else - tk = Token(TkSYMBOL).set_text(":" + tk1.text) - end - - # remove the identifier we just read (we're about to replace it with a - # symbol) - @token_listeners.each do |obj| - obj.pop_token - end if @token_listeners - else - warn("':' not followed by identifier or operator") - tk = tk1 - end - end - - # inform any listeners of our shiny new token - @token_listeners.each do |obj| - obj.add_token(tk) - end if @token_listeners - - tk - end - - def get_tk_until(*tokens) - read = [] - - loop do - tk = get_tk - case tk when *tokens then unget_tk tk; break end - read << tk - end - - read - end - - ## - # Retrieves a String representation of the read tokens - - def get_tkread - read = @read.join("") - @read = [] - read - end - - ## - # Peek equivalent for get_tkread - - def peek_read - @read.join('') - end - - ## - # Peek at the next token, but don't remove it from the stream - - def peek_tk - unget_tk(tk = get_tk) - tk - end - - ## - # Removes the token listener +obj+ - - def remove_token_listener(obj) - @token_listeners.delete(obj) - end - - ## - # Resets the tools - - def reset - @read = [] - @tokens = [] - @unget_read = [] - @nest = 0 - end - - ## - # Skips whitespace tokens including newlines if +skip_nl+ is true - - def skip_tkspace(skip_nl = true) # HACK dup - tokens = [] - - while TkSPACE === (tk = get_tk) or (skip_nl and TkNL === tk) do - tokens.push tk - end - - unget_tk tk - tokens - end - - ## - # Has +obj+ listen to tokens - - def token_listener(obj) - add_token_listener obj - yield - ensure - remove_token_listener obj - end - - ## - # Returns +tk+ to the scanner - - def unget_tk(tk) - @tokens.unshift tk - @unget_read.unshift @read.pop - - # Remove this token from any listeners - @token_listeners.each do |obj| - obj.pop_token - end if @token_listeners - end - -end - - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/parser/simple.rb b/Src/StdLib/ruby/1.9.1/rdoc/parser/simple.rb deleted file mode 100644 index 1c15f9e77..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/parser/simple.rb +++ /dev/null @@ -1,44 +0,0 @@ -## -# Parse a non-source file. We basically take the whole thing as one big -# comment. If the first character in the file is '#', we strip leading pound -# signs. - -class RDoc::Parser::Simple < RDoc::Parser - - parse_files_matching(//) - - attr_reader :content # :nodoc: - - ## - # Prepare to parse a plain file - - def initialize(top_level, file_name, content, options, stats) - super - - preprocess = RDoc::Markup::PreProcess.new @file_name, @options.rdoc_include - - preprocess.handle @content, @top_level - end - - ## - # Extract the file contents and attach them to the TopLevel as a comment - - def scan - comment = remove_coding_comment @content - comment = remove_private_comments comment - - @top_level.comment = comment - @top_level.parser = self.class - @top_level - end - - def remove_private_comments(comment) - comment.gsub(/^--\n.*?^\+\+/m, '').sub(/^--\n.*/m, '') - end - - def remove_coding_comment text - text.sub(/\A# .*coding[=:].*$/, '') - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/rdoc.rb b/Src/StdLib/ruby/1.9.1/rdoc/rdoc.rb deleted file mode 100644 index d5d1a0857..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/rdoc.rb +++ /dev/null @@ -1,457 +0,0 @@ -require 'rdoc' - -require 'rdoc/parser' - -# Simple must come first -require 'rdoc/parser/simple' -require 'rdoc/parser/ruby' -require 'rdoc/parser/c' -require 'rdoc/parser/perl' - -require 'rdoc/stats' -require 'rdoc/options' - -require 'find' -require 'fileutils' -require 'time' - -## -# Encapsulate the production of rdoc documentation. Basically you can use this -# as you would invoke rdoc from the command line: -# -# rdoc = RDoc::RDoc.new -# rdoc.document(args) -# -# Where +args+ is an array of strings, each corresponding to an argument you'd -# give rdoc on the command line. See rdoc/rdoc.rb for details. - -class RDoc::RDoc - - ## - # File pattern to exclude - - attr_accessor :exclude - - ## - # Generator instance used for creating output - - attr_accessor :generator - - ## - # Hash of files and their last modified times. - - attr_reader :last_modified - - ## - # RDoc options - - attr_accessor :options - - ## - # Accessor for statistics. Available after each call to parse_files - - attr_reader :stats - - ## - # This is the list of supported output generators - - GENERATORS = {} - - ## - # Add +klass+ that can generate output after parsing - - def self.add_generator(klass) - name = klass.name.sub(/^RDoc::Generator::/, '').downcase - GENERATORS[name] = klass - end - - ## - # Active RDoc::RDoc instance - - def self.current - @current - end - - ## - # Sets the active RDoc::RDoc instance - - def self.current=(rdoc) - @current = rdoc - end - - def initialize - @current = nil - @exclude = nil - @generator = nil - @last_modified = {} - @old_siginfo = nil - @options = nil - @stats = nil - end - - ## - # Report an error message and exit - - def error(msg) - raise RDoc::Error, msg - end - - ## - # Gathers a set of parseable files from the files and directories listed in - # +files+. - - def gather_files files - files = ["."] if files.empty? - - file_list = normalized_file_list files, true, @exclude - - file_list = file_list.uniq - - file_list = remove_unparseable file_list - end - - ## - # Turns RDoc from stdin into HTML - - def handle_pipe - @html = RDoc::Markup::ToHtml.new - - out = @html.convert $stdin.read - - $stdout.write out - end - - ## - # Installs a siginfo handler that prints the current filename. - - def install_siginfo_handler - return unless Signal.list.include? 'INFO' - - @old_siginfo = trap 'INFO' do - puts @current if @current - end - end - - ## - # Create an output dir if it doesn't exist. If it does exist, but doesn't - # contain the flag file created.rid then we refuse to use it, as - # we may clobber some manually generated documentation - - def setup_output_dir(dir, force) - flag_file = output_flag_file dir - - last = {} - - if File.exist? dir then - error "#{dir} exists and is not a directory" unless File.directory? dir - - begin - open flag_file do |io| - unless force then - Time.parse io.gets - - io.each do |line| - file, time = line.split "\t", 2 - time = Time.parse(time) rescue next - last[file] = time - end - end - end - rescue SystemCallError, TypeError - error <<-ERROR - -Directory #{dir} already exists, but it looks like it isn't an RDoc directory. - -Because RDoc doesn't want to risk destroying any of your existing files, -you'll need to specify a different output directory name (using the --op -option) - - ERROR - end - else - FileUtils.mkdir_p dir - end - - last - end - - ## - # Update the flag file in an output directory. - - def update_output_dir(op_dir, time, last = {}) - open output_flag_file(op_dir), "w" do |f| - f.puts time.rfc2822 - last.each do |n, t| - f.puts "#{n}\t#{t.rfc2822}" - end - end - end - - ## - # Return the path name of the flag file in an output directory. - - def output_flag_file(op_dir) - File.join op_dir, "created.rid" - end - - ## - # The .document file contains a list of file and directory name patterns, - # representing candidates for documentation. It may also contain comments - # (starting with '#') - - def parse_dot_doc_file in_dir, filename - # read and strip comments - patterns = File.read(filename).gsub(/#.*/, '') - - result = [] - - patterns.split.each do |patt| - candidates = Dir.glob(File.join(in_dir, patt)) - result.concat normalized_file_list(candidates) - end - - result - end - - ## - # Given a list of files and directories, create a list of all the Ruby - # files they contain. - # - # If +force_doc+ is true we always add the given files, if false, only - # add files that we guarantee we can parse. It is true when looking at - # files given on the command line, false when recursing through - # subdirectories. - # - # The effect of this is that if you want a file with a non-standard - # extension parsed, you must name it explicitly. - - def normalized_file_list(relative_files, force_doc = false, - exclude_pattern = nil) - file_list = [] - - relative_files.each do |rel_file_name| - next if exclude_pattern && exclude_pattern =~ rel_file_name - stat = File.stat rel_file_name rescue next - - case type = stat.ftype - when "file" then - next if last_modified = @last_modified[rel_file_name] and - stat.mtime.to_i <= last_modified.to_i - - if force_doc or RDoc::Parser.can_parse(rel_file_name) then - file_list << rel_file_name.sub(/^\.\//, '') - @last_modified[rel_file_name] = stat.mtime - end - when "directory" then - next if rel_file_name == "CVS" || rel_file_name == ".svn" - - dot_doc = File.join rel_file_name, RDoc::DOT_DOC_FILENAME - - if File.file? dot_doc then - file_list << parse_dot_doc_file(rel_file_name, dot_doc) - else - file_list << list_files_in_directory(rel_file_name) - end - else - raise RDoc::Error, "I can't deal with a #{type} #{rel_file_name}" - end - end - - file_list.flatten - end - - ## - # Return a list of the files to be processed in a directory. We know that - # this directory doesn't have a .document file, so we're looking for real - # files. However we may well contain subdirectories which must be tested - # for .document files. - - def list_files_in_directory dir - files = Dir.glob File.join(dir, "*") - - normalized_file_list files, false, @options.exclude - end - - ## - # Parses +filename+ and returns an RDoc::TopLevel - - def parse_file filename - @stats.add_file filename - content = read_file_contents filename - - return unless content - - top_level = RDoc::TopLevel.new filename - - parser = RDoc::Parser.for top_level, filename, content, @options, @stats - - return unless parser - - parser.scan - rescue => e - $stderr.puts <<-EOF -Before reporting this, could you check that the file you're documenting -compiles cleanly--RDoc is not a full Ruby parser, and gets confused easily if -fed invalid programs. - -The internal error was: - -\t(#{e.class}) #{e.message} - - EOF - - $stderr.puts e.backtrace.join("\n\t") if $RDOC_DEBUG - - raise e - nil - end - - ## - # Parse each file on the command line, recursively entering directories. - - def parse_files files - file_list = gather_files files - - return [] if file_list.empty? - - file_info = [] - - @stats = RDoc::Stats.new file_list.size, @options.verbosity - @stats.begin_adding - - file_info = file_list.map do |filename| - @current = filename - parse_file filename - end.compact - - @stats.done_adding - - file_info - end - - ## - # Removes file extensions known to be unparseable from +files+ - - def remove_unparseable files - files.reject do |file| - file =~ /\.(?:class|eps|erb|scpt\.txt|ttf|yml)$/i - end - end - - ## - # Format up one or more files according to the given arguments. - # - # For simplicity, +argv+ is an array of strings, equivalent to the strings - # that would be passed on the command line. (This isn't a coincidence, as - # we _do_ pass in ARGV when running interactively). For a list of options, - # see rdoc/rdoc.rb. By default, output will be stored in a directory - # called +doc+ below the current directory, so make sure you're somewhere - # writable before invoking. - # - # Throws: RDoc::Error on error - - def document(argv) - RDoc::TopLevel.reset - RDoc::Parser::C.reset - - @options = RDoc::Options.new - @options.parse argv - - if @options.pipe then - handle_pipe - exit - end - - @exclude = @options.exclude - - @last_modified = setup_output_dir @options.op_dir, @options.force_update - - start_time = Time.now - - file_info = parse_files @options.files - - @options.title = "RDoc Documentation" - - if file_info.empty? - $stderr.puts "\nNo newer files." unless @options.quiet - else - gen_klass = @options.generator - - unless @options.quiet then - $stderr.puts "\nGenerating #{gen_klass.name.sub(/^.*::/, '')}..." - end - - @generator = gen_klass.for @options - - pwd = Dir.pwd - - Dir.chdir @options.op_dir do - begin - self.class.current = self - - @generator.generate file_info - update_output_dir ".", start_time, @last_modified - ensure - self.class.current = nil - end - end - end - - unless @options.quiet or not @stats then - puts - @stats.print - end - end - - def read_file_contents(filename) - content = open filename, "rb" do |f| f.read end - - utf8 = content.sub!(/\A\xef\xbb\xbf/, '') - if defined? Encoding then - if /coding[=:]\s*([^\s;]+)/i =~ content[%r"\A(?:#!.*\n)?.*\n"] - enc = ::Encoding.find($1) - end - if enc ||= (Encoding::UTF_8 if utf8) - content.force_encoding(enc) - end - end - - content - rescue Errno::EISDIR, Errno::ENOENT - nil - end - - ## - # Removes a siginfo handler and replaces the previous - - def remove_siginfo_handler - return unless Signal.list.key? 'INFO' - - handler = @old_siginfo || 'DEFAULT' - - trap 'INFO', handler - end - -end - -begin - require 'rubygems' - - if Gem.respond_to? :find_files then - rdoc_extensions = Gem.find_files 'rdoc/discover' - - rdoc_extensions.each do |extension| - begin - load extension - rescue => e - warn "error loading #{extension.inspect}: #{e.message} (#{e.class})" - end - end - end -rescue LoadError -end - -# require built-in generators after discovery in case they've been replaced -require 'rdoc/generator/darkfish' -require 'rdoc/generator/ri' - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/require.rb b/Src/StdLib/ruby/1.9.1/rdoc/require.rb deleted file mode 100644 index 257127393..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/require.rb +++ /dev/null @@ -1,32 +0,0 @@ -require 'rdoc/code_object' - -## -# A file loaded by \#require - -class RDoc::Require < RDoc::CodeObject - - ## - # Name of the required file - - attr_accessor :name - - ## - # Creates a new Require that loads +name+ with +comment+ - - def initialize(name, comment) - super() - @name = name.gsub(/'|"/, "") #' - self.comment = comment - end - - def inspect # :nodoc: - "#<%s:0x%x require '%s' in %s>" % [ - self.class, - object_id, - @name, - parent_file_name, - ] - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/ri.rb b/Src/StdLib/ruby/1.9.1/rdoc/ri.rb deleted file mode 100644 index 747616fef..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/ri.rb +++ /dev/null @@ -1,18 +0,0 @@ -require 'rdoc' - -## -# Namespace for the ri command line tool's implementation. -# -# See ri --help for details. - -module RDoc::RI - - ## - # Base RI error class - - class Error < RDoc::Error; end - -end - -require 'rdoc/ri/store' - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/ri/driver.rb b/Src/StdLib/ruby/1.9.1/rdoc/ri/driver.rb deleted file mode 100644 index 889ed3cc4..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/ri/driver.rb +++ /dev/null @@ -1,1054 +0,0 @@ -require 'abbrev' -require 'optparse' - -begin - require 'readline' -rescue LoadError -end - -require 'rdoc/ri' -require 'rdoc/ri/paths' -require 'rdoc/markup' -require 'rdoc/markup/formatter' -require 'rdoc/text' - -## -# For RubyGems backwards compatibility - -require 'rdoc/ri/formatter' - -## -# The RI driver implements the command-line ri tool. -# -# The driver supports: -# * loading RI data from: -# * Ruby's standard library -# * RubyGems -# * ~/.rdoc -# * A user-supplied directory -# * Paging output (uses RI_PAGER environment variable, PAGER environment -# variable or the less, more and pager programs) -# * Interactive mode with tab-completion -# * Abbreviated names (ri Zl shows Zlib documentation) -# * Colorized output -# * Merging output from multiple RI data sources - -class RDoc::RI::Driver - - ## - # Base Driver error class - - class Error < RDoc::RI::Error; end - - ## - # Raised when a name isn't found in the ri data stores - - class NotFoundError < Error - - ## - # Name that wasn't found - - alias name message - - def message # :nodoc: - "Nothing known about #{super}" - end - end - - attr_accessor :stores - - ## - # Controls the user of the pager vs $stdout - - attr_accessor :use_stdout - - ## - # Default options for ri - - def self.default_options - options = {} - options[:use_stdout] = !$stdout.tty? - options[:width] = 72 - options[:interactive] = false - options[:use_cache] = true - options[:profile] = false - - # By default all standard paths are used. - options[:use_system] = true - options[:use_site] = true - options[:use_home] = true - options[:use_gems] = true - options[:extra_doc_dirs] = [] - - return options - end - - ## - # Dump +data_path+ using pp - - def self.dump data_path - require 'pp' - - open data_path, 'rb' do |io| - pp Marshal.load(io.read) - end - end - - ## - # Parses +argv+ and returns a Hash of options - - def self.process_args argv - options = default_options - - opts = OptionParser.new do |opt| - opt.accept File do |file,| - File.readable?(file) and not File.directory?(file) and file - end - - opt.program_name = File.basename $0 - opt.version = RDoc::VERSION - opt.release = nil - opt.summary_indent = ' ' * 4 - - opt.banner = <<-EOT -Usage: #{opt.program_name} [options] [names...] - -Where name can be: - - Class | Class::method | Class#method | Class.method | method - -All class names may be abbreviated to their minimum unambiguous form. If a name -is ambiguous, all valid options will be listed. - -The form '.' method matches either class or instance methods, while #method -matches only instance and ::method matches only class methods. - -For example: - - #{opt.program_name} Fil - #{opt.program_name} File - #{opt.program_name} File.new - #{opt.program_name} zip - -Note that shell quoting may be required for method names containing -punctuation: - - #{opt.program_name} 'Array.[]' - #{opt.program_name} compact\\! - -To see the default directories ri will search, run: - - #{opt.program_name} --list-doc-dirs - -Specifying the --system, --site, --home, --gems or --doc-dir options will -limit ri to searching only the specified directories. - -Options may also be set in the 'RI' environment variable. - EOT - - opt.separator nil - opt.separator "Options:" - - opt.separator nil - - formatters = RDoc::Markup.constants.grep(/^To[A-Z][a-z]+$/).sort - formatters = formatters.sort.map do |formatter| - formatter.to_s.sub('To', '').downcase - end - - opt.on("--format=NAME", "-f", - "Uses the selected formatter. The default", - "formatter is bs for paged output and ansi", - "otherwise. Valid formatters are:", - formatters.join(' '), formatters) do |value| - options[:formatter] = RDoc::Markup.const_get "To#{value.capitalize}" - end - - opt.separator nil - - opt.on("--no-pager", "-T", - "Send output directly to stdout,", - "rather than to a pager.") do - options[:use_stdout] = true - end - - opt.separator nil - - opt.on("--width=WIDTH", "-w", OptionParser::DecimalInteger, - "Set the width of the output.") do |value| - options[:width] = value - end - - opt.separator nil - - opt.on("--interactive", "-i", - "In interactive mode you can repeatedly", - "look up methods with autocomplete.") do - options[:interactive] = true - end - - opt.separator nil - - opt.on("--[no-]profile", - "Run with the ruby profiler") do |value| - options[:profile] = value - end - - opt.separator nil - opt.separator "Data source options:" - opt.separator nil - - opt.on("--list-doc-dirs", - "List the directories from which ri will", - "source documentation on stdout and exit.") do - options[:list_doc_dirs] = true - end - - opt.separator nil - - opt.on("--doc-dir=DIRNAME", "-d", Array, - "List of directories from which to source", - "documentation in addition to the standard", - "directories. May be repeated.") do |value| - value.each do |dir| - unless File.directory? dir then - raise OptionParser::InvalidArgument, "#{dir} is not a directory" - end - - options[:extra_doc_dirs] << File.expand_path(dir) - end - end - - opt.separator nil - - opt.on("--no-standard-docs", - "Do not include documentation from", - "the Ruby standard library, site_lib,", - "installed gems, or ~/.rdoc.", - "Use with --doc-dir") do - options[:use_system] = false - options[:use_site] = false - options[:use_gems] = false - options[:use_home] = false - end - - opt.separator nil - - opt.on("--[no-]system", - "Include documentation from Ruby's standard", - "library. Defaults to true.") do |value| - options[:use_system] = value - end - - opt.separator nil - - opt.on("--[no-]site", - "Include documentation from libraries", - "installed in site_lib.", - "Defaults to true.") do |value| - options[:use_site] = value - end - - opt.separator nil - - opt.on("--[no-]gems", - "Include documentation from RubyGems.", - "Defaults to true.") do |value| - options[:use_gems] = value - end - - opt.separator nil - - opt.on("--[no-]home", - "Include documentation stored in ~/.rdoc.", - "Defaults to true.") do |value| - options[:use_home] = value - end - - opt.separator nil - opt.separator "Debug options:" - opt.separator nil - - opt.on("--dump=CACHE", File, - "Dumps data from an ri cache or data file") do |value| - options[:dump_path] = value - end - end - - argv = ENV['RI'].to_s.split.concat argv - - opts.parse! argv - - options[:names] = argv - - options[:use_stdout] ||= !$stdout.tty? - options[:use_stdout] ||= options[:interactive] - options[:width] ||= 72 - - options - - rescue OptionParser::InvalidArgument, OptionParser::InvalidOption => e - puts opts - puts - puts e - exit 1 - end - - ## - # Runs the ri command line executable using +argv+ - - def self.run argv = ARGV - options = process_args argv - - if options[:dump_path] then - dump options[:dump_path] - return - end - - ri = new options - ri.run - end - - ## - # Creates a new driver using +initial_options+ from ::process_args - - def initialize initial_options = {} - @paging = false - @classes = nil - - options = self.class.default_options.update(initial_options) - - @formatter_klass = options[:formatter] - - require 'profile' if options[:profile] - - @names = options[:names] - - @doc_dirs = [] - @stores = [] - - RDoc::RI::Paths.each(options[:use_system], options[:use_site], - options[:use_home], options[:use_gems], - *options[:extra_doc_dirs]) do |path, type| - @doc_dirs << path - - store = RDoc::RI::Store.new path, type - store.load_cache - @stores << store - end - - @list_doc_dirs = options[:list_doc_dirs] - - @interactive = options[:interactive] - @use_stdout = options[:use_stdout] - end - - ## - # Adds paths for undocumented classes +also_in+ to +out+ - - def add_also_in out, also_in - return if also_in.empty? - - out << RDoc::Markup::Rule.new(1) - out << RDoc::Markup::Paragraph.new("Also found in:") - - paths = RDoc::Markup::Verbatim.new - also_in.each do |store| - paths.parts.push ' ', store.friendly_path, "\n" - end - out << paths - end - - ## - # Adds a class header to +out+ for class +name+ which is described in - # +classes+. - - def add_class out, name, classes - heading = if classes.all? { |klass| klass.module? } then - name - else - superclass = classes.map do |klass| - klass.superclass unless klass.module? - end.compact.shift || 'Object' - - "#{name} < #{superclass}" - end - - out << RDoc::Markup::Heading.new(1, heading) - out << RDoc::Markup::BlankLine.new - end - - ## - # Adds "(from ...)" to +out+ for +store+ - - def add_from out, store - out << RDoc::Markup::Paragraph.new("(from #{store.friendly_path})") - end - - ## - # Adds +includes+ to +out+ - - def add_includes out, includes - return if includes.empty? - - out << RDoc::Markup::Rule.new(1) - out << RDoc::Markup::Heading.new(1, "Includes:") - - includes.each do |modules, store| - if modules.length == 1 then - include = modules.first - name = include.name - path = store.friendly_path - out << RDoc::Markup::Paragraph.new("#{name} (from #{path})") - - if include.comment then - out << RDoc::Markup::BlankLine.new - out << include.comment - end - else - out << RDoc::Markup::Paragraph.new("(from #{store.friendly_path})") - - wout, with = modules.partition { |incl| incl.comment.empty? } - - out << RDoc::Markup::BlankLine.new unless with.empty? - - with.each do |incl| - out << RDoc::Markup::Paragraph.new(incl.name) - out << RDoc::Markup::BlankLine.new - out << incl.comment - end - - unless wout.empty? then - verb = RDoc::Markup::Verbatim.new - - wout.each do |incl| - verb.push ' ', incl.name, "\n" - end - - out << verb - end - end - end - end - - ## - # Adds a list of +methods+ to +out+ with a heading of +name+ - - def add_method_list out, methods, name - return unless methods - - out << RDoc::Markup::Heading.new(1, "#{name}:") - out << RDoc::Markup::BlankLine.new - - out.push(*methods.map do |method| - RDoc::Markup::Verbatim.new ' ', method - end) - - out << RDoc::Markup::BlankLine.new - end - - ## - # Returns ancestor classes of +klass+ - - def ancestors_of klass - ancestors = [] - - unexamined = [klass] - seen = [] - - loop do - break if unexamined.empty? - current = unexamined.shift - seen << current - - stores = classes[current] - - break unless stores and not stores.empty? - - klasses = stores.map do |store| - store.ancestors[current] - end.flatten.uniq - - klasses = klasses - seen - - ancestors.push(*klasses) - unexamined.push(*klasses) - end - - ancestors.reverse - end - - ## - # For RubyGems backwards compatibility - - def class_cache # :nodoc: - end - - ## - # Hash mapping a known class or module to the stores it can be loaded from - - def classes - return @classes if @classes - - @classes = {} - - @stores.each do |store| - store.cache[:modules].each do |mod| - # using default block causes searched-for modules to be added - @classes[mod] ||= [] - @classes[mod] << store - end - end - - @classes - end - - ## - # Completes +name+ based on the caches. For Readline - - def complete name - klasses = classes.keys - completions = [] - - klass, selector, method = parse_name name - - # may need to include Foo when given Foo:: - klass_name = method ? name : klass - - if name !~ /#|\./ then - completions.push(*klasses.grep(/^#{klass_name}/)) - elsif selector then - completions << klass if classes.key? klass - elsif classes.key? klass_name then - completions << klass_name - end - - if completions.include? klass and name =~ /#|\.|::/ then - methods = list_methods_matching name - - if not methods.empty? then - # remove Foo if given Foo:: and a method was found - completions.delete klass - elsif selector then - # replace Foo with Foo:: as given - completions.delete klass - completions << "#{klass}#{selector}" - end - - completions.push(*methods) - end - - completions.sort - end - - ## - # Converts +document+ to text and writes it to the pager - - def display document - page do |io| - text = document.accept formatter(io) - - io.write text - end - end - - ## - # Outputs formatted RI data for class +name+. Groups undocumented classes - - def display_class name - return if name =~ /#|\./ - - klasses = [] - includes = [] - - found = @stores.map do |store| - begin - klass = store.load_class name - klasses << klass - includes << [klass.includes, store] if klass.includes - [store, klass] - rescue Errno::ENOENT - end - end.compact - - return if found.empty? - - also_in = [] - - includes.reject! do |modules,| modules.empty? end - - out = RDoc::Markup::Document.new - - add_class out, name, klasses - - add_includes out, includes - - found.each do |store, klass| - comment = klass.comment - class_methods = store.class_methods[klass.full_name] - instance_methods = store.instance_methods[klass.full_name] - attributes = store.attributes[klass.full_name] - - if comment.empty? and !(instance_methods or class_methods) then - also_in << store - next - end - - add_from out, store - - unless comment.empty? then - out << RDoc::Markup::Rule.new(1) - out << comment - end - - if class_methods or instance_methods or not klass.constants.empty? then - out << RDoc::Markup::Rule.new - end - - unless klass.constants.empty? then - out << RDoc::Markup::Heading.new(1, "Constants:") - out << RDoc::Markup::BlankLine.new - list = RDoc::Markup::List.new :NOTE - - constants = klass.constants.sort_by { |constant| constant.name } - - list.push(*constants.map do |constant| - parts = constant.comment.parts if constant.comment - parts << RDoc::Markup::Paragraph.new('[not documented]') if - parts.empty? - - RDoc::Markup::ListItem.new(constant.name, *parts) - end) - - out << list - end - - add_method_list out, class_methods, 'Class methods' - add_method_list out, instance_methods, 'Instance methods' - add_method_list out, attributes, 'Attributes' - - out << RDoc::Markup::BlankLine.new - end - - add_also_in out, also_in - - display out - end - - ## - # Outputs formatted RI data for method +name+ - - def display_method name - found = load_methods_matching name - - raise NotFoundError, name if found.empty? - - out = RDoc::Markup::Document.new - - out << RDoc::Markup::Heading.new(1, name) - out << RDoc::Markup::BlankLine.new - - found.each do |store, methods| - methods.each do |method| - out << RDoc::Markup::Paragraph.new("(from #{store.friendly_path})") - - unless name =~ /^#{Regexp.escape method.parent_name}/ then - out << RDoc::Markup::Heading.new(3, "Implementation from #{method.parent_name}") - end - out << RDoc::Markup::Rule.new(1) - - if method.arglists then - arglists = method.arglists.chomp.split "\n" - arglists = arglists.map { |line| [' ', line, "\n"] } - out << RDoc::Markup::Verbatim.new(*arglists.flatten) - out << RDoc::Markup::Rule.new(1) - end - - out << RDoc::Markup::BlankLine.new - out << method.comment - out << RDoc::Markup::BlankLine.new - end - end - - display out - end - - ## - # Outputs formatted RI data for the class or method +name+. - # - # Returns true if +name+ was found, false if it was not an alternative could - # be guessed, raises an error if +name+ couldn't be guessed. - - def display_name name - return true if display_class name - - display_method name if name =~ /::|#|\./ - - true - rescue NotFoundError - matches = list_methods_matching name if name =~ /::|#|\./ - matches = classes.keys.grep(/^#{name}/) if matches.empty? - - raise if matches.empty? - - page do |io| - io.puts "#{name} not found, maybe you meant:" - io.puts - io.puts matches.join("\n") - end - - false - end - - ## - # Displays each name in +name+ - - def display_names names - names.each do |name| - name = expand_name name - - display_name name - end - end - ## - # Expands abbreviated klass +klass+ into a fully-qualified class. "Zl::Da" - # will be expanded to Zlib::DataError. - - def expand_class klass - klass.split('::').inject '' do |expanded, klass_part| - expanded << '::' unless expanded.empty? - short = expanded << klass_part - - subset = classes.keys.select do |klass_name| - klass_name =~ /^#{expanded}[^:]*$/ - end - - abbrevs = Abbrev.abbrev subset - - expanded = abbrevs[short] - - raise NotFoundError, short unless expanded - - expanded.dup - end - end - - ## - # Expands the class portion of +name+ into a fully-qualified class. See - # #expand_class. - - def expand_name name - klass, selector, method = parse_name name - - return [selector, method].join if klass.empty? - - "#{expand_class klass}#{selector}#{method}" - end - - ## - # Yields items matching +name+ including the store they were found in, the - # class being searched for, the class they were found in (an ancestor) the - # types of methods to look up (from #method_type), and the method name being - # searched for - - def find_methods name - klass, selector, method = parse_name name - - types = method_type selector - - klasses = nil - ambiguous = klass.empty? - - if ambiguous then - klasses = classes.keys - else - klasses = ancestors_of klass - klasses.unshift klass - end - - methods = [] - - klasses.each do |ancestor| - ancestors = classes[ancestor] - - next unless ancestors - - klass = ancestor if ambiguous - - ancestors.each do |store| - methods << [store, klass, ancestor, types, method] - end - end - - methods = methods.sort_by do |_, k, a, _, m| - [k, a, m].compact - end - - methods.each do |item| - yield(*item) # :yields: store, klass, ancestor, types, method - end - - self - end - - ## - # Creates a new RDoc::Markup::Formatter. If a formatter is given with -f, - # use it. If we're outputting to a pager, use bs, otherwise ansi. - - def formatter(io) - if @formatter_klass then - @formatter_klass.new - elsif paging? or !io.tty? then - RDoc::Markup::ToBs.new - else - RDoc::Markup::ToAnsi.new - end - end - - ## - # Runs ri interactively using Readline if it is available. - - def interactive - puts "\nEnter the method name you want to look up." - - if defined? Readline then - Readline.completion_proc = method :complete - puts "You can use tab to autocomplete." - end - - puts "Enter a blank line to exit.\n\n" - - loop do - name = if defined? Readline then - Readline.readline ">> " - else - print ">> " - $stdin.gets - end - - return if name.nil? or name.empty? - - name = expand_name name.strip - - begin - display_name name - rescue NotFoundError => e - puts e.message - end - end - - rescue Interrupt - exit - end - - ## - # Lists classes known to ri - - def list_known_classes - classes = [] - - stores.each do |store| - classes << store.modules - end - - classes = classes.flatten.uniq.sort - - page do |io| - if paging? or io.tty? then - io.puts "Classes and Modules known to ri:" - io.puts - end - - io.puts classes.join("\n") - end - end - - ## - # Returns an Array of methods matching +name+ - - def list_methods_matching name - found = [] - - find_methods name do |store, klass, ancestor, types, method| - if types == :instance or types == :both then - methods = store.instance_methods[ancestor] - - if methods then - matches = methods.grep(/^#{method}/) - - matches = matches.map do |match| - "#{klass}##{match}" - end - - found.push(*matches) - end - end - - if types == :class or types == :both then - methods = store.class_methods[ancestor] - - next unless methods - matches = methods.grep(/^#{method}/) - - matches = matches.map do |match| - "#{klass}::#{match}" - end - - found.push(*matches) - end - end - - found.uniq - end - - ## - # Loads RI data for method +name+ on +klass+ from +store+. +type+ and - # +cache+ indicate if it is a class or instance method. - - def load_method store, cache, klass, type, name - methods = store.send(cache)[klass] - - return unless methods - - method = methods.find do |method_name| - method_name == name - end - - return unless method - - store.load_method klass, "#{type}#{method}" - end - - ## - # Returns an Array of RI data for methods matching +name+ - - def load_methods_matching name - found = [] - - find_methods name do |store, klass, ancestor, types, method| - methods = [] - - methods << load_method(store, :class_methods, ancestor, '::', method) if - types == :class or types == :both - - methods << load_method(store, :instance_methods, ancestor, '#', method) if - types == :instance or types == :both - - found << [store, methods.compact] - end - - found.reject do |path, methods| methods.empty? end - end - - ## - # Returns the type of method (:both, :instance, :class) for +selector+ - - def method_type selector - case selector - when '.', nil then :both - when '#' then :instance - else :class - end - end - - ## - # Paginates output through a pager program. - - def page - if pager = setup_pager then - begin - yield pager - ensure - pager.close - end - else - yield $stdout - end - rescue Errno::EPIPE - ensure - @paging = false - end - - ## - # Are we using a pager? - - def paging? - @paging - end - - ## - # Extract the class, selector and method name parts from +name+ like - # Foo::Bar#baz. - # - # NOTE: Given Foo::Bar, Bar is considered a class even though it may be a - # method - - def parse_name(name) - parts = name.split(/(::|#|\.)/) - - if parts.length == 1 then - if parts.first =~ /^[a-z]/ then - type = '.' - meth = parts.pop - else - type = nil - meth = nil - end - elsif parts.length == 2 or parts.last =~ /::|#|\./ then - type = parts.pop - meth = nil - elsif parts[-2] != '::' or parts.last !~ /^[A-Z]/ then - meth = parts.pop - type = parts.pop - end - - klass = parts.join - - [klass, type, meth] - end - - ## - # Looks up and displays ri data according to the options given. - - def run - if @list_doc_dirs then - puts @doc_dirs - elsif @interactive then - interactive - elsif @names.empty? then - list_known_classes - else - display_names @names - end - rescue NotFoundError => e - abort e.message - end - - ## - # Sets up a pager program to pass output through. Tries the RI_PAGER and - # PAGER environment variables followed by pager, less then more. - - def setup_pager - return if @use_stdout - - pagers = [ENV['RI_PAGER'], ENV['PAGER'], 'pager', 'less', 'more'] - - pagers.compact.uniq.each do |pager| - next unless File.exist? pager - - io = IO.popen pager, "w" rescue next - - next if $? and $?.exited? # pager didn't work - - @paging = true - - return io - end - - @use_stdout = true - - nil - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/ri/formatter.rb b/Src/StdLib/ruby/1.9.1/rdoc/ri/formatter.rb deleted file mode 100644 index 3ff4db95b..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/ri/formatter.rb +++ /dev/null @@ -1,5 +0,0 @@ -## -# For RubyGems backwards compatibility - -module RDoc::RI::Formatter # :nodoc: -end diff --git a/Src/StdLib/ruby/1.9.1/rdoc/ri/paths.rb b/Src/StdLib/ruby/1.9.1/rdoc/ri/paths.rb deleted file mode 100644 index ba9125b24..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/ri/paths.rb +++ /dev/null @@ -1,112 +0,0 @@ -require 'rdoc/ri' - -## -# The directories where ri data lives. - -module RDoc::RI::Paths - - #:stopdoc: - require 'rbconfig' - - version = RbConfig::CONFIG['ruby_version'] - - base = File.join RbConfig::CONFIG['ridir'], version - SYSDIR = File.join base, "system" - SITEDIR = File.join base, "site" - HOMEDIR = (File.expand_path('~/.rdoc') rescue nil) - #:startdoc: - - @gemdirs = nil - - ## - # Iterates over each selected path yielding the directory and type. - # - # Yielded types: - # :system:: Where Ruby's ri data is stored. Yielded when +system+ is - # true - # :site:: Where ri for installed libraries are stored. Yielded when - # +site+ is true. Normally no ri data is stored here. - # :home:: ~/.ri. Yielded when +home+ is true. - # :gem:: ri data for an installed gem. Yielded when +gems+ is true. - # :extra:: ri data directory from the command line. Yielded for each - # entry in +extra_dirs+ - - def self.each system, site, home, gems, *extra_dirs # :yields: directory, type - extra_dirs.each do |dir| - yield dir, :extra - end - - yield SYSDIR, :system if system - yield SITEDIR, :site if site - yield HOMEDIR, :home if home - - gemdirs.each do |dir| - yield dir, :gem - end if gems - - nil - end - - ## - # The latest installed gems' ri directories - - def self.gemdirs - return @gemdirs if @gemdirs - - require 'rubygems' unless defined?(Gem) - - # HACK dup'd from Gem.latest_partials and friends - all_paths = [] - - all_paths = Gem.path.map do |dir| - Dir[File.join(dir, 'doc', '*', 'ri')] - end.flatten - - ri_paths = {} - - all_paths.each do |dir| - base = File.basename File.dirname(dir) - if base =~ /(.*)-((\d+\.)*\d+)/ then - name, version = $1, $2 - ver = Gem::Version.new version - if ri_paths[name].nil? or ver > ri_paths[name][0] then - ri_paths[name] = [ver, dir] - end - end - end - - @gemdirs = ri_paths.map { |k,v| v.last }.sort - rescue LoadError - @gemdirs = [] - end - - ## - # Returns existing directories from the selected documentation directories - # as an Array. - # - # See also ::each - - def self.path(system, site, home, gems, *extra_dirs) - path = raw_path system, site, home, gems, *extra_dirs - - path.select { |directory| File.directory? directory } - end - - ## - # Returns selected documentation directories including nonexistent - # directories. - # - # See also ::each - - def self.raw_path(system, site, home, gems, *extra_dirs) - path = [] - - each(system, site, home, gems, *extra_dirs) do |dir, type| - path << dir - end - - path.compact - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/ri/store.rb b/Src/StdLib/ruby/1.9.1/rdoc/ri/store.rb deleted file mode 100644 index f3899bf97..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/ri/store.rb +++ /dev/null @@ -1,248 +0,0 @@ -require 'rdoc/code_objects' -require 'fileutils' - -## -# A set of ri data. -# -# The store manages reading and writing ri data for a project (gem, path, -# etc.) and maintains a cache of methods, classes and ancestors in the -# store. - -class RDoc::RI::Store - - ## - # Path this store reads or writes - - attr_accessor :path - - ## - # Type of ri datastore this was loaded from. See RDoc::RI::Driver, - # RDoc::RI::Paths. - - attr_accessor :type - - attr_reader :cache - - ## - # Creates a new Store of +type+ that will load or save to +path+ - - def initialize path, type = nil - @type = type - @path = path - - @cache = { - :class_methods => {}, - :instance_methods => {}, - :attributes => {}, - :modules => [], - :ancestors => {}, - } - end - - ## - # Ancestors cache accessor. Maps a klass name to an Array of its ancestors - # in this store. If Foo in this store inherits from Object, Kernel won't be - # listed (it will be included from ruby's ri store). - - def ancestors - @cache[:ancestors] - end - - ## - # Attributes cache accessor. Maps a class to an Array of its attributes. - - def attributes - @cache[:attributes] - end - - ## - # Path to the cache file - - def cache_path - File.join @path, 'cache.ri' - end - - ## - # Path to the ri data for +klass_name+ - - def class_file klass_name - name = klass_name.split('::').last - File.join class_path(klass_name), "cdesc-#{name}.ri" - end - - ## - # Class methods cache accessor. Maps a class to an Array of its class - # methods (not full name). - - def class_methods - @cache[:class_methods] - end - - ## - # Path where data for +klass_name+ will be stored (methods or class data) - - def class_path klass_name - File.join @path, *klass_name.split('::') - end - - ## - # Friendly rendition of #path - - def friendly_path - case type - when :gem then - sep = Regexp.union(*['/', File::ALT_SEPARATOR].compact) - @path =~ /#{sep}doc#{sep}(.*?)#{sep}ri$/ - "gem #{$1}" - when :home then '~/.ri' - when :site then 'ruby site' - when :system then 'ruby core' - else @path - end - end - - def inspect # :nodoc: - "#<%s:0x%x %s %p>" % [self.class, object_id, @path, modules.sort] - end - - ## - # Instance methods cache accessor. Maps a class to an Array of its - # instance methods (not full name). - - def instance_methods - @cache[:instance_methods] - end - - ## - # Loads cache file for this store - - def load_cache - open cache_path, 'rb' do |io| - @cache = Marshal.load io.read - end - rescue Errno::ENOENT - end - - ## - # Loads ri data for +klass_name+ - - def load_class klass_name - open class_file(klass_name), 'rb' do |io| - Marshal.load io.read - end - end - - ## - # Loads ri data for +method_name+ in +klass_name+ - - def load_method klass_name, method_name - open method_file(klass_name, method_name), 'rb' do |io| - Marshal.load io.read - end - end - - ## - # Path to the ri data for +method_name+ in +klass_name+ - - def method_file klass_name, method_name - method_name = method_name.split('::').last - method_name =~ /#(.*)/ - method_type = $1 ? 'i' : 'c' - method_name = $1 if $1 - - method_name = if ''.respond_to? :ord then - method_name.gsub(/\W/) { "%%%02x" % $&[0].ord } - else - method_name.gsub(/\W/) { "%%%02x" % $&[0] } - end - - File.join class_path(klass_name), "#{method_name}-#{method_type}.ri" - end - - ## - # Modules cache accessor. An Array of all the modules (and classes) in the - # store. - - def modules - @cache[:modules] - end - - ## - # Writes the cache file for this store - - def save_cache - # HACK mongrel-1.1.5 documents its files twice - @cache[:attributes]. each do |_, m| m.uniq!; m.sort! end - @cache[:class_methods]. each do |_, m| m.uniq!; m.sort! end - @cache[:instance_methods].each do |_, m| m.uniq!; m.sort! end - - open cache_path, 'wb' do |io| - Marshal.dump @cache, io - end - end - - ## - # Writes the ri data for +klass+ - - def save_class klass - FileUtils.mkdir_p class_path(klass.full_name) - - @cache[:modules] << klass.full_name - - path = class_file klass.full_name - - begin - disk_klass = nil - - open path, 'rb' do |io| - disk_klass = Marshal.load io.read - end - - klass.merge disk_klass - rescue Errno::ENOENT - end - - # BasicObject has no ancestors - ancestors = klass.ancestors.compact.map do |ancestor| - # HACK for classes we don't know about (class X < RuntimeError) - String === ancestor ? ancestor : ancestor.full_name - end - - @cache[:ancestors][klass.full_name] ||= [] - @cache[:ancestors][klass.full_name].push(*ancestors) - - attributes = klass.attributes.map do |attribute| - "#{attribute.type} #{attribute.name}" - end - - unless attributes.empty? then - @cache[:attributes][klass.full_name] ||= [] - @cache[:attributes][klass.full_name].push(*attributes) - end - - open path, 'wb' do |io| - Marshal.dump klass, io - end - end - - ## - # Writes the ri data for +method+ on +klass+ - - def save_method klass, method - FileUtils.mkdir_p class_path(klass.full_name) - - cache = if method.singleton then - @cache[:class_methods] - else - @cache[:instance_methods] - end - cache[klass.full_name] ||= [] - cache[klass.full_name] << method.name - - open method_file(klass.full_name, method.full_name), 'wb' do |io| - Marshal.dump method, io - end - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/ruby_lex.rb b/Src/StdLib/ruby/1.9.1/rdoc/ruby_lex.rb deleted file mode 100644 index 1a30cb67c..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/ruby_lex.rb +++ /dev/null @@ -1,1292 +0,0 @@ -#-- -# irb/ruby-lex.rb - ruby lexcal analyzer -# $Release Version: 0.9.5$ -# $Revision: 17979 $ -# $Date: 2008-07-09 10:17:05 -0700 (Wed, 09 Jul 2008) $ -# by Keiju ISHITSUKA(keiju@ruby-lang.org) -# -#++ - -require "e2mmap" -require "irb/slex" -require "rdoc/ruby_token" -require "stringio" - -## -# Ruby lexer adapted from irb. -# -# The internals are not documented because they are scary. - -class RDoc::RubyLex - - # :stopdoc: - - extend Exception2MessageMapper - - def_exception(:AlreadyDefinedToken, "Already defined token(%s)") - def_exception(:TkReading2TokenNoKey, "key nothing(key='%s')") - def_exception(:TkSymbol2TokenNoKey, "key nothing(key='%s')") - def_exception(:TkReading2TokenDuplicateError, - "key duplicate(token_n='%s', key='%s')") - def_exception(:SyntaxError, "%s") - - def_exception(:TerminateLineInput, "Terminate Line Input") - - include RDoc::RubyToken - include IRB - - attr_reader :continue - attr_reader :lex_state - attr_reader :reader - - class << self - attr_accessor :debug_level - end - - def self.debug? - @debug_level > 0 - end - - self.debug_level = 0 - - def initialize(content, options) - lex_init - - if /\t/ =~ content then - tab_width = options.tab_width - content = content.split(/\n/).map do |line| - 1 while line.gsub!(/\t+/) { - ' ' * (tab_width*$&.length - $`.length % tab_width) - } && $~ - line - end.join("\n") - end - - content << "\n" unless content[-1, 1] == "\n" - - set_input StringIO.new content - - @base_char_no = 0 - @char_no = 0 - @exp_line_no = @line_no = 1 - @here_readed = [] - @readed = [] - @rests = [] - @seek = 0 - - @here_header = false - @indent = 0 - @indent_stack = [] - @lex_state = EXPR_BEG - @space_seen = false - - @continue = false - @line = "" - - @skip_space = false - @readed_auto_clean_up = false - @exception_on_syntax_error = true - - @prompt = nil - @prev_seek = nil - end - - def inspect # :nodoc: - "#<%s:0x%x lex_state %p space_seen %p>" % [ - self.class, object_id, - @lex_state, @space_seen, - ] - end - - attr_accessor :skip_space - attr_accessor :readed_auto_clean_up - attr_accessor :exception_on_syntax_error - - attr_reader :seek - attr_reader :char_no - attr_reader :line_no - attr_reader :indent - - # io functions - def set_input(io, p = nil, &block) - @io = io - if p.respond_to?(:call) - @input = p - elsif block_given? - @input = block - else - @input = Proc.new{@io.gets} - end - end - - def get_readed - if idx = @readed.reverse.index("\n") - @base_char_no = idx - else - @base_char_no += @readed.size - end - - readed = @readed.join("") - @readed = [] - readed - end - - def getc - while @rests.empty? - # return nil unless buf_input - @rests.push nil unless buf_input - end - c = @rests.shift - if @here_header - @here_readed.push c - else - @readed.push c - end - @seek += 1 - if c == "\n" - @line_no += 1 - @char_no = 0 - else - @char_no += 1 - end - c - end - - def gets - l = "" - while c = getc - l.concat(c) - break if c == "\n" - end - return nil if l == "" and c.nil? - l - end - - def eof? - @io.eof? - end - - def getc_of_rests - if @rests.empty? - nil - else - getc - end - end - - def ungetc(c = nil) - if @here_readed.empty? - c2 = @readed.pop - else - c2 = @here_readed.pop - end - c = c2 unless c - @rests.unshift c #c = - @seek -= 1 - if c == "\n" - @line_no -= 1 - if idx = @readed.reverse.index("\n") - @char_no = @readed.size - idx - else - @char_no = @base_char_no + @readed.size - end - else - @char_no -= 1 - end - end - - def peek_equal?(str) - chrs = str.split(//) - until @rests.size >= chrs.size - return false unless buf_input - end - @rests[0, chrs.size] == chrs - end - - def peek_match?(regexp) - while @rests.empty? - return false unless buf_input - end - regexp =~ @rests.join("") - end - - def peek(i = 0) - while @rests.size <= i - return nil unless buf_input - end - @rests[i] - end - - def buf_input - prompt - line = @input.call - return nil unless line - @rests.concat line.split(//) - true - end - private :buf_input - - def set_prompt(p = nil, &block) - p = block if block_given? - if p.respond_to?(:call) - @prompt = p - else - @prompt = Proc.new{print p} - end - end - - def prompt - if @prompt - @prompt.call(@ltype, @indent, @continue, @line_no) - end - end - - def initialize_input - @ltype = nil - @quoted = nil - @indent = 0 - @indent_stack = [] - @lex_state = EXPR_BEG - @space_seen = false - @here_header = false - - @continue = false - prompt - - @line = "" - @exp_line_no = @line_no - end - - def each_top_level_statement - initialize_input - catch(:TERM_INPUT) do - loop do - begin - @continue = false - prompt - unless l = lex - throw :TERM_INPUT if @line == '' - else - #p l - @line.concat l - if @ltype or @continue or @indent > 0 - next - end - end - if @line != "\n" - yield @line, @exp_line_no - end - break unless l - @line = '' - @exp_line_no = @line_no - - @indent = 0 - @indent_stack = [] - prompt - rescue TerminateLineInput - initialize_input - prompt - get_readed - end - end - end - end - - def lex - until (((tk = token).kind_of?(TkNL) || tk.kind_of?(TkEND_OF_SCRIPT)) && - !@continue or - tk.nil?) - #p tk - #p @lex_state - #p self - end - line = get_readed - # print self.inspect - if line == "" and tk.kind_of?(TkEND_OF_SCRIPT) || tk.nil? - nil - else - line - end - end - - def token - # require "tracer" - # Tracer.on - @prev_seek = @seek - @prev_line_no = @line_no - @prev_char_no = @char_no - begin - begin - tk = @OP.match(self) - @space_seen = tk.kind_of?(TkSPACE) - rescue SyntaxError => e - raise RDoc::Error, "syntax error: #{e.message}" if - @exception_on_syntax_error - - tk = TkError.new(@seek, @line_no, @char_no) - end - end while @skip_space and tk.kind_of?(TkSPACE) - - if @readed_auto_clean_up - get_readed - end - # Tracer.off - tk - end - - ENINDENT_CLAUSE = [ - "case", "class", "def", "do", "for", "if", - "module", "unless", "until", "while", "begin" #, "when" - ] - - DEINDENT_CLAUSE = ["end" #, "when" - ] - - PERCENT_LTYPE = { - "q" => "\'", - "Q" => "\"", - "x" => "\`", - "r" => "/", - "w" => "]", - "W" => "]", - "s" => ":" - } - - PERCENT_PAREN = { - "{" => "}", - "[" => "]", - "<" => ">", - "(" => ")" - } - - PERCENT_PAREN_REV = PERCENT_PAREN.invert - - Ltype2Token = { - "\'" => TkSTRING, - "\"" => TkSTRING, - "\`" => TkXSTRING, - "/" => TkREGEXP, - "]" => TkDSTRING, - ":" => TkSYMBOL - } - DLtype2Token = { - "\"" => TkDSTRING, - "\`" => TkDXSTRING, - "/" => TkDREGEXP, - } - - def lex_init() - @OP = IRB::SLex.new - @OP.def_rules("\0", "\004", "\032") do |op, io| - Token(TkEND_OF_SCRIPT) - end - - @OP.def_rules(" ", "\t", "\f", "\r", "\13") do |op, io| - @space_seen = true - str = op - while (ch = getc) =~ /[ \t\f\r\13]/ do - str << ch - end - ungetc - Token TkSPACE, str - end - - @OP.def_rule("#") do |op, io| - identify_comment - end - - @OP.def_rule("=begin", - proc{|op, io| @prev_char_no == 0 && peek(0) =~ /\s/}) do - |op, io| - @ltype = "=" - res = '' - until (ch = getc) == "\n" do res << ch end - until peek_equal?("=end") && peek(4) =~ /\s/ do - until (ch = getc) == "\n" do res << ch end - end - res << gets - @ltype = nil - Token(TkRD_COMMENT, res) - end - - @OP.def_rule("\n") do |op, io| - print "\\n\n" if RDoc::RubyLex.debug? - case @lex_state - when EXPR_BEG, EXPR_FNAME, EXPR_DOT - @continue = true - else - @continue = false - @lex_state = EXPR_BEG - until (@indent_stack.empty? || - [TkLPAREN, TkLBRACK, TkLBRACE, - TkfLPAREN, TkfLBRACK, TkfLBRACE].include?(@indent_stack.last)) - @indent_stack.pop - end - end - @here_header = false - @here_readed = [] - Token(TkNL) - end - - @OP.def_rules("*", "**", - "=", "==", "===", - "=~", "<=>", - "<", "<=", - ">", ">=", ">>") do - |op, io| - case @lex_state - when EXPR_FNAME, EXPR_DOT - @lex_state = EXPR_ARG - else - @lex_state = EXPR_BEG - end - Token(op) - end - - @OP.def_rules("!", "!=", "!~") do - |op, io| - @lex_state = EXPR_BEG - Token(op) - end - - @OP.def_rules("<<") do - |op, io| - tk = nil - if @lex_state != EXPR_END && @lex_state != EXPR_CLASS && - (@lex_state != EXPR_ARG || @space_seen) - c = peek(0) - if /\S/ =~ c && (/["'`]/ =~ c || /\w/ =~ c || c == "-") - tk = identify_here_document - end - end - unless tk - tk = Token(op) - case @lex_state - when EXPR_FNAME, EXPR_DOT - @lex_state = EXPR_ARG - else - @lex_state = EXPR_BEG - end - end - tk - end - - @OP.def_rules("'", '"') do - |op, io| - identify_string(op) - end - - @OP.def_rules("`") do - |op, io| - if @lex_state == EXPR_FNAME - @lex_state = EXPR_END - Token(op) - else - identify_string(op) - end - end - - @OP.def_rules('?') do - |op, io| - if @lex_state == EXPR_END - @lex_state = EXPR_BEG - Token(TkQUESTION) - else - ch = getc - if @lex_state == EXPR_ARG && ch =~ /\s/ - ungetc - @lex_state = EXPR_BEG; - Token(TkQUESTION) - else - str = ch - if ch == '\\' - str << read_escape - end - @lex_state = EXPR_END - str << (ch.respond_to?(:ord) ? ch.ord : ch[0]) - Token(TkINTEGER, str) - end - end - end - - @OP.def_rules("&", "&&", "|", "||") do - |op, io| - @lex_state = EXPR_BEG - Token(op) - end - - @OP.def_rules("+=", "-=", "*=", "**=", - "&=", "|=", "^=", "<<=", ">>=", "||=", "&&=") do - |op, io| - @lex_state = EXPR_BEG - op =~ /^(.*)=$/ - Token(TkOPASGN, $1) - end - - @OP.def_rule("+@", proc{|op, io| @lex_state == EXPR_FNAME}) do - |op, io| - @lex_state = EXPR_ARG - Token(op) - end - - @OP.def_rule("-@", proc{|op, io| @lex_state == EXPR_FNAME}) do - |op, io| - @lex_state = EXPR_ARG - Token(op) - end - - @OP.def_rules("+", "-") do - |op, io| - catch(:RET) do - if @lex_state == EXPR_ARG - if @space_seen and peek(0) =~ /[0-9]/ - throw :RET, identify_number - else - @lex_state = EXPR_BEG - end - elsif @lex_state != EXPR_END and peek(0) =~ /[0-9]/ - throw :RET, identify_number - else - @lex_state = EXPR_BEG - end - Token(op) - end - end - - @OP.def_rule(".") do - |op, io| - @lex_state = EXPR_BEG - if peek(0) =~ /[0-9]/ - ungetc - identify_number - else - # for "obj.if" etc. - @lex_state = EXPR_DOT - Token(TkDOT) - end - end - - @OP.def_rules("..", "...") do - |op, io| - @lex_state = EXPR_BEG - Token(op) - end - - lex_int2 - end - - def lex_int2 - @OP.def_rules("]", "}", ")") do - |op, io| - @lex_state = EXPR_END - @indent -= 1 - @indent_stack.pop - Token(op) - end - - @OP.def_rule(":") do - |op, io| - if @lex_state == EXPR_END || peek(0) =~ /\s/ - @lex_state = EXPR_BEG - Token(TkCOLON) - else - @lex_state = EXPR_FNAME; - Token(TkSYMBEG) - end - end - - @OP.def_rule("::") do - |op, io| - # p @lex_state.id2name, @space_seen - if @lex_state == EXPR_BEG or @lex_state == EXPR_ARG && @space_seen - @lex_state = EXPR_BEG - Token(TkCOLON3) - else - @lex_state = EXPR_DOT - Token(TkCOLON2) - end - end - - @OP.def_rule("/") do - |op, io| - if @lex_state == EXPR_BEG || @lex_state == EXPR_MID - identify_string(op) - elsif peek(0) == '=' - getc - @lex_state = EXPR_BEG - Token(TkOPASGN, "/") #/) - elsif @lex_state == EXPR_ARG and @space_seen and peek(0) !~ /\s/ - identify_string(op) - else - @lex_state = EXPR_BEG - Token("/") #/) - end - end - - @OP.def_rules("^") do - |op, io| - @lex_state = EXPR_BEG - Token("^") - end - - # @OP.def_rules("^=") do - # @lex_state = EXPR_BEG - # Token(OP_ASGN, :^) - # end - - @OP.def_rules(",") do - |op, io| - @lex_state = EXPR_BEG - Token(op) - end - - @OP.def_rules(";") do - |op, io| - @lex_state = EXPR_BEG - until (@indent_stack.empty? || - [TkLPAREN, TkLBRACK, TkLBRACE, - TkfLPAREN, TkfLBRACK, TkfLBRACE].include?(@indent_stack.last)) - @indent_stack.pop - end - Token(op) - end - - @OP.def_rule("~") do - |op, io| - @lex_state = EXPR_BEG - Token("~") - end - - @OP.def_rule("~@", proc{|op, io| @lex_state == EXPR_FNAME}) do - |op, io| - @lex_state = EXPR_BEG - Token("~") - end - - @OP.def_rule("(") do - |op, io| - @indent += 1 - if @lex_state == EXPR_BEG || @lex_state == EXPR_MID - @lex_state = EXPR_BEG - tk_c = TkfLPAREN - else - @lex_state = EXPR_BEG - tk_c = TkLPAREN - end - @indent_stack.push tk_c - tk = Token(tk_c) - end - - @OP.def_rule("[]", proc{|op, io| @lex_state == EXPR_FNAME}) do - |op, io| - @lex_state = EXPR_ARG - Token("[]") - end - - @OP.def_rule("[]=", proc{|op, io| @lex_state == EXPR_FNAME}) do - |op, io| - @lex_state = EXPR_ARG - Token("[]=") - end - - @OP.def_rule("[") do - |op, io| - @indent += 1 - if @lex_state == EXPR_FNAME - tk_c = TkfLBRACK - else - if @lex_state == EXPR_BEG || @lex_state == EXPR_MID - tk_c = TkLBRACK - elsif @lex_state == EXPR_ARG && @space_seen - tk_c = TkLBRACK - else - tk_c = TkfLBRACK - end - @lex_state = EXPR_BEG - end - @indent_stack.push tk_c - Token(tk_c) - end - - @OP.def_rule("{") do - |op, io| - @indent += 1 - if @lex_state != EXPR_END && @lex_state != EXPR_ARG - tk_c = TkLBRACE - else - tk_c = TkfLBRACE - end - @lex_state = EXPR_BEG - @indent_stack.push tk_c - Token(tk_c) - end - - @OP.def_rule('\\') do - |op, io| - if getc == "\n" - @space_seen = true - @continue = true - Token(TkSPACE) - else - ungetc - Token("\\") - end - end - - @OP.def_rule('%') do - |op, io| - if @lex_state == EXPR_BEG || @lex_state == EXPR_MID - identify_quotation - elsif peek(0) == '=' - getc - Token(TkOPASGN, :%) - elsif @lex_state == EXPR_ARG and @space_seen and peek(0) !~ /\s/ - identify_quotation - else - @lex_state = EXPR_BEG - Token("%") #)) - end - end - - @OP.def_rule('$') do - |op, io| - identify_gvar - end - - @OP.def_rule('@') do - |op, io| - if peek(0) =~ /[\w@]/ - ungetc - identify_identifier - else - Token("@") - end - end - - # @OP.def_rule("def", proc{|op, io| /\s/ =~ io.peek(0)}) do - # |op, io| - # @indent += 1 - # @lex_state = EXPR_FNAME - # # @lex_state = EXPR_END - # # until @rests[0] == "\n" or @rests[0] == ";" - # # rests.shift - # # end - # end - - @OP.def_rule("_") do - if peek_match?(/_END__/) and @lex_state == EXPR_BEG then - Token(TkEND_OF_SCRIPT) - else - ungetc - identify_identifier - end - end - - @OP.def_rule("") do - |op, io| - printf "MATCH: start %s: %s\n", op, io.inspect if RDoc::RubyLex.debug? - if peek(0) =~ /[0-9]/ - t = identify_number - else - t = identify_identifier - end - printf "MATCH: end %s: %s\n", op, io.inspect if RDoc::RubyLex.debug? - t - end - - p @OP if RDoc::RubyLex.debug? - end - - def identify_gvar - @lex_state = EXPR_END - - case ch = getc - when /[~_*$?!@\/\\;,=:<>".]/ #" - Token(TkGVAR, "$" + ch) - when "-" - Token(TkGVAR, "$-" + getc) - when "&", "`", "'", "+" - Token(TkBACK_REF, "$"+ch) - when /[1-9]/ - ref = ch - while (ch = getc) =~ /[0-9]/ do ref << ch end - ungetc - Token(TkNTH_REF, "$#{ref}") - when /\w/ - ungetc - ungetc - identify_identifier - else - ungetc - Token("$") - end - end - - def identify_identifier - token = "" - if peek(0) =~ /[$@]/ - token.concat(c = getc) - if c == "@" and peek(0) == "@" - token.concat getc - end - end - - # HACK to avoid a warning the regexp is hidden behind an eval - # HACK need a better way to detect oniguruma - @identifier_re ||= if defined? Encoding then - eval '/[\p{Alnum}_]/u' - else - eval '/[\w\x80-\xff]/' - end - - while (ch = getc) =~ @identifier_re - print " :#{ch}: " if RDoc::RubyLex.debug? - token.concat ch - end - - ungetc - - if (ch == "!" || ch == "?") && token[0,1] =~ /\w/ && peek(0) != "=" - token.concat getc - end - - # almost fix token - - case token - when /^\$/ - return Token(TkGVAR, token) - when /^\@\@/ - @lex_state = EXPR_END - # p Token(TkCVAR, token) - return Token(TkCVAR, token) - when /^\@/ - @lex_state = EXPR_END - return Token(TkIVAR, token) - end - - if @lex_state != EXPR_DOT - print token, "\n" if RDoc::RubyLex.debug? - - token_c, *trans = TkReading2Token[token] - if token_c - # reserved word? - - if (@lex_state != EXPR_BEG && - @lex_state != EXPR_FNAME && - trans[1]) - # modifiers - token_c = TkSymbol2Token[trans[1]] - @lex_state = trans[0] - else - if @lex_state != EXPR_FNAME - if ENINDENT_CLAUSE.include?(token) - # check for ``class = val'' etc. - valid = true - case token - when "class" - valid = false unless peek_match?(/^\s*(<<|\w|::)/) - when "def" - valid = false if peek_match?(/^\s*(([+-\/*&\|^]|<<|>>|\|\||\&\&)=|\&\&|\|\|)/) - when "do" - valid = false if peek_match?(/^\s*([+-\/*]?=|\*|<|>|\&)/) - when *ENINDENT_CLAUSE - valid = false if peek_match?(/^\s*([+-\/*]?=|\*|<|>|\&|\|)/) - else - # no nothing - end - if valid - if token == "do" - if ![TkFOR, TkWHILE, TkUNTIL].include?(@indent_stack.last) - @indent += 1 - @indent_stack.push token_c - end - else - @indent += 1 - @indent_stack.push token_c - end - end - - elsif DEINDENT_CLAUSE.include?(token) - @indent -= 1 - @indent_stack.pop - end - @lex_state = trans[0] - else - @lex_state = EXPR_END - end - end - return Token(token_c, token) - end - end - - if @lex_state == EXPR_FNAME - @lex_state = EXPR_END - if peek(0) == '=' - token.concat getc - end - elsif @lex_state == EXPR_BEG || @lex_state == EXPR_DOT - @lex_state = EXPR_ARG - else - @lex_state = EXPR_END - end - - if token[0, 1] =~ /[A-Z]/ - return Token(TkCONSTANT, token) - elsif token[token.size - 1, 1] =~ /[!?]/ - return Token(TkFID, token) - else - return Token(TkIDENTIFIER, token) - end - end - - def identify_here_document - ch = getc - # if lt = PERCENT_LTYPE[ch] - if ch == "-" - ch = getc - indent = true - end - if /['"`]/ =~ ch - lt = ch - quoted = "" - while (c = getc) && c != lt - quoted.concat c - end - else - lt = '"' - quoted = ch.dup - while (c = getc) && c =~ /\w/ - quoted.concat c - end - ungetc - end - - ltback, @ltype = @ltype, lt - reserve = [] - while ch = getc - reserve.push ch - if ch == "\\" - reserve.push ch = getc - elsif ch == "\n" - break - end - end - - @here_header = false - doc = '' - while l = gets - l = l.sub(/(:?\r)?\n\z/, '') - if (indent ? l.strip : l) == quoted - break - end - doc << l - end - - @here_header = true - @here_readed.concat reserve - while ch = reserve.pop - ungetc ch - end - - @ltype = ltback - @lex_state = EXPR_END - Token(Ltype2Token[lt], doc) - end - - def identify_quotation - ch = getc - if lt = PERCENT_LTYPE[ch] - ch = getc - elsif ch =~ /\W/ - lt = "\"" - else - raise RDoc::Error, "unknown type of %string #{ch.inspect}" - end - # if ch !~ /\W/ - # ungetc - # next - # end - #@ltype = lt - @quoted = ch unless @quoted = PERCENT_PAREN[ch] - identify_string(lt, @quoted) - end - - def identify_number - @lex_state = EXPR_END - - num = '' - - if peek(0) == "0" && peek(1) !~ /[.eE]/ - num << getc - - case peek(0) - when /[xX]/ - ch = getc - match = /[0-9a-fA-F_]/ - when /[bB]/ - ch = getc - match = /[01_]/ - when /[oO]/ - ch = getc - match = /[0-7_]/ - when /[dD]/ - ch = getc - match = /[0-9_]/ - when /[0-7]/ - match = /[0-7_]/ - when /[89]/ - raise RDoc::Error, "Illegal octal digit" - else - return Token(TkINTEGER, num) - end - - num << ch if ch - - len0 = true - non_digit = false - while ch = getc - num << ch - if match =~ ch - if ch == "_" - if non_digit - raise RDoc::Error, "trailing `#{ch}' in number" - else - non_digit = ch - end - else - non_digit = false - len0 = false - end - else - ungetc - num[-1, 1] = '' - if len0 - raise RDoc::Error, "numeric literal without digits" - end - if non_digit - raise RDoc::Error, "trailing `#{non_digit}' in number" - end - break - end - end - return Token(TkINTEGER, num) - end - - type = TkINTEGER - allow_point = true - allow_e = true - non_digit = false - while ch = getc - num << ch - case ch - when /[0-9]/ - non_digit = false - when "_" - non_digit = ch - when allow_point && "." - if non_digit - raise RDoc::Error, "trailing `#{non_digit}' in number" - end - type = TkFLOAT - if peek(0) !~ /[0-9]/ - type = TkINTEGER - ungetc - num[-1, 1] = '' - break - end - allow_point = false - when allow_e && "e", allow_e && "E" - if non_digit - raise RDoc::Error, "trailing `#{non_digit}' in number" - end - type = TkFLOAT - if peek(0) =~ /[+-]/ - num << getc - end - allow_e = false - allow_point = false - non_digit = ch - else - if non_digit - raise RDoc::Error, "trailing `#{non_digit}' in number" - end - ungetc - num[-1, 1] = '' - break - end - end - - Token(type, num) - end - - def identify_string(ltype, quoted = ltype) - @ltype = ltype - @quoted = quoted - - str = if ltype == quoted then - ltype.dup - else - "%#{PERCENT_PAREN_REV[quoted]}" - end - - subtype = nil - begin - nest = 0 - - while ch = getc - str << ch - - if @quoted == ch and nest == 0 - break - elsif @ltype != "'" && @ltype != "]" && @ltype != ":" and ch == "#" - ch = getc - subtype = true - if ch == "{" then - str << ch << skip_inner_expression - next - else - ungetc - end - elsif ch == '\\' and @ltype == "'" #' - case ch = getc - when "\\", "\n", "'" - else - ungetc - end - elsif ch == '\\' #' - str << read_escape - end - - if PERCENT_PAREN.values.include?(@quoted) - if PERCENT_PAREN[ch] == @quoted - nest += 1 - elsif ch == @quoted - nest -= 1 - end - end - end - - if @ltype == "/" - if peek(0) =~ /i|m|x|o|e|s|u|n/ - getc - end - end - - if subtype - Token(DLtype2Token[ltype], str) - else - Token(Ltype2Token[ltype], str) - end - ensure - @ltype = nil - @quoted = nil - @lex_state = EXPR_END - end - end - - def skip_inner_expression - res = "" - nest = 0 - while ch = getc - res << ch - if ch == '}' - break if nest.zero? - nest -= 1 - elsif ch == '{' - nest += 1 - end - end - res - end - - def identify_comment - @ltype = "#" - - comment = '#' - - while ch = getc - # if ch == "\\" #" - # read_escape - # end - if ch == "\n" - @ltype = nil - ungetc - break - end - - comment << ch - end - - return Token(TkCOMMENT, comment) - end - - def read_escape - escape = '' - ch = getc - escape << ch - - case ch - when "\n", "\r", "\f" - when "\\", "n", "t", "r", "f", "v", "a", "e", "b", "s" #" - when /[0-7]/ - ungetc ch - 3.times do - ch = getc - escape << ch - case ch - when /[0-7]/ - when nil - break - else - ungetc - break - end - end - - when "x" - 2.times do - ch = getc - escape << ch - case ch - when /[0-9a-fA-F]/ - when nil - break - else - ungetc - break - end - end - - when "M" - ch = getc - escape << ch - if ch != '-' - ungetc - else - ch = getc - escape << ch - if ch == "\\" #" - escape << read_escape - end - end - - when "C", "c" #, "^" - if ch == "C" and (ch = getc) != "-" - escape << ch - ungetc - elsif (ch = getc) == "\\" #" - escape << ch << read_escape - end - else - # other characters - end - - escape - end - - # :startdoc: - -end - -#RDoc::RubyLex.debug_level = 1 - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/ruby_token.rb b/Src/StdLib/ruby/1.9.1/rdoc/ruby_token.rb deleted file mode 100644 index e792ddb6b..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/ruby_token.rb +++ /dev/null @@ -1,416 +0,0 @@ -#-- -# irb/ruby-token.rb - ruby tokens -# $Release Version: 0.9.5$ -# $Revision: 11708 $ -# $Date: 2007-02-12 15:01:19 -0800 (Mon, 12 Feb 2007) $ -# by Keiju ISHITSUKA(keiju@ruby-lang.org) -#++ -# Definitions of all tokens involved in the lexical analysis. -# -# This class is not documented because it is so deep in the internals. - -module RDoc::RubyToken - # :stopdoc: - - EXPR_BEG = :EXPR_BEG - EXPR_MID = :EXPR_MID - EXPR_END = :EXPR_END - EXPR_ARG = :EXPR_ARG - EXPR_FNAME = :EXPR_FNAME - EXPR_DOT = :EXPR_DOT - EXPR_CLASS = :EXPR_CLASS - - # for ruby 1.4X - if !defined?(Symbol) - Symbol = Integer - end - - def set_token_position(line, char) - @prev_line_no = line - @prev_char_no = char - end - - class Token - def initialize(seek, line_no, char_no, text = nil) - @seek = seek - @line_no = line_no - @char_no = char_no - @text = text - end - - attr :seek - attr :line_no - attr :char_no - - attr_accessor :text - - def ==(other) - self.class == other.class and - other.line_no == @line_no and - other.char_no == @char_no and - other.text == @text - end - - ## - # Because we're used in contexts that expect to return a token, we set the - # text string and then return ourselves - - def set_text(text) - @text = text - self - end - - end - - class TkNode < Token - def initialize(seek, line_no, char_no, node = nil) - super seek, line_no, char_no - @node = node - end - - attr :node - - def ==(other) - self.class == other.class and - other.line_no == @line_no and - other.char_no == @char_no and - other.node == @node - end - - def set_text text - @node = text - self - end - - alias text node - end - - class TkId < Token - def initialize(seek, line_no, char_no, name) - super(seek, line_no, char_no) - @name = name - end - attr :name - - def ==(other) - self.class == other.class and - other.line_no == @line_no and - other.char_no == @char_no and - other.name == @name - end - - def set_text text - @name = text - self - end - - alias text name - end - - class TkKW < TkId - end - - class TkVal < Token - def initialize(seek, line_no, char_no, value = nil) - super(seek, line_no, char_no) - @value = value - end - attr_accessor :value - - def ==(other) - self.class == other.class and - other.line_no == @line_no and - other.char_no == @char_no and - other.value == @value - end - - def set_text text - @value = text - self - end - - alias text value - end - - class TkOp < Token - def initialize(seek, line_no, char_no, name = nil) - super seek, line_no, char_no - @name = name - end - - attr_accessor :name - - def ==(other) - self.class == other.class and - other.line_no == @line_no and - other.char_no == @char_no and - other.name == @name - end - - def set_text text - @name = text - self - end - - alias text name - end - - class TkOPASGN < TkOp - def initialize(seek, line_no, char_no, op) - super(seek, line_no, char_no) - op = TkReading2Token[op][0] unless op.kind_of?(Symbol) - @op = op - @text = nil - end - - attr :op - - def ==(other) - self.class == other.class and - other.line_no == @line_no and - other.char_no == @char_no and - other.op == @op - end - - def text - @text ||= "#{TkToken2Reading[op]}=" - end - end - - class TkUnknownChar < Token - def initialize(seek, line_no, char_no, id) - super(seek, line_no, char_no) - @name = name - end - attr :name - - def ==(other) - self.class == other.class and - other.line_no == @line_no and - other.char_no == @char_no and - other.name == @name - end - - def set_text text - @name = text - self - end - - alias text name - end - - class TkError < Token - end - - def Token(token, value = nil) - value ||= TkToken2Reading[token] - - case token - when String - if (tk = TkReading2Token[token]).nil? - IRB.fail TkReading2TokenNoKey, token - end - - tk = Token(tk[0], value) - - if tk.kind_of?(TkOp) then - tk.name = token - end - when Symbol - if (tk = TkSymbol2Token[token]).nil? - IRB.fail TkSymbol2TokenNoKey, token - end - - tk = Token(tk[0], value) - else - if token.instance_method(:initialize).arity == 3 then - tk = token.new(@prev_seek, @prev_line_no, @prev_char_no) - tk.set_text value - else - tk = token.new(@prev_seek, @prev_line_no, @prev_char_no, value) - end - end - - tk - end - - TokenDefinitions = [ - [:TkCLASS, TkKW, "class", EXPR_CLASS], - [:TkMODULE, TkKW, "module", EXPR_BEG], - [:TkDEF, TkKW, "def", EXPR_FNAME], - [:TkUNDEF, TkKW, "undef", EXPR_FNAME], - [:TkBEGIN, TkKW, "begin", EXPR_BEG], - [:TkRESCUE, TkKW, "rescue", EXPR_MID], - [:TkENSURE, TkKW, "ensure", EXPR_BEG], - [:TkEND, TkKW, "end", EXPR_END], - [:TkIF, TkKW, "if", EXPR_BEG, :TkIF_MOD], - [:TkUNLESS, TkKW, "unless", EXPR_BEG, :TkUNLESS_MOD], - [:TkTHEN, TkKW, "then", EXPR_BEG], - [:TkELSIF, TkKW, "elsif", EXPR_BEG], - [:TkELSE, TkKW, "else", EXPR_BEG], - [:TkCASE, TkKW, "case", EXPR_BEG], - [:TkWHEN, TkKW, "when", EXPR_BEG], - [:TkWHILE, TkKW, "while", EXPR_BEG, :TkWHILE_MOD], - [:TkUNTIL, TkKW, "until", EXPR_BEG, :TkUNTIL_MOD], - [:TkFOR, TkKW, "for", EXPR_BEG], - [:TkBREAK, TkKW, "break", EXPR_END], - [:TkNEXT, TkKW, "next", EXPR_END], - [:TkREDO, TkKW, "redo", EXPR_END], - [:TkRETRY, TkKW, "retry", EXPR_END], - [:TkIN, TkKW, "in", EXPR_BEG], - [:TkDO, TkKW, "do", EXPR_BEG], - [:TkRETURN, TkKW, "return", EXPR_MID], - [:TkYIELD, TkKW, "yield", EXPR_END], - [:TkSUPER, TkKW, "super", EXPR_END], - [:TkSELF, TkKW, "self", EXPR_END], - [:TkNIL, TkKW, "nil", EXPR_END], - [:TkTRUE, TkKW, "true", EXPR_END], - [:TkFALSE, TkKW, "false", EXPR_END], - [:TkAND, TkKW, "and", EXPR_BEG], - [:TkOR, TkKW, "or", EXPR_BEG], - [:TkNOT, TkKW, "not", EXPR_BEG], - [:TkIF_MOD, TkKW], - [:TkUNLESS_MOD, TkKW], - [:TkWHILE_MOD, TkKW], - [:TkUNTIL_MOD, TkKW], - [:TkALIAS, TkKW, "alias", EXPR_FNAME], - [:TkDEFINED, TkKW, "defined?", EXPR_END], - [:TklBEGIN, TkKW, "BEGIN", EXPR_END], - [:TklEND, TkKW, "END", EXPR_END], - [:Tk__LINE__, TkKW, "__LINE__", EXPR_END], - [:Tk__FILE__, TkKW, "__FILE__", EXPR_END], - - [:TkIDENTIFIER, TkId], - [:TkFID, TkId], - [:TkGVAR, TkId], - [:TkCVAR, TkId], - [:TkIVAR, TkId], - [:TkCONSTANT, TkId], - - [:TkINTEGER, TkVal], - [:TkFLOAT, TkVal], - [:TkSTRING, TkVal], - [:TkXSTRING, TkVal], - [:TkREGEXP, TkVal], - [:TkSYMBOL, TkVal], - - [:TkDSTRING, TkNode], - [:TkDXSTRING, TkNode], - [:TkDREGEXP, TkNode], - [:TkNTH_REF, TkNode], - [:TkBACK_REF, TkNode], - - [:TkUPLUS, TkOp, "+@"], - [:TkUMINUS, TkOp, "-@"], - [:TkPOW, TkOp, "**"], - [:TkCMP, TkOp, "<=>"], - [:TkEQ, TkOp, "=="], - [:TkEQQ, TkOp, "==="], - [:TkNEQ, TkOp, "!="], - [:TkGEQ, TkOp, ">="], - [:TkLEQ, TkOp, "<="], - [:TkANDOP, TkOp, "&&"], - [:TkOROP, TkOp, "||"], - [:TkMATCH, TkOp, "=~"], - [:TkNMATCH, TkOp, "!~"], - [:TkDOT2, TkOp, ".."], - [:TkDOT3, TkOp, "..."], - [:TkAREF, TkOp, "[]"], - [:TkASET, TkOp, "[]="], - [:TkLSHFT, TkOp, "<<"], - [:TkRSHFT, TkOp, ">>"], - [:TkCOLON2, TkOp, '::'], - [:TkCOLON3, TkOp, '::'], - #[:OPASGN, TkOp], # +=, -= etc. # - [:TkASSOC, TkOp, "=>"], - [:TkQUESTION, TkOp, "?"], #? - [:TkCOLON, TkOp, ":"], #: - - [:TkfLPAREN, Token, "("], # func( # - [:TkfLBRACK, Token, "["], # func[ # - [:TkfLBRACE, Token, "{"], # func{ # - [:TkSTAR, Token, "*"], # *arg - [:TkAMPER, Token, "&"], # &arg # - [:TkSYMBEG, Token, ":"], # :SYMBOL - - [:TkGT, TkOp, ">"], - [:TkLT, TkOp, "<"], - [:TkPLUS, TkOp, "+"], - [:TkMINUS, TkOp, "-"], - [:TkMULT, TkOp, "*"], - [:TkDIV, TkOp, "/"], - [:TkMOD, TkOp, "%"], - [:TkBITOR, TkOp, "|"], - [:TkBITXOR, TkOp, "^"], - [:TkBITAND, TkOp, "&"], - [:TkBITNOT, TkOp, "~"], - [:TkNOTOP, TkOp, "!"], - - [:TkBACKQUOTE, TkOp, "`"], - - [:TkASSIGN, Token, "="], - [:TkDOT, Token, "."], - [:TkLPAREN, Token, "("], #(exp) - [:TkLBRACK, Token, "["], #[arry] - [:TkLBRACE, Token, "{"], #{hash} - [:TkRPAREN, Token, ")"], - [:TkRBRACK, Token, "]"], - [:TkRBRACE, Token, "}"], - [:TkCOMMA, Token, ","], - [:TkSEMICOLON, Token, ";"], - - [:TkCOMMENT, TkVal], - [:TkRD_COMMENT], - [:TkSPACE, Token, " "], - [:TkNL, Token, "\n"], - [:TkEND_OF_SCRIPT], - - [:TkBACKSLASH, TkUnknownChar, "\\"], - [:TkAT, TkUnknownChar, "@"], - [:TkDOLLAR, TkUnknownChar, "$"], - ] - - # {reading => token_class} - # {reading => [token_class, *opt]} - TkReading2Token = {} - TkToken2Reading = {} - TkSymbol2Token = {} - - def self.def_token(token_n, super_token = Token, reading = nil, *opts) - token_n = token_n.id2name if token_n.kind_of?(Symbol) - if const_defined?(token_n) - IRB.fail AlreadyDefinedToken, token_n - end - token_c = eval("class #{token_n} < #{super_token}; end; #{token_n}") - - if reading - TkToken2Reading[token_c] = reading - - return if TkReading2Token[reading] - - if opts.empty? - TkReading2Token[reading] = [token_c] - else - TkReading2Token[reading] = [token_c].concat(opts) - end - end - TkSymbol2Token[token_n.intern] = token_c - end - - for defs in TokenDefinitions - def_token(*defs) - end - - NEWLINE_TOKEN = TkNL.new nil, 0, 0, "\n" - - class TkSYMBOL - - def to_sym - @sym ||= text[1..-1].intern - end - - end - - # :startdoc: -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/single_class.rb b/Src/StdLib/ruby/1.9.1/rdoc/single_class.rb deleted file mode 100644 index f86583139..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/single_class.rb +++ /dev/null @@ -1,13 +0,0 @@ -require 'rdoc/class_module' - -## -# A singleton class - -class RDoc::SingleClass < RDoc::ClassModule - - def ancestors - includes + [superclass] - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/stats.rb b/Src/StdLib/ruby/1.9.1/rdoc/stats.rb deleted file mode 100644 index 746d1e82b..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/stats.rb +++ /dev/null @@ -1,247 +0,0 @@ -require 'rdoc' - -## -# RDoc stats collector - -class RDoc::Stats - - attr_reader :nodoc_constants - attr_reader :nodoc_methods - - attr_reader :num_constants - attr_reader :num_files - attr_reader :num_methods - - attr_reader :total_files - - def initialize(total_files, verbosity = 1) - @nodoc_constants = 0 - @nodoc_methods = 0 - - @num_constants = 0 - @num_files = 0 - @num_methods = 0 - - @total_files = total_files - - @start = Time.now - - @display = case verbosity - when 0 then Quiet.new total_files - when 1 then Normal.new total_files - else Verbose.new total_files - end - end - - def begin_adding - @display.begin_adding - end - - def add_alias(as) - @display.print_alias as - @num_methods += 1 - @nodoc_methods += 1 if as.document_self and as.comment.empty? - end - - def add_class(klass) - @display.print_class klass - end - - def add_constant(constant) - @display.print_constant constant - @num_constants += 1 - @nodoc_constants += 1 if constant.document_self and constant.comment.empty? - end - - def add_file(file) - @display.print_file @num_files, file - @num_files += 1 - end - - def add_method(method) - @display.print_method method - @num_methods += 1 - @nodoc_methods += 1 if method.document_self and method.comment.empty? - end - - def add_module(mod) - @display.print_module mod - end - - def done_adding - @display.done_adding - end - - def print - classes = RDoc::TopLevel.classes - num_classes = classes.length - nodoc_classes = classes.select do |klass| - klass.document_self and klass.comment.empty? - end.length - - modules = RDoc::TopLevel.modules - num_modules = modules.length - nodoc_modules = modules.select do |mod| - mod.document_self and mod.comment.empty? - end.length - - items = num_classes + @num_constants + num_modules + @num_methods - doc_items = items - - nodoc_classes - @nodoc_constants - nodoc_modules - @nodoc_methods - - percent_doc = doc_items.to_f / items * 100 - - puts "Files: %5d" % @num_files - puts "Classes: %5d (%5d undocumented)" % [num_classes, nodoc_classes] - puts "Constants: %5d (%5d undocumented)" % - [@num_constants, @nodoc_constants] - puts "Modules: %5d (%5d undocumented)" % [num_modules, nodoc_modules] - puts "Methods: %5d (%5d undocumented)" % [@num_methods, @nodoc_methods] - puts "%6.2f%% documented" % percent_doc - puts - puts "Elapsed: %0.1fs" % (Time.now - @start) - end - - ## - # Stats printer that prints nothing - - class Quiet - - def initialize total_files - @total_files = total_files - end - - ## - # Prints a message at the beginning of parsing - - def begin_adding(*) end - - ## - # Prints when an alias is added - - def print_alias(*) end - - ## - # Prints when a class is added - - def print_class(*) end - - ## - # Prints when a constant is added - - def print_constant(*) end - - ## - # Prints when a file is added - - def print_file(*) end - - ## - # Prints when a method is added - - def print_method(*) end - - ## - # Prints when a module is added - - def print_module(*) end - - ## - # Prints when RDoc is done - - def done_adding(*) end - - end - - ## - # Stats printer that prints just the files being documented with a progress - # bar - - class Normal < Quiet - - def begin_adding # :nodoc: - puts "Parsing sources..." - end - - ## - # Prints a file with a progress bar - - def print_file(files_so_far, filename) - progress_bar = sprintf("%3d%% [%2d/%2d] ", - 100 * (files_so_far + 1) / @total_files, - files_so_far + 1, - @total_files) - - if $stdout.tty? - # Print a progress bar, but make sure it fits on a single line. Filename - # will be truncated if necessary. - terminal_width = (ENV['COLUMNS'] || 80).to_i - max_filename_size = terminal_width - progress_bar.size - if filename.size > max_filename_size - # Turn "some_long_filename.rb" to "...ong_filename.rb" - filename = filename[(filename.size - max_filename_size) .. -1] - filename[0..2] = "..." - end - - # Pad the line with whitespaces so that leftover output from the - # previous line doesn't show up. - line = "#{progress_bar}#{filename}" - padding = terminal_width - line.size - line << (" " * padding) if padding > 0 - - $stdout.print("#{line}\r") - else - $stdout.puts "#{progress_bar} #{filename}" - end - $stdout.flush - end - - def done_adding # :nodoc: - puts - end - - end - - ## - # Stats printer that prints everything documented, including the documented - # status - - class Verbose < Normal - - ## - # Returns a marker for RDoc::CodeObject +co+ being undocumented - - def nodoc co - " (undocumented)" unless co.documented? - end - - def print_alias as # :nodoc: - puts "\t\talias #{as.new_name} #{as.old_name}#{nodoc as}" - end - - def print_class(klass) # :nodoc: - puts "\tclass #{klass.full_name}#{nodoc klass}" - end - - def print_constant(constant) # :nodoc: - puts "\t\t#{constant.name}#{nodoc constant}" - end - - def print_file(files_so_far, file) # :nodoc: - super - puts - end - - def print_method(method) # :nodoc: - puts "\t\t#{method.singleton ? '::' : '#'}#{method.name}#{nodoc method}" - end - - def print_module(mod) # :nodoc: - puts "\tmodule #{mod.full_name}#{nodoc mod}" - end - - end - -end - - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/task.rb b/Src/StdLib/ruby/1.9.1/rdoc/task.rb deleted file mode 100644 index 4dc1c1023..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/task.rb +++ /dev/null @@ -1,33 +0,0 @@ -#-- -# Copyright (c) 2003, 2004 Jim Weirich, 2009 Eric Hodel -# -# Permission is hereby granted, free of charge, to any person obtaining -# a copy of this software and associated documentation files (the -# "Software"), to deal in the Software without restriction, including -# without limitation the rights to use, copy, modify, merge, publish, -# distribute, sublicense, and/or sell copies of the Software, and to -# permit persons to whom the Software is furnished to do so, subject to -# the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -#++ - -require 'rdoc' -require 'rake' -require 'rake/rdoctask' - -# :stopdoc: -module RDoc - Task = Rake::RDocTask -end -# :startdoc: - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/text.rb b/Src/StdLib/ruby/1.9.1/rdoc/text.rb deleted file mode 100644 index 7b5970ed9..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/text.rb +++ /dev/null @@ -1,130 +0,0 @@ -## -# Methods for manipulating comment text - -module RDoc::Text - - ## - # Expands tab characters in +text+ to eight spaces - - def expand_tabs text - expanded = [] - - text.each_line do |line| - line.gsub!(/^(.{8}*?)([^\t\r\n]{0,7})\t/) do - "#{$1}#{$2}#{' ' * (8 - $2.size)}" - end until line !~ /\t/ - - expanded << line - end - - expanded.join - end - - ## - # Flush +text+ left based on the shortest line - - def flush_left text - indents = [] - - text.each_line do |line| - indents << (line =~ /[^\s]/ || 9999) - end - - indent = indents.min - - flush = [] - - text.each_line do |line| - line[/^ {0,#{indent}}/] = '' - flush << line - end - - flush.join - end - - ## - # Convert a string in markup format into HTML. Removes the first paragraph - # tags if +remove_para+ is true. - # - # Requires the including class to implement #formatter - - def markup text - document = parse text - - document.accept formatter - end - - ## - # Strips hashes, expands tabs then flushes +text+ to the left - - def normalize_comment text - return text if text.empty? - - text = strip_hashes text - text = expand_tabs text - text = flush_left text - strip_newlines text - end - - ## - # Normalizes +text+ then builds a RDoc::Markup::Document from it - - def parse text - return text if RDoc::Markup::Document === text - - text = normalize_comment text - - return RDoc::Markup::Document.new if text =~ /\A\n*\z/ - - RDoc::Markup::Parser.parse text - rescue RDoc::Markup::Parser::Error => e - $stderr.puts <<-EOF -While parsing markup, RDoc encountered a #{e.class}: - -#{e} -\tfrom #{e.backtrace.join "\n\tfrom "} - ----8<--- -#{text} ----8<--- - -RDoc #{RDoc::VERSION} - -Ruby #{RUBY_VERSION}-p#{RUBY_PATCHLEVEL} #{RUBY_RELEASE_DATE} - -Please file a bug report with the above information at: - -http://rubyforge.org/tracker/?atid=2472&group_id=627&func=browse - - EOF - raise - end - - ## - # Strips leading # characters from +text+ - - def strip_hashes text - return text if text =~ /^(?>\s*)[^\#]/ - text.gsub(/^\s*(#+)/) { $1.tr '#',' ' } - end - - ## - # Strips leading and trailing \n characters from +text+ - - def strip_newlines text - text.gsub(/\A\n*(.*?)\n*\z/m, '\1') - end - - ## - # Strips /* */ style comments - - def strip_stars text - text = text.gsub %r%Document-method:\s+[\w:.#]+%, '' - text.sub! %r%/\*+% do " " * $&.length end - text.sub! %r%\*+/% do " " * $&.length end - text.gsub! %r%^[ \t]*\*%m do " " * $&.length end - text - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/tokenstream.rb b/Src/StdLib/ruby/1.9.1/rdoc/tokenstream.rb deleted file mode 100644 index 0147e8742..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/tokenstream.rb +++ /dev/null @@ -1,52 +0,0 @@ -module RDoc; end - -## -# A TokenStream is a list of tokens, gathered during the parse of some entity -# (say a method). Entities populate these streams by being registered with the -# lexer. Any class can collect tokens by including TokenStream. From the -# outside, you use such an object by calling the start_collecting_tokens -# method, followed by calls to add_token and pop_token. - -module RDoc::TokenStream - - ## - # Adds +tokens+ to the collected tokens - - def add_tokens(*tokens) - tokens.flatten.each { |token| @token_stream << token } - end - - alias add_token add_tokens - - ## - # Starts collecting tokens - - def collect_tokens - @token_stream = [] - end - - alias start_collecting_tokens collect_tokens - - ## - # Remove the last token from the collected tokens - - def pop_token - @token_stream.pop - end - - ## - # Current token stream - - def token_stream - @token_stream - end - - ## - # Returns a string representation of the token stream - - def tokens_to_s - token_stream.map { |token| token.text }.join '' - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/rdoc/top_level.rb b/Src/StdLib/ruby/1.9.1/rdoc/top_level.rb deleted file mode 100644 index f05723b2b..000000000 --- a/Src/StdLib/ruby/1.9.1/rdoc/top_level.rb +++ /dev/null @@ -1,248 +0,0 @@ -require 'rdoc/context' - -## -# A TopLevel context is a representation of the contents of a single file - -class RDoc::TopLevel < RDoc::Context - - ## - # This TopLevel's File::Stat struct - - attr_accessor :file_stat - - ## - # Relative name of this file - - attr_accessor :relative_name - - ## - # Absolute name of this file - - attr_accessor :absolute_name - - attr_accessor :diagram - - ## - # The parser that processed this file - - attr_accessor :parser - - ## - # Returns all classes and modules discovered by RDoc - - def self.all_classes_and_modules - classes_hash.values + modules_hash.values - end - - ## - # Returns all classes discovered by RDoc - - def self.classes - classes_hash.values - end - - ## - # Hash of all classes known to RDoc - - def self.classes_hash - @all_classes - end - - ## - # All TopLevels known to RDoc - - def self.files - @all_files.values - end - - ## - # Hash of all files known to RDoc - - def self.files_hash - @all_files - end - - ## - # Finds the class with +name+ in all discovered classes - - def self.find_class_named(name) - classes_hash[name] - end - - ## - # Finds the class with +name+ starting in namespace +from+ - - def self.find_class_named_from name, from - from = find_class_named from unless RDoc::Context === from - - until RDoc::TopLevel === from do - return nil unless from - - klass = from.find_class_named name - return klass if klass - - from = from.parent - end - - find_class_named name - end - - ## - # Finds the class or module with +name+ - - def self.find_class_or_module(name) - name =~ /^::/ - name = $' || name - - RDoc::TopLevel.classes_hash[name] || RDoc::TopLevel.modules_hash[name] - end - - ## - # Finds the file with +name+ in all discovered files - - def self.find_file_named(name) - @all_files[name] - end - - ## - # Finds the module with +name+ in all discovered modules - - def self.find_module_named(name) - modules_hash[name] - end - - ## - # Returns all modules discovered by RDoc - - def self.modules - modules_hash.values - end - - ## - # Hash of all modules known to RDoc - - def self.modules_hash - @all_modules - end - - ## - # Empties RDoc of stored class, module and file information - - def self.reset - @all_classes = {} - @all_modules = {} - @all_files = {} - end - - reset - - ## - # Creates a new TopLevel for +file_name+ - - def initialize(file_name) - super() - @name = nil - @relative_name = file_name - @absolute_name = file_name - @file_stat = File.stat(file_name) rescue nil # HACK for testing - @diagram = nil - @parser = nil - - RDoc::TopLevel.files_hash[file_name] = self - end - - ## - # Adds +method+ to Object instead of RDoc::TopLevel - - def add_method(method) - object = self.class.find_class_named 'Object' - object = add_class RDoc::NormalClass, 'Object' unless object - - object.add_method method - end - - ## - # Base name of this file - - def base_name - File.basename @absolute_name - end - - ## - # See RDoc::TopLevel.find_class_or_module - - def find_class_or_module name - RDoc::TopLevel.find_class_or_module name - end - - ## - # Finds a class or module named +symbol+ - - def find_local_symbol(symbol) - find_class_or_module(symbol) || super - end - - ## - # Finds a module or class with +name+ - - def find_module_named(name) - find_class_or_module(name) || find_enclosing_module_named(name) - end - - ## - # The name of this file - - def full_name - @relative_name - end - - ## - # URL for this with a +prefix+ - - def http_url(prefix) - path = [prefix, @relative_name.tr('.', '_')] - - File.join(*path.compact) + '.html' - end - - def inspect # :nodoc: - "#<%s:0x%x %p modules: %p classes: %p>" % [ - self.class, object_id, - base_name, - @modules.map { |n,m| m }, - @classes.map { |n,c| c } - ] - end - - ## - # Date this file was last modified, if known - - def last_modified - @file_stat ? file_stat.mtime.to_s : 'Unknown' - end - - ## - # Base name of this file - - alias name base_name - - ## - # Path to this file - - def path - http_url RDoc::RDoc.current.generator.file_dir - end - - def pretty_print q # :nodoc: - q.group 2, "[#{self.class}: ", "]" do - q.text "base name: #{base_name.inspect}" - q.breakable - - items = @modules.map { |n,m| m } - items.push(*@modules.map { |n,c| c }) - q.seplist items do |mod| q.pp mod end - end - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/scanf.rb b/Src/StdLib/ruby/1.9.1/scanf.rb deleted file mode 100644 index e326e8890..000000000 --- a/Src/StdLib/ruby/1.9.1/scanf.rb +++ /dev/null @@ -1,719 +0,0 @@ -# scanf for Ruby -# -# $Release Version: 1.1.2 $ -# $Revision: 27139 $ -# $Id: scanf.rb 27139 2010-04-01 04:32:22Z naruse $ -# $Author: naruse $ -# -# A product of the Austin Ruby Codefest (Austin, Texas, August 2002) - -=begin - -=scanf for Ruby - -==Description - -scanf for Ruby is an implementation of the C function scanf(3), -modified as necessary for Ruby compatibility. - -The methods provided are String#scanf, IO#scanf, and -Kernel#scanf. Kernel#scanf is a wrapper around STDIN.scanf. IO#scanf -can be used on any IO stream, including file handles and sockets. -scanf can be called either with or without a block. - -scanf for Ruby scans an input string or stream according to a -format, as described below ("Conversions"), and returns an -array of matches between the format and the input. The format is -defined in a string, and is similar (though not identical) to the -formats used in Kernel#printf and Kernel#sprintf. - -The format may contain conversion specifiers, which tell scanf -what form (type) each particular matched substring should be converted -to (e.g., decimal integer, floating point number, literal string, -etc.) The matches and conversions take place from left to right, and -the conversions themselves are returned as an array. - -The format string may also contain characters other than those in the -conversion specifiers. White space (blanks, tabs, or newlines) in the -format string matches any amount of white space, including none, in -the input. Everything else matches only itself. - -Scanning stops, and scanf returns, when any input character fails to -match the specifications in the format string, or when input is -exhausted, or when everything in the format string has been -matched. All matches found up to the stopping point are returned in -the return array (or yielded to the block, if a block was given). - - -==Basic usage - - require 'scanf.rb' - - # String#scanf and IO#scanf take a single argument (a format string) - array = aString.scanf("%d%s") - array = anIO.scanf("%d%s") - - # Kernel#scanf reads from STDIN - array = scanf("%d%s") - -==Block usage - -When called with a block, scanf keeps scanning the input, cycling back -to the beginning of the format string, and yields a new array of -conversions to the block every time the format string is matched -(including partial matches, but not including complete failures). The -actual return value of scanf when called with a block is an array -containing the results of all the executions of the block. - - str = "123 abc 456 def 789 ghi" - str.scanf("%d%s") { |num,str| [ num * 2, str.upcase ] } - # => [[246, "ABC"], [912, "DEF"], [1578, "GHI"]] - -==Conversions - -The single argument to scanf is a format string, which generally -includes one or more conversion specifiers. Conversion specifiers -begin with the percent character ('%') and include information about -what scanf should next scan for (string, decimal number, single -character, etc.). - -There may be an optional maximum field width, expressed as a decimal -integer, between the % and the conversion. If no width is given, a -default of `infinity' is used (with the exception of the %c specifier; -see below). Otherwise, given a field width of n for a given -conversion, at most n characters are scanned in processing -that conversion. Before conversion begins, most conversions skip -white space in the input string; this white space is not counted -against the field width. - -The following conversions are available. (See the files EXAMPLES -and tests/scanftests.rb for examples.) - -[%] - Matches a literal `%'. That is, `%%' in the format string matches a - single input `%' character. No conversion is done, and the resulting - '%' is not included in the return array. - -[d] - Matches an optionally signed decimal integer. - -[u] - Same as d. - -[i] - Matches an optionally signed integer. The integer is read in base - 16 if it begins with `0x' or `0X', in base 8 if it begins with `0', - and in base 10 other- wise. Only characters that correspond to the - base are recognized. - -[o] - Matches an optionally signed octal integer. - -[x,X] - Matches an optionally signed hexadecimal integer, - -[a,e,f,g,A,E,F,G] - Matches an optionally signed floating-point number. - -[s] - Matches a sequence of non-white-space character. The input string stops at - white space or at the maximum field width, whichever occurs first. - -[c] - Matches a single character, or a sequence of n characters if a - field width of n is specified. The usual skip of leading white - space is suppressed. To skip white space first, use an explicit space in - the format. - -[[] - Matches a nonempty sequence of characters from the specified set - of accepted characters. The usual skip of leading white space is - suppressed. This bracketed sub-expression is interpreted exactly like a - character class in a Ruby regular expression. (In fact, it is placed as-is - in a regular expression.) The matching against the input string ends with - the appearance of a character not in (or, with a circumflex, in) the set, - or when the field width runs out, whichever comes first. - -===Assignment suppression - -To require that a particular match occur, but without including the result -in the return array, place the assignment suppression flag, which is -the star character ('*'), immediately after the leading '%' of a format -specifier (just before the field width, if any). - -==Examples - -See the files EXAMPLES and tests/scanftests.rb. - -==scanf for Ruby compared with scanf in C - -scanf for Ruby is based on the C function scanf(3), but with modifications, -dictated mainly by the underlying differences between the languages. - -===Unimplemented flags and specifiers - -* The only flag implemented in scanf for Ruby is '*' (ignore - upcoming conversion). Many of the flags available in C versions of scanf(4) - have to do with the type of upcoming pointer arguments, and are literally - meaningless in Ruby. - -* The n specifier (store number of characters consumed so far in - next pointer) is not implemented. - -* The p specifier (match a pointer value) is not implemented. - -===Altered specifiers - -[o,u,x,X] - In scanf for Ruby, all of these specifiers scan for an optionally signed - integer, rather than for an unsigned integer like their C counterparts. - -===Return values - -scanf for Ruby returns an array of successful conversions, whereas -scanf(3) returns the number of conversions successfully -completed. (See below for more details on scanf for Ruby's return -values.) - -==Return values - -Without a block, scanf returns an array containing all the conversions -it has found. If none are found, scanf will return an empty array. An -unsuccesful match is never ignored, but rather always signals the end -of the scanning operation. If the first unsuccessful match takes place -after one or more successful matches have already taken place, the -returned array will contain the results of those successful matches. - -With a block scanf returns a 'map'-like array of transformations from -the block -- that is, an array reflecting what the block did with each -yielded result from the iterative scanf operation. (See "Block -usage", above.) - -==Test suite - -scanf for Ruby includes a suite of unit tests (requiring the -TestUnit package), which can be run with the command ruby -tests/scanftests.rb or the command make test. - -==Current limitations and bugs - -When using IO#scanf under Windows, make sure you open your files in -binary mode: - - File.open("filename", "rb") - -so that scanf can keep track of characters correctly. - -Support for character classes is reasonably complete (since it -essentially piggy-backs on Ruby's regular expression handling of -character classes), but users are advised that character class testing -has not been exhaustive, and that they should exercise some caution -in using any of the more complex and/or arcane character class -idioms. - - -==Technical notes - -===Rationale behind scanf for Ruby - -The impetus for a scanf implementation in Ruby comes chiefly from the fact -that existing pattern matching operations, such as Regexp#match and -String#scan, return all results as strings, which have to be converted to -integers or floats explicitly in cases where what's ultimately wanted are -integer or float values. - -===Design of scanf for Ruby - -scanf for Ruby is essentially a -to- converter. - -When scanf is called, a FormatString object is generated from the -format string ("%d%s...") argument. The FormatString object breaks the -format string down into atoms ("%d", "%5f", "blah", etc.), and from -each atom it creates a FormatSpecifier object, which it -saves. - -Each FormatSpecifier has a regular expression fragment and a "handler" -associated with it. For example, the regular expression fragment -associated with the format "%d" is "([-+]?\d+)", and the handler -associated with it is a wrapper around String#to_i. scanf itself calls -FormatString#match, passing in the input string. FormatString#match -iterates through its FormatSpecifiers; for each one, it matches the -corresponding regular expression fragment against the string. If -there's a match, it sends the matched string to the handler associated -with the FormatSpecifier. - -Thus, to follow up the "%d" example: if "123" occurs in the input -string when a FormatSpecifier consisting of "%d" is reached, the "123" -will be matched against "([-+]?\d+)", and the matched string will be -rendered into an integer by a call to to_i. - -The rendered match is then saved to an accumulator array, and the -input string is reduced to the post-match substring. Thus the string -is "eaten" from the left as the FormatSpecifiers are applied in -sequence. (This is done to a duplicate string; the original string is -not altered.) - -As soon as a regular expression fragment fails to match the string, or -when the FormatString object runs out of FormatSpecifiers, scanning -stops and results accumulated so far are returned in an array. - -==License and copyright - -Copyright:: (c) 2002-2003 David Alan Black -License:: Distributed on the same licensing terms as Ruby itself - -==Warranty disclaimer - -This software is provided "as is" and without any express or implied -warranties, including, without limitation, the implied warranties of -merchantibility and fitness for a particular purpose. - -==Credits and acknowledgements - -scanf for Ruby was developed as the major activity of the Austin -Ruby Codefest (Austin, Texas, August 2002). - -Principal author:: David Alan Black (mailto:dblack@superlink.net) -Co-author:: Hal Fulton (mailto:hal9000@hypermetrics.com) -Project contributors:: Nolan Darilek, Jason Johnston - -Thanks to Hal Fulton for hosting the Codefest. - -Thanks to Matz for suggestions about the class design. - -Thanks to Gavin Sinclair for some feedback on the documentation. - -The text for parts of this document, especially the Description and -Conversions sections, above, were adapted from the Linux Programmer's -Manual manpage for scanf(3), dated 1995-11-01. - -==Bugs and bug reports - -scanf for Ruby is based on something of an amalgam of C scanf -implementations and documentation, rather than on a single canonical -description. Suggestions for features and behaviors which appear in -other scanfs, and would be meaningful in Ruby, are welcome, as are -reports of suspicious behaviors and/or bugs. (Please see "Credits and -acknowledgements", above, for email addresses.) - -=end - -module Scanf - - class FormatSpecifier - - attr_reader :re_string, :matched_string, :conversion, :matched - - private - - def skip; /^\s*%\*/.match(@spec_string); end - - def extract_float(s) - return nil unless s &&! skip - if /\A(?[-+]?)0[xX](?\.\h+|\h+(?:\.\h*)?)[pP](?[-+]\d+)/ =~ s - f1, f2 = frac.split('.') - f = f1.hex - if f2 - len = f2.length - if len > 0 - f += f2.hex / (16.0 ** len) - end - end - (sign == ?- ? -1 : 1) * Math.ldexp(f, exp.to_i) - else - s.to_f - end - end - def extract_decimal(s); s.to_i if s &&! skip; end - def extract_hex(s); s.hex if s &&! skip; end - def extract_octal(s); s.oct if s &&! skip; end - def extract_integer(s); Integer(s) if s &&! skip; end - def extract_plain(s); s unless skip; end - - def nil_proc(s); nil; end - - public - - def to_s - @spec_string - end - - def count_space? - /(?:\A|\S)%\*?\d*c|%\d*\[/.match(@spec_string) - end - - def initialize(str) - @spec_string = str - h = '[A-Fa-f0-9]' - - @re_string, @handler = - case @spec_string - - # %[[:...:]] - when /%\*?(\[\[:[a-z]+:\]\])/ - [ "(#{$1}+)", :extract_plain ] - - # %5[[:...:]] - when /%\*?(\d+)(\[\[:[a-z]+:\]\])/ - [ "(#{$2}{1,#{$1}})", :extract_plain ] - - # %[...] - when /%\*?\[([^\]]*)\]/ - yes = $1 - if /^\^/.match(yes) then no = yes[1..-1] else no = '^' + yes end - [ "([#{yes}]+)(?=[#{no}]|\\z)", :extract_plain ] - - # %5[...] - when /%\*?(\d+)\[([^\]]*)\]/ - yes = $2 - w = $1 - [ "([#{yes}]{1,#{w}})", :extract_plain ] - - # %i - when /%\*?i/ - [ "([-+]?(?:(?:0[0-7]+)|(?:0[Xx]#{h}+)|(?:[1-9]\\d*)))", :extract_integer ] - - # %5i - when /%\*?(\d+)i/ - n = $1.to_i - s = "(" - if n > 1 then s += "[1-9]\\d{1,#{n-1}}|" end - if n > 1 then s += "0[0-7]{1,#{n-1}}|" end - if n > 2 then s += "[-+]0[0-7]{1,#{n-2}}|" end - if n > 2 then s += "[-+][1-9]\\d{1,#{n-2}}|" end - if n > 2 then s += "0[Xx]#{h}{1,#{n-2}}|" end - if n > 3 then s += "[-+]0[Xx]#{h}{1,#{n-3}}|" end - s += "\\d" - s += ")" - [ s, :extract_integer ] - - # %d, %u - when /%\*?[du]/ - [ '([-+]?\d+)', :extract_decimal ] - - # %5d, %5u - when /%\*?(\d+)[du]/ - n = $1.to_i - s = "(" - if n > 1 then s += "[-+]\\d{1,#{n-1}}|" end - s += "\\d{1,#{$1}})" - [ s, :extract_decimal ] - - # %x - when /%\*?[Xx]/ - [ "([-+]?(?:0[Xx])?#{h}+)", :extract_hex ] - - # %5x - when /%\*?(\d+)[Xx]/ - n = $1.to_i - s = "(" - if n > 3 then s += "[-+]0[Xx]#{h}{1,#{n-3}}|" end - if n > 2 then s += "0[Xx]#{h}{1,#{n-2}}|" end - if n > 1 then s += "[-+]#{h}{1,#{n-1}}|" end - s += "#{h}{1,#{n}}" - s += ")" - [ s, :extract_hex ] - - # %o - when /%\*?o/ - [ '([-+]?[0-7]+)', :extract_octal ] - - # %5o - when /%\*?(\d+)o/ - [ "([-+][0-7]{1,#{$1.to_i-1}}|[0-7]{1,#{$1}})", :extract_octal ] - - # %f - when /%\*?[aefgAEFG]/ - [ '([-+]?(?:0[xX](?:\.\h+|\h+(?:\.\h*)?)[pP][-+]\d+|\d+(?![\d.])|\d*\.\d*(?:[eE][-+]?\d+)?))', :extract_float ] - - # %5f - when /%\*?(\d+)[aefgAEFG]/ - [ '(?=[-+]?(?:0[xX](?:\.\h+|\h+(?:\.\h*)?)[pP][-+]\d+|\d+(?![\d.])|\d*\.\d*(?:[eE][-+]?\d+)?))' + - "(\\S{1,#{$1}})", :extract_float ] - - # %5s - when /%\*?(\d+)s/ - [ "(\\S{1,#{$1}})", :extract_plain ] - - # %s - when /%\*?s/ - [ '(\S+)', :extract_plain ] - - # %c - when /\s%\*?c/ - [ "\\s*(.)", :extract_plain ] - - # %c - when /%\*?c/ - [ "(.)", :extract_plain ] - - # %5c (whitespace issues are handled by the count_*_space? methods) - when /%\*?(\d+)c/ - [ "(.{1,#{$1}})", :extract_plain ] - - # %% - when /%%/ - [ '(\s*%)', :nil_proc ] - - # literal characters - else - [ "(#{Regexp.escape(@spec_string)})", :nil_proc ] - end - - @re_string = '\A' + @re_string - end - - def to_re - Regexp.new(@re_string,Regexp::MULTILINE) - end - - def match(str) - @matched = false - s = str.dup - s.sub!(/\A\s+/,'') unless count_space? - res = to_re.match(s) - if res - @conversion = send(@handler, res[1]) - @matched_string = @conversion.to_s - @matched = true - end - res - end - - def letter - @spec_string[/%\*?\d*([a-z\[])/, 1] - end - - def width - w = @spec_string[/%\*?(\d+)/, 1] - w && w.to_i - end - - def mid_match? - return false unless @matched - cc_no_width = letter == '[' &&! width - c_or_cc_width = (letter == 'c' || letter == '[') && width - width_left = c_or_cc_width && (matched_string.size < width) - - return width_left || cc_no_width - end - - end - - class FormatString - - attr_reader :string_left, :last_spec_tried, - :last_match_tried, :matched_count, :space - - SPECIFIERS = 'diuXxofFeEgGscaA' - REGEX = / - # possible space, followed by... - (?:\s* - # percent sign, followed by... - % - # another percent sign, or... - (?:%| - # optional assignment suppression flag - \*? - # optional maximum field width - \d* - # named character class, ... - (?:\[\[:\w+:\]\]| - # traditional character class, or... - \[[^\]]*\]| - # specifier letter. - [#{SPECIFIERS}])))| - # or miscellaneous characters - [^%\s]+/ix - - def initialize(str) - @specs = [] - @i = 1 - s = str.to_s - return unless /\S/.match(s) - @space = true if /\s\z/.match(s) - @specs.replace s.scan(REGEX).map {|spec| FormatSpecifier.new(spec) } - end - - def to_s - @specs.join('') - end - - def prune(n=matched_count) - n.times { @specs.shift } - end - - def spec_count - @specs.size - end - - def last_spec - @i == spec_count - 1 - end - - def match(str) - accum = [] - @string_left = str - @matched_count = 0 - - @specs.each_with_index do |spec,i| - @i=i - @last_spec_tried = spec - @last_match_tried = spec.match(@string_left) - break unless @last_match_tried - @matched_count += 1 - - accum << spec.conversion - - @string_left = @last_match_tried.post_match - break if @string_left.empty? - end - return accum.compact - end - end -end - -class IO - -# The trick here is doing a match where you grab one *line* -# of input at a time. The linebreak may or may not occur -# at the boundary where the string matches a format specifier. -# And if it does, some rule about whitespace may or may not -# be in effect... -# -# That's why this is much more elaborate than the string -# version. -# -# For each line: -# Match succeeds (non-emptily) -# and the last attempted spec/string sub-match succeeded: -# -# could the last spec keep matching? -# yes: save interim results and continue (next line) -# -# The last attempted spec/string did not match: -# -# are we on the next-to-last spec in the string? -# yes: -# is fmt_string.string_left all spaces? -# yes: does current spec care about input space? -# yes: fatal failure -# no: save interim results and continue -# no: continue [this state could be analyzed further] -# -# - - def scanf(str,&b) - return block_scanf(str,&b) if b - return [] unless str.size > 0 - - start_position = pos rescue 0 - matched_so_far = 0 - source_buffer = "" - result_buffer = [] - final_result = [] - - fstr = Scanf::FormatString.new(str) - - loop do - if eof || (tty? &&! fstr.match(source_buffer)) - final_result.concat(result_buffer) - break - end - - source_buffer << gets - - current_match = fstr.match(source_buffer) - - spec = fstr.last_spec_tried - - if spec.matched - if spec.mid_match? - result_buffer.replace(current_match) - next - end - - elsif (fstr.matched_count == fstr.spec_count - 1) - if /\A\s*\z/.match(fstr.string_left) - break if spec.count_space? - result_buffer.replace(current_match) - next - end - end - - final_result.concat(current_match) - - matched_so_far += source_buffer.size - source_buffer.replace(fstr.string_left) - matched_so_far -= source_buffer.size - break if fstr.last_spec - fstr.prune - end - seek(start_position + matched_so_far, IO::SEEK_SET) rescue Errno::ESPIPE - soak_up_spaces if fstr.last_spec && fstr.space - - return final_result - end - - private - - def soak_up_spaces - c = getc - ungetc(c) if c - until eof ||! c || /\S/.match(c.chr) - c = getc - end - ungetc(c) if (c && /\S/.match(c.chr)) - end - - def block_scanf(str) - final = [] -# Sub-ideal, since another FS gets created in scanf. -# But used here to determine the number of specifiers. - fstr = Scanf::FormatString.new(str) - last_spec = fstr.last_spec - begin - current = scanf(str) - break if current.empty? - final.push(yield(current)) - end until eof || fstr.last_spec_tried == last_spec - return final - end -end - -class String - - def scanf(fstr,&b) - if b - block_scanf(fstr,&b) - else - fs = - if fstr.is_a? Scanf::FormatString - fstr - else - Scanf::FormatString.new(fstr) - end - fs.match(self) - end - end - - def block_scanf(fstr,&b) - fs = Scanf::FormatString.new(fstr) - str = self.dup - final = [] - begin - current = str.scanf(fs) - final.push(yield(current)) unless current.empty? - str = fs.string_left - end until current.empty? || str.empty? - return final - end -end - -module Kernel - private - def scanf(fs,&b) - STDIN.scanf(fs,&b) - end -end diff --git a/Src/StdLib/ruby/1.9.1/shell.rb b/Src/StdLib/ruby/1.9.1/shell.rb deleted file mode 100644 index f838a542c..000000000 --- a/Src/StdLib/ruby/1.9.1/shell.rb +++ /dev/null @@ -1,300 +0,0 @@ -# -# shell.rb - -# $Release Version: 0.7 $ -# $Revision: 1.9 $ -# by Keiju ISHITSUKA(keiju@ruby-lang.org) -# -# -- -# -# -# - -require "e2mmap" - -require "thread" unless defined?(Mutex) - -require "forwardable" - -require "shell/error" -require "shell/command-processor" -require "shell/process-controller" - -class Shell - @RCS_ID='-$Id: shell.rb,v 1.9 2002/03/04 12:01:10 keiju Exp keiju $-' - - include Error - extend Exception2MessageMapper - -# @cascade = true - # debug: true -> normal debug - # debug: 1 -> eval definition debug - # debug: 2 -> detail inspect debug - @debug = false - @verbose = true - - @debug_display_process_id = false - @debug_display_thread_id = true - @debug_output_mutex = Mutex.new - - class << Shell - extend Forwardable - - attr_accessor :cascade, :debug, :verbose - -# alias cascade? cascade - alias debug? debug - alias verbose? verbose - @verbose = true - - def debug=(val) - @debug = val - @verbose = val if val - end - - def cd(path) - new(path) - end - - def default_system_path - if @default_system_path - @default_system_path - else - ENV["PATH"].split(":") - end - end - - def default_system_path=(path) - @default_system_path = path - end - - def default_record_separator - if @default_record_separator - @default_record_separator - else - $/ - end - end - - def default_record_separator=(rs) - @default_record_separator = rs - end - - # os resource mutex - mutex_methods = ["unlock", "lock", "locked?", "synchronize", "try_lock", "exclusive_unlock"] - for m in mutex_methods - def_delegator("@debug_output_mutex", m, "debug_output_"+m.to_s) - end - - end - - def initialize(pwd = Dir.pwd, umask = nil) - @cwd = File.expand_path(pwd) - @dir_stack = [] - @umask = umask - - @system_path = Shell.default_system_path - @record_separator = Shell.default_record_separator - - @command_processor = CommandProcessor.new(self) - @process_controller = ProcessController.new(self) - - @verbose = Shell.verbose - @debug = Shell.debug - end - - attr_reader :system_path - - def system_path=(path) - @system_path = path - rehash - end - - attr_accessor :umask, :record_separator - attr_accessor :verbose, :debug - - def debug=(val) - @debug = val - @verbose = val if val - end - - alias verbose? verbose - alias debug? debug - - attr_reader :command_processor - attr_reader :process_controller - - def expand_path(path) - File.expand_path(path, @cwd) - end - - # Most Shell commands are defined via CommandProcessor - - # - # Dir related methods - # - # Shell#cwd/dir/getwd/pwd - # Shell#chdir/cd - # Shell#pushdir/pushd - # Shell#popdir/popd - # Shell#mkdir - # Shell#rmdir - - attr_reader :cwd - alias dir cwd - alias getwd cwd - alias pwd cwd - - attr_reader :dir_stack - alias dirs dir_stack - - # If called as iterator, it restores the current directory when the - # block ends. - def chdir(path = nil, verbose = @verbose) - check_point - - if iterator? - notify("chdir(with block) #{path}") if verbose - cwd_old = @cwd - begin - chdir(path, nil) - yield - ensure - chdir(cwd_old, nil) - end - else - notify("chdir #{path}") if verbose - path = "~" unless path - @cwd = expand_path(path) - notify "current dir: #{@cwd}" - rehash - Void.new(self) - end - end - alias cd chdir - - def pushdir(path = nil, verbose = @verbose) - check_point - - if iterator? - notify("pushdir(with block) #{path}") if verbose - pushdir(path, nil) - begin - yield - ensure - popdir - end - elsif path - notify("pushdir #{path}") if verbose - @dir_stack.push @cwd - chdir(path, nil) - notify "dir stack: [#{@dir_stack.join ', '}]" - self - else - notify("pushdir") if verbose - if pop = @dir_stack.pop - @dir_stack.push @cwd - chdir pop - notify "dir stack: [#{@dir_stack.join ', '}]" - self - else - Shell.Fail DirStackEmpty - end - end - Void.new(self) - end - alias pushd pushdir - - def popdir - check_point - - notify("popdir") - if pop = @dir_stack.pop - chdir pop - notify "dir stack: [#{@dir_stack.join ', '}]" - self - else - Shell.Fail DirStackEmpty - end - Void.new(self) - end - alias popd popdir - - # - # process management - # - def jobs - @process_controller.jobs - end - - def kill(sig, command) - @process_controller.kill_job(sig, command) - end - - # - # command definitions - # - def Shell.def_system_command(command, path = command) - CommandProcessor.def_system_command(command, path) - end - - def Shell.undef_system_command(command) - CommandProcessor.undef_system_command(command) - end - - def Shell.alias_command(ali, command, *opts, &block) - CommandProcessor.alias_command(ali, command, *opts, &block) - end - - def Shell.unalias_command(ali) - CommandProcessor.unalias_command(ali) - end - - def Shell.install_system_commands(pre = "sys_") - CommandProcessor.install_system_commands(pre) - end - - # - def inspect - if debug.kind_of?(Integer) && debug > 2 - super - else - to_s - end - end - - def self.notify(*opts, &block) - Shell::debug_output_synchronize do - if opts[-1].kind_of?(String) - yorn = verbose? - else - yorn = opts.pop - end - return unless yorn - - if @debug_display_thread_id - if @debug_display_process_id - prefix = "shell(##{Process.pid}:#{Thread.current.to_s.sub("Thread", "Th")}): " - else - prefix = "shell(#{Thread.current.to_s.sub("Thread", "Th")}): " - end - else - prefix = "shell: " - end - _head = true - STDERR.print opts.collect{|mes| - mes = mes.dup - yield mes if iterator? - if _head - _head = false -# "shell" " + mes - prefix + mes - else - " "* prefix.size + mes - end - }.join("\n")+"\n" - end - end - - CommandProcessor.initialize - CommandProcessor.run_config -end diff --git a/Src/StdLib/ruby/1.9.1/shell/builtin-command.rb b/Src/StdLib/ruby/1.9.1/shell/builtin-command.rb deleted file mode 100644 index 563e4241a..000000000 --- a/Src/StdLib/ruby/1.9.1/shell/builtin-command.rb +++ /dev/null @@ -1,160 +0,0 @@ -# -# shell/builtin-command.rb - -# $Release Version: 0.7 $ -# $Revision: 25189 $ -# by Keiju ISHITSUKA(keiju@ruby-lang.org) -# -# -- -# -# -# - -require "shell/filter" - -class Shell - class BuiltInCommand - # - def expand_path(path) - @shell.expand_path(path) - end - - # - # File related commands - # Shell#foreach - # Shell#open - # Shell#unlink - # Shell#test - # - # - - # - # CommandProcessor#foreach(path, rs) - # path: String - # rs: String - record separator - # iterator - # Same as: - # File#foreach (when path is file) - # Dir#foreach (when path is directory) - # path is relative to pwd - # - def foreach(path = nil, *rs) - path = "." unless path - path = expand_path(path) - - if File.directory?(path) - Dir.foreach(path){|fn| yield fn} - else - IO.foreach(path, *rs){|l| yield l} - end - end - - # - # CommandProcessor#open(path, mode) - # path: String - # mode: String - # return: File or Dir - # Same as: - # File#open (when path is file) - # Dir#open (when path is directory) - # mode has an effect only when path is a file - # - def open(path, mode = nil, perm = 0666, &b) - path = expand_path(path) - if File.directory?(path) - Dir.open(path, &b) - else - if @shell.umask - f = File.open(path, mode, perm) - File.chmod(perm & ~@shell.umask, path) - if block_given? - f.each(&b) - end - f - else - f = File.open(path, mode, perm, &b) - end - end - end - # public :open - - # - # CommandProcessor#unlink(path) - # same as: - # Dir#unlink (when path is directory) - # File#unlink (when path is file) - # - def unlink(path) - @shell.check_point - - path = expand_path(path) - if File.directory?(path) - Dir.unlink(path) - else - IO.unlink(path) - end - Void.new(@shell) - end - - # - # CommandProcessor#test(command, file1, file2) - # CommandProcessor#[command, file1, file2] - # command: char or String or Symbol - # file1: String - # file2: String(optional) - # return: Boolean - # same as: - # test() (when command is char or length 1 string or symbol) - # FileTest.command (others) - # example: - # sh[?e, "foo"] - # sh[:e, "foo"] - # sh["e", "foo"] - # sh[:exists?, "foo"] - # sh["exists?", "foo"] - # - alias top_level_test test - def test(command, file1, file2=nil) - file1 = expand_path(file1) - file2 = expand_path(file2) if file2 - command = command.id2name if command.kind_of?(Symbol) - - case command - when Integer - if file2 - top_level_test(command, file1, file2) - else - top_level_test(command, file1) - end - when String - if command.size == 1 - if file2 - top_level_test(command, file1, file2) - else - top_level_test(command, file1) - end - else - if file2 - FileTest.send(command, file1, file2) - else - FileTest.send(command, file1) - end - end - end - end - alias [] test - - # - # Dir related methods - # - # Shell#mkdir - # Shell#rmdir - # - #-- - # - # CommandProcessor#mkdir(*path) - # path: String - # same as Dir.mkdir() - # - def mkdir(*path) - @shell.check_point - notify("mkdir #{path.join(' ')}") - - perm = nil - if path.last.kind_of?(Integer) - perm = path.pop - end - for dir in path - d = expand_path(dir) - if perm - Dir.mkdir(d, perm) - else - Dir.mkdir(d) - end - File.chmod(d, 0666 & ~@shell.umask) if @shell.umask - end - Void.new(@shell) - end - - # - # CommandProcessor#rmdir(*path) - # path: String - # same as Dir.rmdir() - # - def rmdir(*path) - @shell.check_point - notify("rmdir #{path.join(' ')}") - - for dir in path - Dir.rmdir(expand_path(dir)) - end - Void.new(@shell) - end - - # - # CommandProcessor#system(command, *opts) - # command: String - # opts: String - # return: SystemCommand - # Same as system() function - # example: - # print sh.system("ls", "-l") - # sh.system("ls", "-l") | sh.head > STDOUT - # - def system(command, *opts) - if opts.empty? - if command =~ /\*|\?|\{|\}|\[|\]|<|>|\(|\)|~|&|\||\\|\$|;|'|`|"|\n/ - return SystemCommand.new(@shell, find_system_command("sh"), "-c", command) - else - command, *opts = command.split(/\s+/) - end - end - SystemCommand.new(@shell, find_system_command(command), *opts) - end - - # - # ProcessCommand#rehash - # clear command hash table. - # - def rehash - @system_commands = {} - end - - # - # ProcessCommand#transact - # - def check_point - @shell.process_controller.wait_all_jobs_execution - end - alias finish_all_jobs check_point - - def transact(&block) - begin - @shell.instance_eval(&block) - ensure - check_point - end - end - - # - # internal commands - # - def out(dev = STDOUT, &block) - dev.print transact(&block) - end - - def echo(*strings) - Echo.new(@shell, *strings) - end - - def cat(*filenames) - Cat.new(@shell, *filenames) - end - - # def sort(*filenames) - # Sort.new(self, *filenames) - # end - - def glob(pattern) - Glob.new(@shell, pattern) - end - - def append(to, filter) - case to - when String - AppendFile.new(@shell, to, filter) - when IO - AppendIO.new(@shell, to, filter) - else - Shell.Fail Error::CantApplyMethod, "append", to.class - end - end - - def tee(file) - Tee.new(@shell, file) - end - - def concat(*jobs) - Concat.new(@shell, *jobs) - end - - # %pwd, %cwd -> @pwd - def notify(*opts, &block) - Shell.notify(*opts) {|mes| - yield mes if iterator? - - mes.gsub!("%pwd", "#{@cwd}") - mes.gsub!("%cwd", "#{@cwd}") - } - end - - # - # private functions - # - def find_system_command(command) - return command if /^\// =~ command - case path = @system_commands[command] - when String - if exists?(path) - return path - else - Shell.Fail Error::CommandNotFound, command - end - when false - Shell.Fail Error::CommandNotFound, command - end - - for p in @shell.system_path - path = join(p, command) - if FileTest.exist?(path) - @system_commands[command] = path - return path - end - end - @system_commands[command] = false - Shell.Fail Error::CommandNotFound, command - end - - # - # CommandProcessor.def_system_command(command, path) - # command: String - # path: String - # define 'command()' method as method. - # - def self.def_system_command(command, path = command) - begin - eval((d = %Q[def #{command}(*opts) - SystemCommand.new(@shell, '#{path}', *opts) - end]), nil, __FILE__, __LINE__ - 1) - rescue SyntaxError - Shell.notify "warn: Can't define #{command} path: #{path}." - end - Shell.notify "Define #{command} path: #{path}.", Shell.debug? - Shell.notify("Definition of #{command}: ", d, - Shell.debug.kind_of?(Integer) && Shell.debug > 1) - end - - def self.undef_system_command(command) - command = command.id2name if command.kind_of?(Symbol) - remove_method(command) - Shell.module_eval{remove_method(command)} - Filter.module_eval{remove_method(command)} - self - end - - # define command alias - # ex) - # def_alias_command("ls_c", "ls", "-C", "-F") - # def_alias_command("ls_c", "ls"){|*opts| ["-C", "-F", *opts]} - # - @alias_map = {} - def self.alias_map - @alias_map - end - def self.alias_command(ali, command, *opts, &block) - ali = ali.id2name if ali.kind_of?(Symbol) - command = command.id2name if command.kind_of?(Symbol) - begin - if iterator? - @alias_map[ali.intern] = proc - - eval((d = %Q[def #{ali}(*opts) - @shell.__send__(:#{command}, - *(CommandProcessor.alias_map[:#{ali}].call *opts)) - end]), nil, __FILE__, __LINE__ - 1) - - else - args = opts.collect{|opt| '"' + opt + '"'}.join(",") - eval((d = %Q[def #{ali}(*opts) - @shell.__send__(:#{command}, #{args}, *opts) - end]), nil, __FILE__, __LINE__ - 1) - end - rescue SyntaxError - Shell.notify "warn: Can't alias #{ali} command: #{command}." - Shell.notify("Definition of #{ali}: ", d) - raise - end - Shell.notify "Define #{ali} command: #{command}.", Shell.debug? - Shell.notify("Definition of #{ali}: ", d, - Shell.debug.kind_of?(Integer) && Shell.debug > 1) - self - end - - def self.unalias_command(ali) - ali = ali.id2name if ali.kind_of?(Symbol) - @alias_map.delete ali.intern - undef_system_command(ali) - end - - # - # CommandProcessor.def_builtin_commands(delegation_class, command_specs) - # delegation_class: Class or Module - # command_specs: [[command_name, [argument,...]],...] - # command_name: String - # arguments: String - # FILENAME?? -> expand_path(filename??) - # *FILENAME?? -> filename??.collect{|f|expand_path(f)}.join(", ") - # define command_name(argument,...) as - # delegation_class.command_name(argument,...) - # - def self.def_builtin_commands(delegation_class, command_specs) - for meth, args in command_specs - arg_str = args.collect{|arg| arg.downcase}.join(", ") - call_arg_str = args.collect{ - |arg| - case arg - when /^(FILENAME.*)$/ - format("expand_path(%s)", $1.downcase) - when /^(\*FILENAME.*)$/ - # \*FILENAME* -> filenames.collect{|fn| expand_path(fn)}.join(", ") - $1.downcase + '.collect{|fn| expand_path(fn)}' - else - arg - end - }.join(", ") - d = %Q[def #{meth}(#{arg_str}) - #{delegation_class}.#{meth}(#{call_arg_str}) - end] - Shell.notify "Define #{meth}(#{arg_str})", Shell.debug? - Shell.notify("Definition of #{meth}: ", d, - Shell.debug.kind_of?(Integer) && Shell.debug > 1) - eval d - end - end - - # - # CommandProcessor.install_system_commands(pre) - # pre: String - command name prefix - # defines every command which belongs in default_system_path via - # CommandProcessor.command(). It doesn't define already defined - # methods twice. By default, "pre_" is prefixes to each method - # name. Characters that may not be used in a method name are - # all converted to '_'. Definition errors are just ignored. - # - def self.install_system_commands(pre = "sys_") - defined_meth = {} - for m in Shell.methods - defined_meth[m] = true - end - sh = Shell.new - for path in Shell.default_system_path - next unless sh.directory? path - sh.cd path - sh.foreach do - |cn| - if !defined_meth[pre + cn] && sh.file?(cn) && sh.executable?(cn) - command = (pre + cn).gsub(/\W/, "_").sub(/^([0-9])/, '_\1') - begin - def_system_command(command, sh.expand_path(cn)) - rescue - Shell.notify "warn: Can't define #{command} path: #{cn}" - end - defined_meth[command] = command - end - end - end - end - - #---------------------------------------------------------------------- - # - # class initializing methods - - # - #---------------------------------------------------------------------- - def self.add_delegate_command_to_shell(id) - id = id.intern if id.kind_of?(String) - name = id.id2name - if Shell.method_defined?(id) - Shell.notify "warn: override definition of Shell##{name}." - Shell.notify "warn: alias Shell##{name} to Shell##{name}_org.\n" - Shell.module_eval "alias #{name}_org #{name}" - end - Shell.notify "method added: Shell##{name}.", Shell.debug? - Shell.module_eval(%Q[def #{name}(*args, &block) - begin - @command_processor.__send__(:#{name}, *args, &block) - rescue Exception - $@.delete_if{|s| /:in `__getobj__'$/ =~ s} #` - $@.delete_if{|s| /^\\(eval\\):/ =~ s} - raise - end - end], __FILE__, __LINE__) - - if Shell::Filter.method_defined?(id) - Shell.notify "warn: override definition of Shell::Filter##{name}." - Shell.notify "warn: alias Shell##{name} to Shell::Filter##{name}_org." - Filter.module_eval "alias #{name}_org #{name}" - end - Shell.notify "method added: Shell::Filter##{name}.", Shell.debug? - Filter.module_eval(%Q[def #{name}(*args, &block) - begin - self | @shell.__send__(:#{name}, *args, &block) - rescue Exception - $@.delete_if{|s| /:in `__getobj__'$/ =~ s} #` - $@.delete_if{|s| /^\\(eval\\):/ =~ s} - raise - end - end], __FILE__, __LINE__) - end - - # - # define default builtin commands - # - def self.install_builtin_commands - # method related File. - # (exclude open/foreach/unlink) - normal_delegation_file_methods = [ - ["atime", ["FILENAME"]], - ["basename", ["fn", "*opts"]], - ["chmod", ["mode", "*FILENAMES"]], - ["chown", ["owner", "group", "*FILENAME"]], - ["ctime", ["FILENAMES"]], - ["delete", ["*FILENAMES"]], - ["dirname", ["FILENAME"]], - ["ftype", ["FILENAME"]], - ["join", ["*items"]], - ["link", ["FILENAME_O", "FILENAME_N"]], - ["lstat", ["FILENAME"]], - ["mtime", ["FILENAME"]], - ["readlink", ["FILENAME"]], - ["rename", ["FILENAME_FROM", "FILENAME_TO"]], - # ["size", ["FILENAME"]], - ["split", ["pathname"]], - ["stat", ["FILENAME"]], - ["symlink", ["FILENAME_O", "FILENAME_N"]], - ["truncate", ["FILENAME", "length"]], - ["utime", ["atime", "mtime", "*FILENAMES"]]] - - def_builtin_commands(File, normal_delegation_file_methods) - alias_method :rm, :delete - - # method related FileTest - def_builtin_commands(FileTest, - FileTest.singleton_methods(false).collect{|m| [m, ["FILENAME"]]}) - - end - - end -end diff --git a/Src/StdLib/ruby/1.9.1/shell/error.rb b/Src/StdLib/ruby/1.9.1/shell/error.rb deleted file mode 100644 index d2e858df8..000000000 --- a/Src/StdLib/ruby/1.9.1/shell/error.rb +++ /dev/null @@ -1,25 +0,0 @@ -# -# shell/error.rb - -# $Release Version: 0.7 $ -# $Revision: 25189 $ -# by Keiju ISHITSUKA(keiju@ruby-lang.org) -# -# -- -# -# -# - -require "e2mmap" - -class Shell - module Error - extend Exception2MessageMapper - def_e2message TypeError, "wrong argument type %s (expected %s)" - - def_exception :DirStackEmpty, "Directory stack empty." - def_exception :CantDefine, "Can't define method(%s, %s)." - def_exception :CantApplyMethod, "This method(%s) does not apply to this type(%s)." - def_exception :CommandNotFound, "Command not found(%s)." - end -end - diff --git a/Src/StdLib/ruby/1.9.1/shell/filter.rb b/Src/StdLib/ruby/1.9.1/shell/filter.rb deleted file mode 100644 index 7438a7545..000000000 --- a/Src/StdLib/ruby/1.9.1/shell/filter.rb +++ /dev/null @@ -1,109 +0,0 @@ -# -# shell/filter.rb - -# $Release Version: 0.7 $ -# $Revision: 25189 $ -# by Keiju ISHITSUKA(keiju@ruby-lang.org) -# -# -- -# -# -# - -class Shell - # - # Filter - # A method to require - # each() - # - class Filter - include Enumerable - - def initialize(sh) - @shell = sh # parent shell - @input = nil # input filter - end - - attr_reader :input - - def input=(filter) - @input = filter - end - - def each(rs = nil) - rs = @shell.record_separator unless rs - if @input - @input.each(rs){|l| yield l} - end - end - - def < (src) - case src - when String - cat = Cat.new(@shell, src) - cat | self - when IO - self.input = src - self - else - Shell.Fail Error::CantApplyMethod, "<", to.class - end - end - - def > (to) - case to - when String - dst = @shell.open(to, "w") - begin - each(){|l| dst << l} - ensure - dst.close - end - when IO - each(){|l| to << l} - else - Shell.Fail Error::CantApplyMethod, ">", to.class - end - self - end - - def >> (to) - begin - Shell.cd(@shell.pwd).append(to, self) - rescue CantApplyMethod - Shell.Fail Error::CantApplyMethod, ">>", to.class - end - end - - def | (filter) - filter.input = self - if active? - @shell.process_controller.start_job filter - end - filter - end - - def + (filter) - Join.new(@shell, self, filter) - end - - def to_a - ary = [] - each(){|l| ary.push l} - ary - end - - def to_s - str = "" - each(){|l| str.concat l} - str - end - - def inspect - if @shell.debug.kind_of?(Integer) && @shell.debug > 2 - super - else - to_s - end - end - end -end diff --git a/Src/StdLib/ruby/1.9.1/shell/process-controller.rb b/Src/StdLib/ruby/1.9.1/shell/process-controller.rb deleted file mode 100644 index 5cb711646..000000000 --- a/Src/StdLib/ruby/1.9.1/shell/process-controller.rb +++ /dev/null @@ -1,319 +0,0 @@ -# -# shell/process-controller.rb - -# $Release Version: 0.7 $ -# $Revision: 27967 $ -# by Keiju ISHITSUKA(keiju@ruby-lang.org) -# -# -- -# -# -# -require "forwardable" - -require "thread" -require "sync" - -class Shell - class ProcessController - - @ProcessControllers = {} - @ProcessControllersMonitor = Mutex.new - @ProcessControllersCV = ConditionVariable.new - - @BlockOutputMonitor = Mutex.new - @BlockOutputCV = ConditionVariable.new - - class << self - extend Forwardable - - def_delegator("@ProcessControllersMonitor", - "synchronize", "process_controllers_exclusive") - - def active_process_controllers - process_controllers_exclusive do - @ProcessControllers.dup - end - end - - def activate(pc) - process_controllers_exclusive do - @ProcessControllers[pc] ||= 0 - @ProcessControllers[pc] += 1 - end - end - - def inactivate(pc) - process_controllers_exclusive do - if @ProcessControllers[pc] - if (@ProcessControllers[pc] -= 1) == 0 - @ProcessControllers.delete(pc) - @ProcessControllersCV.signal - end - end - end - end - - def each_active_object - process_controllers_exclusive do - for ref in @ProcessControllers.keys - yield ref - end - end - end - - def block_output_synchronize(&b) - @BlockOutputMonitor.synchronize(&b) - end - - def wait_to_finish_all_process_controllers - process_controllers_exclusive do - while !@ProcessControllers.empty? - Shell::notify("Process finishing, but active shell exists", - "You can use Shell#transact or Shell#check_point for more safe execution.") - if Shell.debug? - for pc in @ProcessControllers.keys - Shell::notify(" Not finished jobs in "+pc.shell.to_s) - for com in pc.jobs - com.notify(" Jobs: %id") - end - end - end - @ProcessControllersCV.wait(@ProcessControllersMonitor) - end - end - end - end - - # for shell-command complete finish at this process exit. - USING_AT_EXIT_WHEN_PROCESS_EXIT = true - at_exit do - wait_to_finish_all_process_controllers unless $@ - end - - def initialize(shell) - @shell = shell - @waiting_jobs = [] - @active_jobs = [] - @jobs_sync = Sync.new - - @job_monitor = Mutex.new - @job_condition = ConditionVariable.new - end - - attr_reader :shell - - def jobs - jobs = [] - @jobs_sync.synchronize(:SH) do - jobs.concat @waiting_jobs - jobs.concat @active_jobs - end - jobs - end - - def active_jobs - @active_jobs - end - - def waiting_jobs - @waiting_jobs - end - - def jobs_exist? - @jobs_sync.synchronize(:SH) do - @active_jobs.empty? or @waiting_jobs.empty? - end - end - - def active_jobs_exist? - @jobs_sync.synchronize(:SH) do - @active_jobs.empty? - end - end - - def waiting_jobs_exist? - @jobs_sync.synchronize(:SH) do - @waiting_jobs.empty? - end - end - - # schedule a command - def add_schedule(command) - @jobs_sync.synchronize(:EX) do - ProcessController.activate(self) - if @active_jobs.empty? - start_job command - else - @waiting_jobs.push(command) - end - end - end - - # start a job - def start_job(command = nil) - @jobs_sync.synchronize(:EX) do - if command - return if command.active? - @waiting_jobs.delete command - else - command = @waiting_jobs.shift -# command.notify "job(%id) pre-start.", @shell.debug? - - return unless command - end - @active_jobs.push command - command.start -# command.notify "job(%id) post-start.", @shell.debug? - - # start all jobs that input from the job - for job in @waiting_jobs.dup - start_job(job) if job.input == command - end -# command.notify "job(%id) post2-start.", @shell.debug? - end - end - - def waiting_job?(job) - @jobs_sync.synchronize(:SH) do - @waiting_jobs.include?(job) - end - end - - def active_job?(job) - @jobs_sync.synchronize(:SH) do - @active_jobs.include?(job) - end - end - - # terminate a job - def terminate_job(command) - @jobs_sync.synchronize(:EX) do - @active_jobs.delete command - ProcessController.inactivate(self) - if @active_jobs.empty? - command.notify("start_job in terminate_job(%id)", Shell::debug?) - start_job - end - end - end - - # kill a job - def kill_job(sig, command) - @jobs_sync.synchronize(:EX) do - if @waiting_jobs.delete command - ProcessController.inactivate(self) - return - elsif @active_jobs.include?(command) - begin - r = command.kill(sig) - ProcessController.inactivate(self) - rescue - print "Shell: Warn: $!\n" if @shell.verbose? - return nil - end - @active_jobs.delete command - r - end - end - end - - # wait for all jobs to terminate - def wait_all_jobs_execution - @job_monitor.synchronize do - begin - while !jobs.empty? - @job_condition.wait(@job_monitor) - for job in jobs - job.notify("waiting job(%id)", Shell::debug?) - end - end - ensure - redo unless jobs.empty? - end - end - end - - # simple fork - def sfork(command, &block) - pipe_me_in, pipe_peer_out = IO.pipe - pipe_peer_in, pipe_me_out = IO.pipe - - - pid = nil - pid_mutex = Mutex.new - pid_cv = ConditionVariable.new - - Thread.start do - ProcessController.block_output_synchronize do - STDOUT.flush - ProcessController.each_active_object do |pc| - for jobs in pc.active_jobs - jobs.flush - end - end - - pid = fork { - Thread.list.each do |th| -# th.kill unless [Thread.main, Thread.current].include?(th) - th.kill unless Thread.current == th - end - - STDIN.reopen(pipe_peer_in) - STDOUT.reopen(pipe_peer_out) - - ObjectSpace.each_object(IO) do |io| - if ![STDIN, STDOUT, STDERR].include?(io) - io.close unless io.closed? - end - end - - yield - } - end - pid_cv.signal - - pipe_peer_in.close - pipe_peer_out.close - command.notify "job(%name:##{pid}) start", @shell.debug? - - begin - _pid = nil - command.notify("job(%id) start to waiting finish.", @shell.debug?) - _pid = Process.waitpid(pid, nil) - rescue Errno::ECHILD - command.notify "warn: job(%id) was done already waitpid." - _pid = true - # rescue - # STDERR.puts $! - ensure - command.notify("Job(%id): Wait to finish when Process finished.", @shell.debug?) - # when the process ends, wait until the command terminates - if USING_AT_EXIT_WHEN_PROCESS_EXIT or _pid - else - command.notify("notice: Process finishing...", - "wait for Job[%id] to finish.", - "You can use Shell#transact or Shell#check_point for more safe execution.") - redo - end - -# command.notify "job(%id) pre-pre-finish.", @shell.debug? - @job_monitor.synchronize do -# command.notify "job(%id) pre-finish.", @shell.debug? - terminate_job(command) -# command.notify "job(%id) pre-finish2.", @shell.debug? - @job_condition.signal - command.notify "job(%id) finish.", @shell.debug? - end - end - end - - pid_mutex.synchronize do - while !pid - pid_cv.wait(pid_mutex) - end - end - - return pid, pipe_me_in, pipe_me_out - end - end -end diff --git a/Src/StdLib/ruby/1.9.1/shell/system-command.rb b/Src/StdLib/ruby/1.9.1/shell/system-command.rb deleted file mode 100644 index 6b1f3d870..000000000 --- a/Src/StdLib/ruby/1.9.1/shell/system-command.rb +++ /dev/null @@ -1,159 +0,0 @@ -# -# shell/system-command.rb - -# $Release Version: 0.7 $ -# $Revision: 25189 $ -# by Keiju ISHITSUKA(keiju@ruby-lang.org) -# -# -- -# -# -# - -require "shell/filter" - -class Shell - class SystemCommand < Filter - def initialize(sh, command, *opts) - if t = opts.find{|opt| !opt.kind_of?(String) && opt.class} - Shell.Fail Error::TypeError, t.class, "String" - end - super(sh) - @command = command - @opts = opts - - @input_queue = Queue.new - @pid = nil - - sh.process_controller.add_schedule(self) - end - - attr_reader :command - alias name command - - def wait? - @shell.process_controller.waiting_job?(self) - end - - def active? - @shell.process_controller.active_job?(self) - end - - def input=(inp) - super - if active? - start_export - end - end - - def start - notify([@command, *@opts].join(" ")) - - @pid, @pipe_in, @pipe_out = @shell.process_controller.sfork(self) { - Dir.chdir @shell.pwd - $0 = @command - exec(@command, *@opts) - } - if @input - start_export - end - start_import - end - - def flush - @pipe_out.flush if @pipe_out and !@pipe_out.closed? - end - - def terminate - begin - @pipe_in.close - rescue IOError - end - begin - @pipe_out.close - rescue IOError - end - end - - def kill(sig) - if @pid - Process.kill(sig, @pid) - end - end - - def start_import - notify "Job(%id) start imp-pipe.", @shell.debug? - rs = @shell.record_separator unless rs - _eop = true - th = Thread.start { - begin - while l = @pipe_in.gets - @input_queue.push l - end - _eop = false - rescue Errno::EPIPE - _eop = false - ensure - if !ProcessController::USING_AT_EXIT_WHEN_PROCESS_EXIT and _eop - notify("warn: Process finishing...", - "wait for Job[%id] to finish pipe importing.", - "You can use Shell#transact or Shell#check_point for more safe execution.") - redo - end - notify "job(%id}) close imp-pipe.", @shell.debug? - @input_queue.push :EOF - @pipe_in.close - end - } - end - - def start_export - notify "job(%id) start exp-pipe.", @shell.debug? - _eop = true - th = Thread.start{ - begin - @input.each do |l| - ProcessController::block_output_synchronize do - @pipe_out.print l - end - end - _eop = false - rescue Errno::EPIPE, Errno::EIO - _eop = false - ensure - if !ProcessController::USING_AT_EXIT_WHEN_PROCESS_EXIT and _eop - notify("shell: warn: Process finishing...", - "wait for Job(%id) to finish pipe exporting.", - "You can use Shell#transact or Shell#check_point for more safe execution.") - redo - end - notify "job(%id) close exp-pipe.", @shell.debug? - @pipe_out.close - end - } - end - - alias super_each each - def each(rs = nil) - while (l = @input_queue.pop) != :EOF - yield l - end - end - - # ex) - # if you wish to output: - # "shell: job(#{@command}:#{@pid}) close pipe-out." - # then - # mes: "job(%id) close pipe-out." - # yorn: Boolean(@shell.debug? or @shell.verbose?) - def notify(*opts, &block) - @shell.notify(*opts) do |mes| - yield mes if iterator? - - mes.gsub!("%id", "#{@command}:##{@pid}") - mes.gsub!("%name", "#{@command}") - mes.gsub!("%pid", "#{@pid}") - mes - end - end - end -end diff --git a/Src/StdLib/ruby/1.9.1/shell/version.rb b/Src/StdLib/ruby/1.9.1/shell/version.rb deleted file mode 100644 index c597d7afd..000000000 --- a/Src/StdLib/ruby/1.9.1/shell/version.rb +++ /dev/null @@ -1,15 +0,0 @@ -# -# version.rb - shell version definition file -# $Release Version: 0.7$ -# $Revision: 25189 $ -# by Keiju ISHITSUKA(keiju@ruby-lang.org) -# -# -- -# -# -# - -class Shell - @RELEASE_VERSION = "0.7" - @LAST_UPDATE_DATE = "07/03/20" -end diff --git a/Src/StdLib/ruby/1.9.1/syck.rb b/Src/StdLib/ruby/1.9.1/syck.rb deleted file mode 100644 index a207cf696..000000000 --- a/Src/StdLib/ruby/1.9.1/syck.rb +++ /dev/null @@ -1,447 +0,0 @@ -# -*- mode: ruby; ruby-indent-level: 4; tab-width: 4 -*- vim: sw=4 ts=4 -# $Id: syck.rb 27334 2010-04-14 02:37:54Z nobu $ -# -# = yaml.rb: top-level module with methods for loading and parsing YAML documents -# -# Author:: why the lucky stiff -# - -require 'yaml/syck' - -# == YAML -# -# YAML(tm) (rhymes with 'camel') is a -# straightforward machine parsable data serialization format designed for -# human readability and interaction with scripting languages such as Perl -# and Python. YAML is optimized for data serialization, formatted -# dumping, configuration files, log files, Internet messaging and -# filtering. This specification describes the YAML information model and -# serialization format. Together with the Unicode standard for characters, it -# provides all the information necessary to understand YAML Version 1.0 -# and construct computer programs to process it. -# -# See http://yaml.org/ for more information. For a quick tutorial, please -# visit YAML In Five Minutes (http://yaml.kwiki.org/?YamlInFiveMinutes). -# -# == About This Library -# -# The YAML 1.0 specification outlines four stages of YAML loading and dumping. -# This library honors all four of those stages, although data is really only -# available to you in three stages. -# -# The four stages are: native, representation, serialization, and presentation. -# -# The native stage refers to data which has been loaded completely into Ruby's -# own types. (See +YAML::load+.) -# -# The representation stage means data which has been composed into -# +YAML::BaseNode+ objects. In this stage, the document is available as a -# tree of node objects. You can perform YPath queries and transformations -# at this level. (See +YAML::parse+.) -# -# The serialization stage happens inside the parser. The YAML parser used in -# Ruby is called Syck. Serialized nodes are available in the extension as -# SyckNode structs. -# -# The presentation stage is the YAML document itself. This is accessible -# to you as a string. (See +YAML::dump+.) -# -# For more information about the various information models, see Chapter -# 3 of the YAML 1.0 Specification (http://yaml.org/spec/#id2491269). -# -# The YAML module provides quick access to the most common loading (YAML::load) -# and dumping (YAML::dump) tasks. This module also provides an API for registering -# global types (YAML::add_domain_type). -# -# == Example -# -# A simple round-trip (load and dump) of an object. -# -# require "yaml" -# -# test_obj = ["dogs", "cats", "badgers"] -# -# yaml_obj = YAML::dump( test_obj ) -# # -> --- -# - dogs -# - cats -# - badgers -# ruby_obj = YAML::load( yaml_obj ) -# # => ["dogs", "cats", "badgers"] -# ruby_obj == test_obj -# # => true -# -# To register your custom types with the global resolver, use +add_domain_type+. -# -# YAML::add_domain_type( "your-site.com,2004", "widget" ) do |type, val| -# Widget.new( val ) -# end -# -module Syck - - DefaultResolver.use_types_at( @@tagged_classes ) - - # Returns a new default parser - def self.parser; Parser.new.set_resolver( self.resolver ); end - - # Returns a new generic parser - def self.generic_parser - warn "#{caller[0]}: YAML.generic_parser is deprecated, switch to psych" if $VERBOSE && !caller[0].start_with?(File.dirname(__FILE__)) - Parser.new.set_resolver( GenericResolver ) - end - - # Returns the default resolver - def self.resolver - warn "#{caller[0]}: YAML.resolver is deprecated" if $VERBOSE && !caller[0].start_with?(File.dirname(__FILE__)) - DefaultResolver - end - - # Returns a new default emitter - def self.emitter - warn "#{caller[0]}: YAML.emitter is deprecated" if $VERBOSE && !caller[0].start_with?(File.dirname(__FILE__)) - Emitter.new.set_resolver( self.resolver ) - end - - # - # Converts _obj_ to YAML and writes the YAML result to _io_. - # - # File.open( 'animals.yaml', 'w' ) do |out| - # YAML.dump( ['badger', 'elephant', 'tiger'], out ) - # end - # - # If no _io_ is provided, a string containing the dumped YAML - # is returned. - # - # YAML.dump( :locked ) - # #=> "--- :locked" - # - def self.dump( obj, io = nil ) - obj.to_yaml( io || io2 = StringIO.new ) - io || ( io2.rewind; io2.read ) - end - - # - # Load a document from the current _io_ stream. - # - # File.open( 'animals.yaml' ) { |yf| YAML::load( yf ) } - # #=> ['badger', 'elephant', 'tiger'] - # - # Can also load from a string. - # - # YAML.load( "--- :locked" ) - # #=> :locked - # - def self.load( io ) - yp = parser.load( io ) - end - - # - # Load a document from the file located at _filepath_. - # - # YAML.load_file( 'animals.yaml' ) - # #=> ['badger', 'elephant', 'tiger'] - # - def self.load_file( filepath ) - File.open( filepath ) do |f| - load( f ) - end - end - - # - # Parse the first document from the current _io_ stream - # - # File.open( 'animals.yaml' ) { |yf| YAML::load( yf ) } - # #=> #, - # #, - # #]> - # - # Can also load from a string. - # - # YAML.parse( "--- :locked" ) - # #=> # - # - def self.parse( io ) - yp = generic_parser.load( io ) - end - - # - # Parse a document from the file located at _filepath_. - # - # YAML.parse_file( 'animals.yaml' ) - # #=> #, - # #, - # #]> - # - def self.parse_file( filepath ) - File.open( filepath ) do |f| - parse( f ) - end - end - - # - # Calls _block_ with each consecutive document in the YAML - # stream contained in _io_. - # - # File.open( 'many-docs.yaml' ) do |yf| - # YAML.each_document( yf ) do |ydoc| - # ## ydoc contains the single object - # ## from the YAML document - # end - # end - # - def self.each_document( io, &block ) - warn "#{caller[0]}: YAML.each_document is deprecated" if $VERBOSE && !caller[0].start_with?(File.dirname(__FILE__)) - yp = parser.load_documents( io, &block ) - end - - # - # Calls _block_ with each consecutive document in the YAML - # stream contained in _io_. - # - # File.open( 'many-docs.yaml' ) do |yf| - # YAML.load_documents( yf ) do |ydoc| - # ## ydoc contains the single object - # ## from the YAML document - # end - # end - # - def self.load_documents( io, &doc_proc ) - yp = parser.load_documents( io, &doc_proc ) - end - - # - # Calls _block_ with a tree of +YAML::BaseNodes+, one tree for - # each consecutive document in the YAML stream contained in _io_. - # - # File.open( 'many-docs.yaml' ) do |yf| - # YAML.each_node( yf ) do |ydoc| - # ## ydoc contains a tree of nodes - # ## from the YAML document - # end - # end - # - def self.each_node( io, &doc_proc ) - warn "#{caller[0]}: YAML.each_node is deprecated" if $VERBOSE && !caller[0].start_with?(File.dirname(__FILE__)) - yp = generic_parser.load_documents( io, &doc_proc ) - end - - # - # Calls _block_ with a tree of +YAML::BaseNodes+, one tree for - # each consecutive document in the YAML stream contained in _io_. - # - # File.open( 'many-docs.yaml' ) do |yf| - # YAML.parse_documents( yf ) do |ydoc| - # ## ydoc contains a tree of nodes - # ## from the YAML document - # end - # end - # - def self.parse_documents( io, &doc_proc ) - warn "#{caller[0]}: YAML.parse_documents is deprecated, use load_stream" if $VERBOSE && !caller[0].start_with?(File.dirname(__FILE__)) - self.each_node( io, &doc_proc ) - end - - # - # Loads all documents from the current _io_ stream, - # returning a +YAML::Stream+ object containing all - # loaded documents. - # - def self.load_stream( io ) - d = nil - parser.load_documents( io ) do |doc| - d = Stream.new if not d - d.add( doc ) - end - return d - end - - # - # Returns a YAML stream containing each of the items in +objs+, - # each having their own document. - # - # YAML.dump_stream( 0, [], {} ) - # #=> --- 0 - # --- [] - # --- {} - # - def self.dump_stream( *objs ) - d = Stream.new - objs.each do |doc| - d.add( doc ) - end - d.emit - end - - # - # Add a global handler for a YAML domain type. - # - def self.add_domain_type( domain, type_tag, &transfer_proc ) - resolver.add_type( "tag:#{ domain }:#{ type_tag }", transfer_proc ) - end - - # - # Add a transfer method for a builtin type - # - def self.add_builtin_type( type_tag, &transfer_proc ) - resolver.add_type( "tag:yaml.org,2002:#{ type_tag }", transfer_proc ) - end - - # - # Add a transfer method for a builtin type - # - def self.add_ruby_type( type_tag, &transfer_proc ) - warn "#{caller[0]}: YAML.add_ruby_type is deprecated, use add_domain_type" if $VERBOSE && !caller[0].start_with?(File.dirname(__FILE__)) - resolver.add_type( "tag:ruby.yaml.org,2002:#{ type_tag }", transfer_proc ) - end - - # - # Add a private document type - # - def self.add_private_type( type_re, &transfer_proc ) - warn "#{caller[0]}: YAML.add_private_type is deprecated, use add_domain_type" if $VERBOSE && !caller[0].start_with?(File.dirname(__FILE__)) - resolver.add_type( "x-private:" + type_re, transfer_proc ) - end - - # - # Detect typing of a string - # - def self.detect_implicit( val ) - warn "#{caller[0]}: YAML.detect_implicit is deprecated" if $VERBOSE && !caller[0].start_with?(File.dirname(__FILE__)) - resolver.detect_implicit( val ) - end - - # - # Convert a type_id to a taguri - # - def self.tagurize( val ) - warn "#{caller[0]}: YAML.tagurize is deprecated" if $VERBOSE && !caller[0].start_with?(File.dirname(__FILE__)) - resolver.tagurize( val ) - end - - # - # Apply a transfer method to a Ruby object - # - def self.transfer( type_id, obj ) - warn "#{caller[0]}: YAML.transfer is deprecated" if $VERBOSE && !caller[0].start_with?(File.dirname(__FILE__)) - resolver.transfer( tagurize( type_id ), obj ) - end - - # - # Apply any implicit a node may qualify for - # - def self.try_implicit( obj ) - warn "#{caller[0]}: YAML.try_implicit is deprecated" if $VERBOSE && !caller[0].start_with?(File.dirname(__FILE__)) - transfer( detect_implicit( obj ), obj ) - end - - # - # Method to extract colon-seperated type and class, returning - # the type and the constant of the class - # - def self.read_type_class( type, obj_class ) - warn "#{caller[0]}: YAML.read_type_class is deprecated" if $VERBOSE && !caller[0].start_with?(File.dirname(__FILE__)) - scheme, domain, type, tclass = type.split( ':', 4 ) - tclass.split( "::" ).each { |c| obj_class = obj_class.const_get( c ) } if tclass - return [ type, obj_class ] - end - - # - # Allocate blank object - # - def self.object_maker( obj_class, val ) - warn "#{caller[0]}: YAML.object_maker is deprecated" if $VERBOSE && !caller[0].start_with?(File.dirname(__FILE__)) - if Hash === val - o = obj_class.allocate - val.each_pair { |k,v| - o.instance_variable_set("@#{k}", v) - } - o - else - raise Error, "Invalid object explicitly tagged !ruby/Object: " + val.inspect - end - end - - # - # Allocate an Emitter if needed - # - def self.quick_emit( oid, opts = {}, &e ) - warn "#{caller[0]}: YAML.quick_emit is deprecated" if $VERBOSE && !caller[0].start_with?(File.dirname(__FILE__)) - out = - if opts.is_a? Emitter - opts - else - emitter.reset( opts ) - end - out.emit( oid, &e ) - end - -end - -module Kernel - # - # ryan:: You know how Kernel.p is a really convenient way to dump ruby - # structures? The only downside is that it's not as legible as - # YAML. - # - # _why:: (listening) - # - # ryan:: I know you don't want to urinate all over your users' namespaces. - # But, on the other hand, convenience of dumping for debugging is, - # IMO, a big YAML use case. - # - # _why:: Go nuts! Have a pony parade! - # - # ryan:: Either way, I certainly will have a pony parade. - # - - # Prints any supplied _objects_ out in YAML. Intended as - # a variation on +Kernel::p+. - # - # S = Struct.new(:name, :state) - # s = S['dave', 'TX'] - # y s - # - # _produces:_ - # - # --- !ruby/struct:S - # name: dave - # state: TX - # - def y( object, *objects ) - objects.unshift object - puts( if objects.length == 1 - YAML.dump( *objects ) - else - YAML.dump_stream( *objects ) - end ) - end - private :y -end - - diff --git a/Src/StdLib/ruby/1.9.1/syck/baseemitter.rb b/Src/StdLib/ruby/1.9.1/syck/baseemitter.rb deleted file mode 100644 index 25ab6bfd0..000000000 --- a/Src/StdLib/ruby/1.9.1/syck/baseemitter.rb +++ /dev/null @@ -1,242 +0,0 @@ -# -# BaseEmitter -# - -require 'syck/constants' -require 'syck/encoding' -require 'syck/error' - -module Syck - module BaseEmitter - def options( opt = nil ) - if opt - @options[opt] || DEFAULTS[opt] - else - @options - end - end - - def options=( opt ) - @options = opt - end - - # - # Emit binary data - # - def binary_base64( value ) - self << "!binary " - self.node_text( [value].pack("m"), '|' ) - end - - # - # Emit plain, normal flowing text - # - def node_text( value, block = nil ) - @seq_map = false - valx = value.dup - unless block - block = - if options(:UseBlock) - '|' - elsif not options(:UseFold) and valx =~ /\n[ \t]/ and not valx =~ /#{ESCAPE_CHAR}/ - '|' - else - '>' - end - indt = $&.to_i if block =~ /\d+/ - if valx =~ /(\A\n*[ \t#]|^---\s+)/ - indt = options(:Indent) unless indt.to_i > 0 - block += indt.to_s - end - - block += - if valx =~ /\n\Z\n/ - "+" - elsif valx =~ /\Z\n/ - "" - else - "-" - end - end - block += "\n" - if block[0] == ?" - esc_skip = ( "\t\n" unless valx =~ /^[ \t]/ ) || "" - valx = fold( Syck.escape( valx, esc_skip ) + "\"" ).chomp - self << '"' + indent_text( valx, indt, false ) - else - if block[0] == ?> - valx = fold( valx ) - end - #p [block, indt] - self << block + indent_text( valx, indt ) - end - end - - # - # Emit a simple, unqouted string - # - def simple( value ) - @seq_map = false - self << value.to_s - end - - # - # Emit double-quoted string - # - def double( value ) - "\"#{Syck.escape( value )}\"" - end - - # - # Emit single-quoted string - # - def single( value ) - "'#{value}'" - end - - # - # Write a text block with the current indent - # - def indent_text( text, mod, first_line = true ) - return "" if text.to_s.empty? - spacing = indent( mod ) - text = text.gsub( /\A([^\n])/, "#{ spacing }\\1" ) if first_line - return text.gsub( /\n^([^\n])/, "\n#{spacing}\\1" ) - end - - # - # Write a current indent - # - def indent( mod = nil ) - #p [ self.id, level, mod, :INDENT ] - if level <= 0 - mod ||= 0 - else - mod ||= options(:Indent) - mod += ( level - 1 ) * options(:Indent) - end - return " " * mod - end - - # - # Add indent to the buffer - # - def indent! - self << indent - end - - # - # Folding paragraphs within a column - # - def fold( value ) - value.gsub( /(^[ \t]+.*$)|(\S.{0,#{options(:BestWidth) - 1}})(?:[ \t]+|(\n+(?=[ \t]|\Z))|$)/ ) do - $1 || $2 + ( $3 || "\n" ) - end - end - - # - # Quick mapping - # - def map( type, &e ) - val = Mapping.new - e.call( val ) - self << "#{type} " if type.length.nonzero? - - # - # Empty hashes - # - if val.length.zero? - self << "{}" - @seq_map = false - else - # FIXME - # if @buffer.length == 1 and options(:UseHeader) == false and type.length.zero? - # @headless = 1 - # end - - defkey = @options.delete( :DefaultKey ) - if defkey - seq_map_shortcut - self << "= : " - defkey.to_yaml( :Emitter => self ) - end - - # - # Emit the key and value - # - val.each { |v| - seq_map_shortcut - if v[0].is_complex_yaml? - self << "? " - end - v[0].to_yaml( :Emitter => self ) - if v[0].is_complex_yaml? - self << "\n" - indent! - end - self << ": " - v[1].to_yaml( :Emitter => self ) - } - end - end - - def seq_map_shortcut - # FIXME: seq_map needs to work with the new anchoring system - # if @seq_map - # @anchor_extras[@buffer.length - 1] = "\n" + indent - # @seq_map = false - # else - self << "\n" - indent! - # end - end - - # - # Quick sequence - # - def seq( type, &e ) - @seq_map = false - val = Sequence.new - e.call( val ) - self << "#{type} " if type.length.nonzero? - - # - # Empty arrays - # - if val.length.zero? - self << "[]" - else - # FIXME - # if @buffer.length == 1 and options(:UseHeader) == false and type.length.zero? - # @headless = 1 - # end - - # - # Emit the key and value - # - val.each { |v| - self << "\n" - indent! - self << "- " - @seq_map = true if v.class == Hash - v.to_yaml( :Emitter => self ) - } - end - end - end - - # - # Emitter helper classes - # - class Mapping < Array - def add( k, v ) - push [k, v] - end - end - - class Sequence < Array - def add( v ) - push v - end - end -end diff --git a/Src/StdLib/ruby/1.9.1/syck/basenode.rb b/Src/StdLib/ruby/1.9.1/syck/basenode.rb deleted file mode 100644 index 60b5bbe6d..000000000 --- a/Src/StdLib/ruby/1.9.1/syck/basenode.rb +++ /dev/null @@ -1,223 +0,0 @@ -# -# YAML::BaseNode class -# - -module Syck - - # - # YAML Generic Model container - # - module BaseNode - - # - # Search for YPath entry and return - # qualified nodes. - # - def select( ypath_str ) - warn "#{caller[0]}: select is deprecated" if $VERBOSE - matches = match_path( ypath_str ) - - # - # Create a new generic view of the elements selected - # - if matches - result = [] - matches.each { |m| - result.push m.last - } - Syck.transfer( 'seq', result ) - end - end - - # - # Search for YPath entry and return - # transformed nodes. - # - def select!( ypath_str ) - warn "#{caller[0]}: select!() is deprecated" if $VERBOSE - matches = match_path( ypath_str ) - - # - # Create a new generic view of the elements selected - # - if matches - result = [] - matches.each { |m| - result.push m.last.transform - } - result - end - end - - # - # Search for YPath entry and return a list of - # qualified paths. - # - def search( ypath_str ) - warn "#{caller[0]}: search() is deprecated" if $VERBOSE - matches = match_path( ypath_str ) - - if matches - matches.collect { |m| - path = [] - m.each_index { |i| - path.push m[i] if ( i % 2 ).zero? - } - "/" + path.compact.join( "/" ) - } - end - end - - def at( seg ) - warn "#{caller[0]}: at() is deprecated" if $VERBOSE - if Hash === @value - self[seg] - elsif Array === @value and seg =~ /\A\d+\Z/ and @value[seg.to_i] - @value[seg.to_i] - end - end - - # - # YPath search returning a complete depth array - # - def match_path( ypath_str ) - warn "#{caller[0]}: match_path is deprecated" if $VERBOSE - require 'syck/ypath' - depth = 0 - matches = [] - YPath.each_path( ypath_str ) do |ypath| - seg = match_segment( ypath, 0 ) - matches += seg if seg - end - matches.uniq - end - - # - # Search a node for a single YPath segment - # - def match_segment( ypath, depth ) - warn "#{caller[0]}: match_segment is deprecated" if $VERBOSE - deep_nodes = [] - seg = ypath.segments[ depth ] - if seg == "/" - unless String === @value - idx = -1 - @value.collect { |v| - idx += 1 - if Hash === @value - match_init = [v[0].transform, v[1]] - match_deep = v[1].match_segment( ypath, depth ) - else - match_init = [idx, v] - match_deep = v.match_segment( ypath, depth ) - end - if match_deep - match_deep.each { |m| - deep_nodes.push( match_init + m ) - } - end - } - end - depth += 1 - seg = ypath.segments[ depth ] - end - match_nodes = - case seg - when "." - [[nil, self]] - when ".." - [["..", nil]] - when "*" - if @value.is_a? Enumerable - idx = -1 - @value.collect { |h| - idx += 1 - if Hash === @value - [h[0].transform, h[1]] - else - [idx, h] - end - } - end - else - if seg =~ /^"(.*)"$/ - seg = $1 - elsif seg =~ /^'(.*)'$/ - seg = $1 - end - if ( v = at( seg ) ) - [[ seg, v ]] - end - end - return deep_nodes unless match_nodes - pred = ypath.predicates[ depth ] - if pred - case pred - when /^\.=/ - pred = $' # ' - match_nodes.reject! { |n| - n.last.value != pred - } - else - match_nodes.reject! { |n| - n.last.at( pred ).nil? - } - end - end - return match_nodes + deep_nodes unless ypath.segments.length > depth + 1 - - #puts "DEPTH: #{depth + 1}" - deep_nodes = [] - match_nodes.each { |n| - if n[1].is_a? BaseNode - match_deep = n[1].match_segment( ypath, depth + 1 ) - if match_deep - match_deep.each { |m| - deep_nodes.push( n + m ) - } - end - else - deep_nodes = [] - end - } - deep_nodes = nil if deep_nodes.length == 0 - deep_nodes - end - - # - # We want the node to act like as Hash - # if it is. - # - def []( *key ) - if Hash === @value - v = @value.detect { |k,| k.transform == key.first } - v[1] if v - elsif Array === @value - @value.[]( *key ) - end - end - - def children - if Hash === @value - @value.values.collect { |c| c[1] } - elsif Array === @value - @value - end - end - - def children_with_index - warn "#{caller[0]}: children_with_index is deprecated, use children" if $VERBOSE - if Hash === @value - @value.keys.collect { |i| [self[i], i] } - elsif Array === @value - i = -1; @value.collect { |v| i += 1; [v, i] } - end - end - - def emit - transform.to_yaml - end - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/syck/constants.rb b/Src/StdLib/ruby/1.9.1/syck/constants.rb deleted file mode 100644 index 19b557b29..000000000 --- a/Src/StdLib/ruby/1.9.1/syck/constants.rb +++ /dev/null @@ -1,45 +0,0 @@ -# -# Constants used throughout the library -# -module Syck - - # - # Constants - # - VERSION = '0.60' - SUPPORTED_YAML_VERSIONS = ['1.0'] - - # - # Parser tokens - # - WORD_CHAR = 'A-Za-z0-9' - PRINTABLE_CHAR = '-_A-Za-z0-9!?/()$\'". ' - NOT_PLAIN_CHAR = '\x7f\x0-\x1f\x80-\x9f' - ESCAPE_CHAR = '[\\x00-\\x09\\x0b-\\x1f]' - INDICATOR_CHAR = '*&!|\\\\^@%{}[]=' - SPACE_INDICATORS = '-#:,?' - RESTRICTED_INDICATORS = '#:,}]' - DNS_COMP_RE = "\\w(?:[-\\w]*\\w)?" - DNS_NAME_RE = "(?:(?:#{DNS_COMP_RE}\\.)+#{DNS_COMP_RE}|#{DNS_COMP_RE})" - ESCAPES = %w{\x00 \x01 \x02 \x03 \x04 \x05 \x06 \a - \x08 \t \n \v \f \r \x0e \x0f - \x10 \x11 \x12 \x13 \x14 \x15 \x16 \x17 - \x18 \x19 \x1a \e \x1c \x1d \x1e \x1f - } - UNESCAPES = { - 'a' => "\x07", 'b' => "\x08", 't' => "\x09", - 'n' => "\x0a", 'v' => "\x0b", 'f' => "\x0c", - 'r' => "\x0d", 'e' => "\x1b", '\\' => '\\', - } - - # - # Default settings - # - DEFAULTS = { - :Indent => 2, :UseHeader => false, :UseVersion => false, :Version => '1.0', - :SortKeys => false, :AnchorFormat => 'id%03d', :ExplicitTypes => false, - :WidthType => 'absolute', :BestWidth => 80, - :UseBlock => false, :UseFold => false, :Encoding => :None - } - -end diff --git a/Src/StdLib/ruby/1.9.1/syck/encoding.rb b/Src/StdLib/ruby/1.9.1/syck/encoding.rb deleted file mode 100644 index 1507c30bb..000000000 --- a/Src/StdLib/ruby/1.9.1/syck/encoding.rb +++ /dev/null @@ -1,35 +0,0 @@ -# -# Handle Unicode-to-Internal conversion -# - -module Syck - - # - # Escape the string, condensing common escapes - # - def self.escape( value, skip = "" ) - warn "#{caller[0]}: YAML.escape is deprecated" if $VERBOSE - value.gsub( /\\/, "\\\\\\" ). - gsub( /"/, "\\\"" ). - gsub( /([\x00-\x1f])/ ) do - skip[$&] || ESCAPES[ $&.unpack("C")[0] ] - end - end - - # - # Unescape the condenses escapes - # - def self.unescape( value ) - warn "#{caller[0]}: YAML.unescape is deprecated" if $VERBOSE - value.gsub( /\\(?:([nevfbart\\])|0?x([0-9a-fA-F]{2})|u([0-9a-fA-F]{4}))/ ) { - if $3 - ["#$3".hex ].pack('U*') - elsif $2 - [$2].pack( "H2" ) - else - UNESCAPES[$1] - end - } - end - -end diff --git a/Src/StdLib/ruby/1.9.1/syck/error.rb b/Src/StdLib/ruby/1.9.1/syck/error.rb deleted file mode 100644 index 40920b0ec..000000000 --- a/Src/StdLib/ruby/1.9.1/syck/error.rb +++ /dev/null @@ -1,34 +0,0 @@ -# -# Error messages and exception class -# - -module Syck - - # - # Error messages - # - - ERROR_NO_HEADER_NODE = "With UseHeader=false, the node Array or Hash must have elements" - ERROR_NEED_HEADER = "With UseHeader=false, the node must be an Array or Hash" - ERROR_BAD_EXPLICIT = "Unsupported explicit transfer: '%s'" - ERROR_MANY_EXPLICIT = "More than one explicit transfer" - ERROR_MANY_IMPLICIT = "More than one implicit request" - ERROR_NO_ANCHOR = "No anchor for alias '%s'" - ERROR_BAD_ANCHOR = "Invalid anchor: %s" - ERROR_MANY_ANCHOR = "More than one anchor" - ERROR_ANCHOR_ALIAS = "Can't define both an anchor and an alias" - ERROR_BAD_ALIAS = "Invalid alias: %s" - ERROR_MANY_ALIAS = "More than one alias" - ERROR_ZERO_INDENT = "Can't use zero as an indentation width" - ERROR_UNSUPPORTED_VERSION = "This release of YAML.rb does not support YAML version %s" - ERROR_UNSUPPORTED_ENCODING = "Attempt to use unsupported encoding: %s" - - # - # YAML Error classes - # - - class Error < StandardError; end - class ParseError < Error; end - class TypeError < StandardError; end - -end diff --git a/Src/StdLib/ruby/1.9.1/syck/loader.rb b/Src/StdLib/ruby/1.9.1/syck/loader.rb deleted file mode 100644 index e1c54970d..000000000 --- a/Src/StdLib/ruby/1.9.1/syck/loader.rb +++ /dev/null @@ -1,14 +0,0 @@ -# -# YAML::Loader class -# .. type handling .. -# -module Syck - class Loader - TRANSFER_DOMAINS = { - 'yaml.org,2002' => {}, - 'ruby.yaml.org,2002' => {} - } - PRIVATE_TYPES = {} - IMPLICIT_TYPES = [ 'null', 'bool', 'time', 'int', 'float' ] - end -end diff --git a/Src/StdLib/ruby/1.9.1/syck/rubytypes.rb b/Src/StdLib/ruby/1.9.1/syck/rubytypes.rb deleted file mode 100644 index 0acc7f49f..000000000 --- a/Src/StdLib/ruby/1.9.1/syck/rubytypes.rb +++ /dev/null @@ -1,464 +0,0 @@ -# -*- mode: ruby; ruby-indent-level: 4; tab-width: 4 -*- vim: sw=4 ts=4 -require 'date' - -class Class - def to_yaml( opts = {} ) - raise TypeError, "can't dump anonymous class %s" % self.class - end -end - -class Object - yaml_as "tag:ruby.yaml.org,2002:object" - def to_yaml_style; end - def to_yaml_properties; instance_variables.sort; end - def to_yaml( opts = {} ) - YAML::quick_emit( self, opts ) do |out| - out.map( taguri, to_yaml_style ) do |map| - to_yaml_properties.each do |m| - map.add( m[1..-1], instance_variable_get( m ) ) - end - end - end - end - alias :syck_to_yaml :to_yaml -end - -class Hash - yaml_as "tag:ruby.yaml.org,2002:hash" - yaml_as "tag:yaml.org,2002:map" - def yaml_initialize( tag, val ) - if Array === val - update Hash.[]( *val ) # Convert the map to a sequence - elsif Hash === val - update val - else - raise YAML::TypeError, "Invalid map explicitly tagged #{ tag }: " + val.inspect - end - end - def to_yaml( opts = {} ) - return super unless YAML::ENGINE.syck? - YAML::quick_emit( self, opts ) do |out| - out.map( taguri, to_yaml_style ) do |map| - each do |k, v| - map.add( k, v ) - end - end - end - end -end - -class Struct - yaml_as "tag:ruby.yaml.org,2002:struct" - def self.yaml_tag_class_name; self.name.gsub( "Struct::", "" ); end - def self.yaml_tag_read_class( name ); "Struct::#{ name }"; end - def self.yaml_new( klass, tag, val ) - if Hash === val - struct_type = nil - - # - # Use existing Struct if it exists - # - props = {} - val.delete_if { |k,v| props[k] = v if k =~ /^@/ } - begin - struct_name, struct_type = YAML.read_type_class( tag, Struct ) - rescue NameError - end - if not struct_type - struct_def = [ tag.split( ':', 4 ).last ] - struct_type = Struct.new( *struct_def.concat( val.keys.collect { |k| k.intern } ) ) - end - - # - # Set the Struct properties - # - st = YAML::object_maker( struct_type, {} ) - st.members.each do |m| - st.send( "#{m}=", val[m.to_s] ) - end - props.each do |k,v| - st.instance_variable_set(k, v) - end - st - else - raise YAML::TypeError, "Invalid Ruby Struct: " + val.inspect - end - end - def to_yaml( opts = {} ) - return super unless YAML::ENGINE.syck? - YAML::quick_emit( self, opts ) do |out| - # - # Basic struct is passed as a YAML map - # - out.map( taguri, to_yaml_style ) do |map| - self.members.each do |m| - map.add( m.to_s, self[m.to_s] ) - end - self.to_yaml_properties.each do |m| - map.add( m, instance_variable_get( m ) ) - end - end - end - end -end - -class Array - yaml_as "tag:ruby.yaml.org,2002:array" - yaml_as "tag:yaml.org,2002:seq" - def yaml_initialize( tag, val ); concat( val.to_a ); end - def to_yaml( opts = {} ) - return super unless YAML::ENGINE.syck? - YAML::quick_emit( self, opts ) do |out| - out.seq( taguri, to_yaml_style ) do |seq| - each do |x| - seq.add( x ) - end - end - end - end -end - -class Exception - yaml_as "tag:ruby.yaml.org,2002:exception" - def Exception.yaml_new( klass, tag, val ) - o = YAML.object_maker( klass, { 'mesg' => val.delete( 'message' ) } ) - val.each_pair do |k,v| - o.instance_variable_set("@#{k}", v) - end - o - end - def to_yaml( opts = {} ) - return super unless YAML::ENGINE.syck? - YAML::quick_emit( self, opts ) do |out| - out.map( taguri, to_yaml_style ) do |map| - map.add( 'message', message ) - to_yaml_properties.each do |m| - map.add( m[1..-1], instance_variable_get( m ) ) - end - end - end - end -end - -class String - yaml_as "tag:ruby.yaml.org,2002:string" - yaml_as "tag:yaml.org,2002:binary" - yaml_as "tag:yaml.org,2002:str" - def is_complex_yaml? - to_yaml_style or not to_yaml_properties.empty? or self =~ /\n.+/ - end - def is_binary_data? - self.count("^ -~\t\r\n").fdiv(self.size) > 0.3 || self.index("\x00") unless self.empty? - end - def String.yaml_new( klass, tag, val ) - val = val.unpack("m")[0] if tag == "tag:yaml.org,2002:binary" - val = { 'str' => val } if String === val - if Hash === val - s = klass.allocate - # Thank you, NaHi - String.instance_method(:initialize). - bind(s). - call( val.delete( 'str' ) ) - val.each { |k,v| s.instance_variable_set( k, v ) } - s - else - raise YAML::TypeError, "Invalid String: " + val.inspect - end - end - def to_yaml( opts = {} ) - return super unless YAML::ENGINE.syck? - YAML::quick_emit( is_complex_yaml? ? self : nil, opts ) do |out| - if is_binary_data? - out.scalar( "tag:yaml.org,2002:binary", [self].pack("m"), :literal ) - elsif to_yaml_properties.empty? - out.scalar( taguri, self, self =~ /^:/ ? :quote2 : to_yaml_style ) - else - out.map( taguri, to_yaml_style ) do |map| - map.add( 'str', "#{self}" ) - to_yaml_properties.each do |m| - map.add( m, instance_variable_get( m ) ) - end - end - end - end - end -end - -class Symbol - yaml_as "tag:ruby.yaml.org,2002:symbol" - yaml_as "tag:ruby.yaml.org,2002:sym" - def Symbol.yaml_new( klass, tag, val ) - if String === val - val = YAML::load( val ) if val =~ /\A(["']).*\1\z/ - val.intern - else - raise YAML::TypeError, "Invalid Symbol: " + val.inspect - end - end - def to_yaml( opts = {} ) - return super unless YAML::ENGINE.syck? - YAML::quick_emit( nil, opts ) do |out| - out.scalar( "tag:yaml.org,2002:str", self.inspect, :plain ) - end - end -end - -class Range - yaml_as "tag:ruby.yaml.org,2002:range" - def Range.yaml_new( klass, tag, val ) - inr = %r'(\w+|[+-]?\d+(?:\.\d+)?(?:e[+-]\d+)?|"(?:[^\\"]|\\.)*")' - opts = {} - if String === val and val =~ /^#{inr}(\.{2,3})#{inr}$/o - r1, rdots, r2 = $1, $2, $3 - opts = { - 'begin' => YAML.load( "--- #{r1}" ), - 'end' => YAML.load( "--- #{r2}" ), - 'excl' => rdots.length == 3 - } - val = {} - elsif Hash === val - opts['begin'] = val.delete('begin') - opts['end'] = val.delete('end') - opts['excl'] = val.delete('excl') - end - if Hash === opts - r = YAML::object_maker( klass, {} ) - # Thank you, NaHi - Range.instance_method(:initialize). - bind(r). - call( opts['begin'], opts['end'], opts['excl'] ) - val.each { |k,v| r.instance_variable_set( k, v ) } - r - else - raise YAML::TypeError, "Invalid Range: " + val.inspect - end - end - def to_yaml( opts = {} ) - return super unless YAML::ENGINE.syck? - YAML::quick_emit( self, opts ) do |out| - # if self.begin.is_complex_yaml? or self.begin.respond_to? :to_str or - # self.end.is_complex_yaml? or self.end.respond_to? :to_str or - # not to_yaml_properties.empty? - out.map( taguri, to_yaml_style ) do |map| - map.add( 'begin', self.begin ) - map.add( 'end', self.end ) - map.add( 'excl', self.exclude_end? ) - to_yaml_properties.each do |m| - map.add( m, instance_variable_get( m ) ) - end - end - # else - # out.scalar( taguri ) do |sc| - # sc.embed( self.begin ) - # sc.concat( self.exclude_end? ? "..." : ".." ) - # sc.embed( self.end ) - # end - # end - end - end -end - -class Regexp - yaml_as "tag:ruby.yaml.org,2002:regexp" - def Regexp.yaml_new( klass, tag, val ) - if String === val and val =~ /^\/(.*)\/([mix]*)$/ - val = { 'regexp' => $1, 'mods' => $2 } - end - if Hash === val - mods = nil - unless val['mods'].to_s.empty? - mods = 0x00 - mods |= Regexp::EXTENDED if val['mods'].include?( 'x' ) - mods |= Regexp::IGNORECASE if val['mods'].include?( 'i' ) - mods |= Regexp::MULTILINE if val['mods'].include?( 'm' ) - end - val.delete( 'mods' ) - r = YAML::object_maker( klass, {} ) - Regexp.instance_method(:initialize). - bind(r). - call( val.delete( 'regexp' ), mods ) - val.each { |k,v| r.instance_variable_set( k, v ) } - r - else - raise YAML::TypeError, "Invalid Regular expression: " + val.inspect - end - end - def to_yaml( opts = {} ) - return super unless YAML::ENGINE.syck? - YAML::quick_emit( nil, opts ) do |out| - if to_yaml_properties.empty? - out.scalar( taguri, self.inspect, :plain ) - else - out.map( taguri, to_yaml_style ) do |map| - src = self.inspect - if src =~ /\A\/(.*)\/([a-z]*)\Z/ - map.add( 'regexp', $1 ) - map.add( 'mods', $2 ) - else - raise YAML::TypeError, "Invalid Regular expression: " + src - end - to_yaml_properties.each do |m| - map.add( m, instance_variable_get( m ) ) - end - end - end - end - end -end - -class Time - yaml_as "tag:ruby.yaml.org,2002:time" - yaml_as "tag:yaml.org,2002:timestamp" - def Time.yaml_new( klass, tag, val ) - if Hash === val - t = val.delete( 'at' ) - val.each { |k,v| t.instance_variable_set( k, v ) } - t - else - raise YAML::TypeError, "Invalid Time: " + val.inspect - end - end - def to_yaml( opts = {} ) - return super unless YAML::ENGINE.syck? - YAML::quick_emit( self, opts ) do |out| - tz = "Z" - # from the tidy Tobias Peters Thanks! - unless self.utc? - utc_same_instant = self.dup.utc - utc_same_writing = Time.utc(year,month,day,hour,min,sec,usec) - difference_to_utc = utc_same_writing - utc_same_instant - if (difference_to_utc < 0) - difference_sign = '-' - absolute_difference = -difference_to_utc - else - difference_sign = '+' - absolute_difference = difference_to_utc - end - difference_minutes = (absolute_difference/60).round - tz = "%s%02d:%02d" % [ difference_sign, difference_minutes / 60, difference_minutes % 60] - end - standard = self.strftime( "%Y-%m-%d %H:%M:%S" ) - standard += ".%06d" % [usec] if usec.nonzero? - standard += " %s" % [tz] - if to_yaml_properties.empty? - out.scalar( taguri, standard, :plain ) - else - out.map( taguri, to_yaml_style ) do |map| - map.add( 'at', standard ) - to_yaml_properties.each do |m| - map.add( m, instance_variable_get( m ) ) - end - end - end - end - end -end - -class Date - yaml_as "tag:yaml.org,2002:timestamp#ymd" - def to_yaml( opts = {} ) - return super unless YAML::ENGINE.syck? - YAML::quick_emit( self, opts ) do |out| - out.scalar( "tag:yaml.org,2002:timestamp", self.to_s, :plain ) - end - end -end - -class Integer - yaml_as "tag:yaml.org,2002:int" - def to_yaml( opts = {} ) - return super unless YAML::ENGINE.syck? - YAML::quick_emit( nil, opts ) do |out| - out.scalar( "tag:yaml.org,2002:int", self.to_s, :plain ) - end - end -end - -class Float - yaml_as "tag:yaml.org,2002:float" - def to_yaml( opts = {} ) - return super unless YAML::ENGINE.syck? - YAML::quick_emit( nil, opts ) do |out| - str = self.to_s - if str == "Infinity" - str = ".Inf" - elsif str == "-Infinity" - str = "-.Inf" - elsif str == "NaN" - str = ".NaN" - end - out.scalar( "tag:yaml.org,2002:float", str, :plain ) - end - end -end - -class Rational - yaml_as "tag:ruby.yaml.org,2002:object:Rational" - def Rational.yaml_new( klass, tag, val ) - if val.is_a? String - Rational( val ) - else - Rational( val['numerator'], val['denominator'] ) - end - end - def to_yaml( opts = {} ) - return super unless YAML::ENGINE.syck? - YAML::quick_emit( self, opts ) do |out| - out.map( taguri, nil ) do |map| - map.add( 'denominator', denominator ) - map.add( 'numerator', numerator ) - end - end - end -end - -class Complex - yaml_as "tag:ruby.yaml.org,2002:object:Complex" - def Complex.yaml_new( klass, tag, val ) - if val.is_a? String - Complex( val ) - else - Complex( val['real'], val['image'] ) - end - end - def to_yaml( opts = {} ) - return super unless YAML::ENGINE.syck? - YAML::quick_emit( self, opts ) do |out| - out.map( taguri, nil ) do |map| - map.add( 'image', imaginary ) - map.add( 'real', real ) - end - end - end -end - -class TrueClass - yaml_as "tag:yaml.org,2002:bool#yes" - def to_yaml( opts = {} ) - return super unless YAML::ENGINE.syck? - YAML::quick_emit( nil, opts ) do |out| - out.scalar( taguri, "true", :plain ) - end - end -end - -class FalseClass - yaml_as "tag:yaml.org,2002:bool#no" - def to_yaml( opts = {} ) - return super unless YAML::ENGINE.syck? - YAML::quick_emit( nil, opts ) do |out| - out.scalar( taguri, "false", :plain ) - end - end -end - -class NilClass - yaml_as "tag:yaml.org,2002:null" - def to_yaml( opts = {} ) - return super unless YAML::ENGINE.syck? - YAML::quick_emit( nil, opts ) do |out| - out.scalar( taguri, "", :plain ) - end - end -end - diff --git a/Src/StdLib/ruby/1.9.1/syck/stream.rb b/Src/StdLib/ruby/1.9.1/syck/stream.rb deleted file mode 100644 index 995ebe36a..000000000 --- a/Src/StdLib/ruby/1.9.1/syck/stream.rb +++ /dev/null @@ -1,41 +0,0 @@ -module Syck - - # - # YAML::Stream -- for emitting many documents - # - class Stream - - attr_accessor :documents, :options - - def initialize( opts = {} ) - @options = opts - @documents = [] - end - - def []( i ) - @documents[ i ] - end - - def add( doc ) - @documents << doc - end - - def edit( doc_num, doc ) - warn "#{caller[0]}: edit is deprecated" if $VERBOSE - @documents[ doc_num ] = doc - end - - def emit( io = nil ) - # opts = @options.dup - # opts[:UseHeader] = true if @documents.length > 1 - out = Syck.emitter - out.reset( io || io2 = StringIO.new ) - @documents.each { |v| - v.to_yaml( out ) - } - io || ( io2.rewind; io2.read ) - end - - end - -end diff --git a/Src/StdLib/ruby/1.9.1/syck/stringio.rb b/Src/StdLib/ruby/1.9.1/syck/stringio.rb deleted file mode 100644 index 820ad46fa..000000000 --- a/Src/StdLib/ruby/1.9.1/syck/stringio.rb +++ /dev/null @@ -1,85 +0,0 @@ -warn "#{caller[0]}: yaml/stringio is deprecated" if $VERBOSE - -# -# Limited StringIO if no core lib is available -# -begin -require 'stringio' -rescue LoadError - # StringIO based on code by MoonWolf - class StringIO - def initialize(string="") - @string=string - @pos=0 - @eof=(string.size==0) - end - def pos - @pos - end - def eof - @eof - end - alias eof? eof - def readline(rs=$/) - if @eof - raise EOFError - else - if p = @string[@pos..-1]=~rs - line = @string[@pos,p+1] - else - line = @string[@pos..-1] - end - @pos+=line.size - @eof =true if @pos==@string.size - $_ = line - end - end - def rewind - seek(0,0) - end - def seek(offset,whence) - case whence - when 0 - @pos=offset - when 1 - @pos+=offset - when 2 - @pos=@string.size+offset - end - @eof=(@pos>=@string.size) - 0 - end - end - - # - # Class method for creating streams - # - def Syck.make_stream( io ) - if String === io - io = StringIO.new( io ) - elsif not IO === io - raise Syck::Error, "YAML stream must be an IO or String object." - end - if Syck::unicode - def io.readline - Syck.utf_to_internal( readline( @ln_sep ), @utf_encoding ) - end - def io.check_unicode - @utf_encoding = Syck.sniff_encoding( read( 4 ) ) - @ln_sep = Syck.enc_separator( @utf_encoding ) - seek( -4, IO::SEEK_CUR ) - end - def io.utf_encoding - @utf_encoding - end - io.check_unicode - else - def io.utf_encoding - :None - end - end - io - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/syck/syck.rb b/Src/StdLib/ruby/1.9.1/syck/syck.rb deleted file mode 100644 index 1f23411bc..000000000 --- a/Src/StdLib/ruby/1.9.1/syck/syck.rb +++ /dev/null @@ -1,16 +0,0 @@ -# -# YAML::Syck module -# .. glues syck and yaml.rb together .. -# -require 'syck/basenode' - -module Syck - - # - # Mixin BaseNode functionality - # - class Node - include Syck::BaseNode - end - -end diff --git a/Src/StdLib/ruby/1.9.1/syck/tag.rb b/Src/StdLib/ruby/1.9.1/syck/tag.rb deleted file mode 100644 index 28f6ac19c..000000000 --- a/Src/StdLib/ruby/1.9.1/syck/tag.rb +++ /dev/null @@ -1,95 +0,0 @@ -# -*- mode: ruby; ruby-indent-level: 4; tab-width: 4 -*- vim: sw=4 ts=4 -# $Id: tag.rb 27365 2010-04-16 20:31:59Z tenderlove $ -# -# = yaml/tag.rb: methods for associating a taguri to a class. -# -# Author:: why the lucky stiff -# -module Syck - # A dictionary of taguris which map to - # Ruby classes. - @@tagged_classes = {} - - # - # Associates a taguri _tag_ with a Ruby class _cls_. The taguri is used to give types - # to classes when loading YAML. Taguris are of the form: - # - # tag:authorityName,date:specific - # - # The +authorityName+ is a domain name or email address. The +date+ is the date the type - # was issued in YYYY or YYYY-MM or YYYY-MM-DD format. The +specific+ is a name for - # the type being added. - # - # For example, built-in YAML types have 'yaml.org' as the +authorityName+ and '2002' as the - # +date+. The +specific+ is simply the name of the type: - # - # tag:yaml.org,2002:int - # tag:yaml.org,2002:float - # tag:yaml.org,2002:timestamp - # - # The domain must be owned by you on the +date+ declared. If you don't own any domains on the - # date you declare the type, you can simply use an e-mail address. - # - # tag:why@ruby-lang.org,2004:notes/personal - # - def self.tag_class( tag, cls ) - if @@tagged_classes.has_key? tag - warn "class #{ @@tagged_classes[tag] } held ownership of the #{ tag } tag" - end - @@tagged_classes[tag] = cls - end - - # Returns the complete dictionary of taguris, paired with classes. The key for - # the dictionary is the full taguri. The value for each key is the class constant - # associated to that taguri. - # - # YAML.tagged_classes["tag:yaml.org,2002:int"] => Integer - # - def self.tagged_classes - @@tagged_classes - end -end - -class Module - # :stopdoc: - - # Adds a taguri _tag_ to a class, used when dumping or loading the class - # in YAML. See YAML::tag_class for detailed information on typing and - # taguris. - def syck_yaml_as( tag, sc = true ) - verbose, $VERBOSE = $VERBOSE, nil - class_eval <<-"END", __FILE__, __LINE__+1 - attr_writer :taguri - def taguri - if respond_to? :to_yaml_type - Syck.tagurize( to_yaml_type[1..-1] ) - else - return @taguri if defined?(@taguri) and @taguri - tag = #{ tag.dump } - if self.class.yaml_tag_subclasses? and self.class != Syck.tagged_classes[tag] - tag = "\#{ tag }:\#{ self.class.yaml_tag_class_name }" - end - tag - end - end - def self.yaml_tag_subclasses?; #{ sc ? 'true' : 'false' }; end - END - Syck.tag_class tag, self - ensure - $VERBOSE = verbose - end - remove_method :yaml_as rescue nil - alias :yaml_as :syck_yaml_as - - # Transforms the subclass name into a name suitable for display - # in a subclassed tag. - def yaml_tag_class_name - self.name - end - # Transforms the subclass name found in the tag into a Ruby - # constant name. - def yaml_tag_read_class( name ) - name - end - # :startdoc: -end diff --git a/Src/StdLib/ruby/1.9.1/syck/types.rb b/Src/StdLib/ruby/1.9.1/syck/types.rb deleted file mode 100644 index 200187c25..000000000 --- a/Src/StdLib/ruby/1.9.1/syck/types.rb +++ /dev/null @@ -1,192 +0,0 @@ -# -*- mode: ruby; ruby-indent-level: 4 -*- vim: sw=4 -# -# Classes required by the full core typeset -# - -module Syck - - # - # Default private type - # - class PrivateType - def self.tag_subclasses?; false; end - verbose, $VERBOSE = $VERBOSE, nil - def initialize( type, val ) - @type_id = type; @value = val - @value.taguri = "x-private:#{ @type_id }" - end - def to_yaml( opts = {} ) - @value.to_yaml( opts ) - end - ensure - $VERBOSE = verbose - end - - # - # Default domain type - # - class DomainType - def self.tag_subclasses?; false; end - verbose, $VERBOSE = $VERBOSE, nil - def initialize( domain, type, val ) - @domain = domain; @type_id = type; @value = val - @value.taguri = "tag:#{ @domain }:#{ @type_id }" - end - def to_yaml( opts = {} ) - @value.to_yaml( opts ) - end - ensure - $VERBOSE = verbose - end - - # - # Unresolved objects - # - class Object - def self.tag_subclasses?; false; end - def to_yaml( opts = {} ) - Syck.quick_emit( self, opts ) do |out| - out.map( "tag:ruby.yaml.org,2002:object:#{ @class }", to_yaml_style ) do |map| - @ivars.each do |k,v| - map.add( k, v ) - end - end - end - end - end - - # - # YAML Hash class to support comments and defaults - # - class SpecialHash < ::Hash - attr_accessor :default - def inspect - self.default.to_s - end - def to_s - self.default.to_s - end - def update( h ) - if Syck::SpecialHash === h - @default = h.default if h.default - end - super( h ) - end - def to_yaml( opts = {} ) - opts[:DefaultKey] = self.default - super( opts ) - end - end - - # - # Builtin collection: !omap - # - class Omap < ::Array - yaml_as "tag:yaml.org,2002:omap" - def yaml_initialize( tag, val ) - if Array === val - val.each do |v| - if Hash === v - concat( v.to_a ) # Convert the map to a sequence - else - raise Syck::Error, "Invalid !omap entry: " + val.inspect - end - end - else - raise Syck::Error, "Invalid !omap: " + val.inspect - end - self - end - def self.[]( *vals ) - o = Omap.new - 0.step( vals.length - 1, 2 ) do |i| - o[vals[i]] = vals[i+1] - end - o - end - def []( k ) - self.assoc( k ).to_a[1] - end - def []=( k, *rest ) - val, set = rest.reverse - if ( tmp = self.assoc( k ) ) and not set - tmp[1] = val - else - self << [ k, val ] - end - val - end - def has_key?( k ) - self.assoc( k ) ? true : false - end - def is_complex_yaml? - true - end - def to_yaml( opts = {} ) - Syck.quick_emit( self, opts ) do |out| - out.seq( taguri, to_yaml_style ) do |seq| - self.each do |v| - seq.add( Hash[ *v ] ) - end - end - end - end - end - - # - # Builtin collection: !pairs - # - class Pairs < ::Array - yaml_as "tag:yaml.org,2002:pairs" - def yaml_initialize( tag, val ) - if Array === val - val.each do |v| - if Hash === v - concat( v.to_a ) # Convert the map to a sequence - else - raise Syck::Error, "Invalid !pairs entry: " + val.inspect - end - end - else - raise Syck::Error, "Invalid !pairs: " + val.inspect - end - self - end - def self.[]( *vals ) - p = Pairs.new - 0.step( vals.length - 1, 2 ) { |i| - p[vals[i]] = vals[i+1] - } - p - end - def []( k ) - self.assoc( k ).to_a - end - def []=( k, val ) - self << [ k, val ] - val - end - def has_key?( k ) - self.assoc( k ) ? true : false - end - def is_complex_yaml? - true - end - def to_yaml( opts = {} ) - Syck.quick_emit( self, opts ) do |out| - out.seq( taguri, to_yaml_style ) do |seq| - self.each do |v| - seq.add( Hash[ *v ] ) - end - end - end - end - end - - # - # Builtin collection: !set - # - class Set < ::Hash - yaml_as "tag:yaml.org,2002:set" - end -end diff --git a/Src/StdLib/ruby/1.9.1/syck/yamlnode.rb b/Src/StdLib/ruby/1.9.1/syck/yamlnode.rb deleted file mode 100644 index 7d92ea958..000000000 --- a/Src/StdLib/ruby/1.9.1/syck/yamlnode.rb +++ /dev/null @@ -1,54 +0,0 @@ -# -# YAML::YamlNode class -# -require 'syck/basenode' - -module Syck - - # - # YAML Generic Model container - # - class YamlNode - include BaseNode - attr_accessor :kind, :type_id, :value, :anchor - def initialize(t, v) - @type_id = t - if Hash === v - @kind = 'map' - @value = {} - v.each {|key,val| - @value[key.transform] = [key, val] - } - elsif Array === v - @kind = 'seq' - @value = v - elsif String === v - @kind = 'scalar' - @value = v - end - end - - # - # Transform this node fully into a native type - # - def transform - t = nil - if @value.is_a? Hash - t = {} - @value.each { |k,v| - t[ k ] = v[1].transform - } - elsif @value.is_a? Array - t = [] - @value.each { |v| - t.push v.transform - } - else - t = @value - end - Syck.transfer_method( @type_id, t ) - end - - end - -end diff --git a/Src/StdLib/ruby/1.9.1/syck/ypath.rb b/Src/StdLib/ruby/1.9.1/syck/ypath.rb deleted file mode 100644 index 5a58cdac8..000000000 --- a/Src/StdLib/ruby/1.9.1/syck/ypath.rb +++ /dev/null @@ -1,54 +0,0 @@ -# -# YAML::YPath -# - -warn "#{caller[0]}: YAML::YPath is deprecated" if $VERBOSE - -module Syck - - class YPath - attr_accessor :segments, :predicates, :flags - def initialize( str ) - @segments = [] - @predicates = [] - @flags = nil - while str =~ /^\/?(\/|[^\/\[]+)(?:\[([^\]]+)\])?/ - @segments.push $1 - @predicates.push $2 - str = $' - end - unless str.to_s.empty? - @segments += str.split( "/" ) - end - if @segments.length == 0 - @segments.push "." - end - end - def self.each_path( str ) - # - # Find choices - # - paths = [] - str = "(#{ str })" - while str.sub!( /\(([^()]+)\)/, "\n#{ paths.length }\n" ) - paths.push $1.split( '|' ) - end - - # - # Construct all possible paths - # - all = [ str ] - ( paths.length - 1 ).downto( 0 ) do |i| - all = all.collect do |a| - paths[i].collect do |p| - a.gsub( /\n#{ i }\n/, p ) - end - end.flatten.uniq - end - all.collect do |path| - yield YPath.new( path ) - end - end - end - -end diff --git a/Src/StdLib/ruby/1.9.1/sync.rb b/Src/StdLib/ruby/1.9.1/sync.rb deleted file mode 100644 index af6340a0e..000000000 --- a/Src/StdLib/ruby/1.9.1/sync.rb +++ /dev/null @@ -1,307 +0,0 @@ -# -# sync.rb - 2 phase lock with counter -# $Release Version: 1.0$ -# $Revision: 27967 $ -# by Keiju ISHITSUKA(keiju@ishitsuka.com) -# -# -- -# Sync_m, Synchronizer_m -# Usage: -# obj.extend(Sync_m) -# or -# class Foo -# include Sync_m -# : -# end -# -# Sync_m#sync_mode -# Sync_m#sync_locked?, locked? -# Sync_m#sync_shared?, shared? -# Sync_m#sync_exclusive?, sync_exclusive? -# Sync_m#sync_try_lock, try_lock -# Sync_m#sync_lock, lock -# Sync_m#sync_unlock, unlock -# -# Sync, Synchronizer: -# Usage: -# sync = Sync.new -# -# Sync#mode -# Sync#locked? -# Sync#shared? -# Sync#exclusive? -# Sync#try_lock(mode) -- mode = :EX, :SH, :UN -# Sync#lock(mode) -- mode = :EX, :SH, :UN -# Sync#unlock -# Sync#synchronize(mode) {...} -# -# - -unless defined? Thread - raise "Thread not available for this ruby interpreter" -end - -module Sync_m - RCS_ID='-$Id: sync.rb 27967 2010-05-23 08:48:44Z nobu $-' - - # lock mode - UN = :UN - SH = :SH - EX = :EX - - # exceptions - class Err < StandardError - def Err.Fail(*opt) - fail self, sprintf(self::Message, *opt) - end - - class UnknownLocker < Err - Message = "Thread(%s) not locked." - def UnknownLocker.Fail(th) - super(th.inspect) - end - end - - class LockModeFailer < Err - Message = "Unknown lock mode(%s)" - def LockModeFailer.Fail(mode) - if mode.id2name - mode = id2name - end - super(mode) - end - end - end - - def Sync_m.define_aliases(cl) - cl.module_eval %q{ - alias locked? sync_locked? - alias shared? sync_shared? - alias exclusive? sync_exclusive? - alias lock sync_lock - alias unlock sync_unlock - alias try_lock sync_try_lock - alias synchronize sync_synchronize - } - end - - def Sync_m.append_features(cl) - super - # do nothing for Modules - # make aliases for Classes. - define_aliases(cl) unless cl.instance_of?(Module) - self - end - - def Sync_m.extend_object(obj) - super - obj.sync_extend - end - - def sync_extend - unless (defined? locked? and - defined? shared? and - defined? exclusive? and - defined? lock and - defined? unlock and - defined? try_lock and - defined? synchronize) - Sync_m.define_aliases(singleton_class) - end - sync_initialize - end - - # accessing - def sync_locked? - sync_mode != UN - end - - def sync_shared? - sync_mode == SH - end - - def sync_exclusive? - sync_mode == EX - end - - # locking methods. - def sync_try_lock(mode = EX) - return unlock if mode == UN - @sync_mutex.synchronize do - ret = sync_try_lock_sub(mode) - end - ret - end - - def sync_lock(m = EX) - return unlock if m == UN - - while true - @sync_mutex.synchronize do - if sync_try_lock_sub(m) - return self - else - if sync_sh_locker[Thread.current] - sync_upgrade_waiting.push [Thread.current, sync_sh_locker[Thread.current]] - sync_sh_locker.delete(Thread.current) - else - sync_waiting.push Thread.current - end - @sync_mutex.sleep - end - end - end - self - end - - def sync_unlock(m = EX) - wakeup_threads = [] - @sync_mutex.synchronize do - if sync_mode == UN - Err::UnknownLocker.Fail(Thread.current) - end - - m = sync_mode if m == EX and sync_mode == SH - - runnable = false - case m - when UN - Err::UnknownLocker.Fail(Thread.current) - - when EX - if sync_ex_locker == Thread.current - if (self.sync_ex_count = sync_ex_count - 1) == 0 - self.sync_ex_locker = nil - if sync_sh_locker.include?(Thread.current) - self.sync_mode = SH - else - self.sync_mode = UN - end - runnable = true - end - else - Err::UnknownLocker.Fail(Thread.current) - end - - when SH - if (count = sync_sh_locker[Thread.current]).nil? - Err::UnknownLocker.Fail(Thread.current) - else - if (sync_sh_locker[Thread.current] = count - 1) == 0 - sync_sh_locker.delete(Thread.current) - if sync_sh_locker.empty? and sync_ex_count == 0 - self.sync_mode = UN - runnable = true - end - end - end - end - - if runnable - if sync_upgrade_waiting.size > 0 - th, count = sync_upgrade_waiting.shift - sync_sh_locker[th] = count - th.wakeup - wakeup_threads.push th - else - wait = sync_waiting - self.sync_waiting = [] - for th in wait - th.wakeup - wakeup_threads.push th - end - end - end - end - for th in wakeup_threads - th.run - end - self - end - - def sync_synchronize(mode = EX) - sync_lock(mode) - begin - yield - ensure - sync_unlock - end - end - - attr_accessor :sync_mode - - attr_accessor :sync_waiting - attr_accessor :sync_upgrade_waiting - attr_accessor :sync_sh_locker - attr_accessor :sync_ex_locker - attr_accessor :sync_ex_count - - def sync_inspect - sync_iv = instance_variables.select{|iv| /^@sync_/ =~ iv.id2name}.collect{|iv| iv.id2name + '=' + instance_eval(iv.id2name).inspect}.join(",") - print "<#{self.class}.extend Sync_m: #{inspect}, " - end - - private - - def sync_initialize - @sync_mode = UN - @sync_waiting = [] - @sync_upgrade_waiting = [] - @sync_sh_locker = Hash.new - @sync_ex_locker = nil - @sync_ex_count = 0 - - @sync_mutex = Mutex.new - end - - def initialize(*args) - super - sync_initialize - end - - def sync_try_lock_sub(m) - case m - when SH - case sync_mode - when UN - self.sync_mode = m - sync_sh_locker[Thread.current] = 1 - ret = true - when SH - count = 0 unless count = sync_sh_locker[Thread.current] - sync_sh_locker[Thread.current] = count + 1 - ret = true - when EX - # in EX mode, lock will upgrade to EX lock - if sync_ex_locker == Thread.current - self.sync_ex_count = sync_ex_count + 1 - ret = true - else - ret = false - end - end - when EX - if sync_mode == UN or - sync_mode == SH && sync_sh_locker.size == 1 && sync_sh_locker.include?(Thread.current) - self.sync_mode = m - self.sync_ex_locker = Thread.current - self.sync_ex_count = 1 - ret = true - elsif sync_mode == EX && sync_ex_locker == Thread.current - self.sync_ex_count = sync_ex_count + 1 - ret = true - else - ret = false - end - else - Err::LockModeFailer.Fail mode - end - return ret - end -end -Synchronizer_m = Sync_m - -class Sync - include Sync_m -end -Synchronizer = Sync diff --git a/Src/StdLib/ruby/1.9.1/thwait.rb b/Src/StdLib/ruby/1.9.1/thwait.rb deleted file mode 100644 index 57ba8f631..000000000 --- a/Src/StdLib/ruby/1.9.1/thwait.rb +++ /dev/null @@ -1,143 +0,0 @@ -# -# thwait.rb - thread synchronization class -# $Release Version: 0.9 $ -# $Revision: 1.3 $ -# by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd.) - -require "thread.rb" -require "e2mmap.rb" - -# -# This class watches for termination of multiple threads. Basic functionality -# (wait until specified threads have terminated) can be accessed through the -# class method ThreadsWait::all_waits. Finer control can be gained using -# instance methods. -# -# Example: -# -# ThreadsWait.all_wait(thr1, thr2, ...) do |t| -# STDERR.puts "Thread #{t} has terminated." -# end -# -# -# th = ThreadsWait.new(thread1,...) -# th.next_wait # next one to be done -# -# -class ThreadsWait - RCS_ID='-$Id: thwait.rb,v 1.3 1998/06/26 03:19:34 keiju Exp keiju $-' - - extend Exception2MessageMapper - def_exception("ErrNoWaitingThread", "No threads for waiting.") - def_exception("ErrNoFinishedThread", "No finished threads.") - - # - # Waits until all specified threads have terminated. If a block is provided, - # it is executed for each thread as they terminate. - # - def ThreadsWait.all_waits(*threads) # :yield: thread - tw = ThreadsWait.new(*threads) - if block_given? - tw.all_waits do |th| - yield th - end - else - tw.all_waits - end - end - - # - # Creates a ThreadsWait object, specifying the threads to wait on. - # Non-blocking. - # - def initialize(*threads) - @threads = [] - @wait_queue = Queue.new - join_nowait(*threads) unless threads.empty? - end - - # Returns the array of threads that have not terminated yet. - attr :threads - - # - # Returns +true+ if there are no threads in the pool still running. - # - def empty? - @threads.empty? - end - - # - # Returns +true+ if any thread has terminated and is ready to be collected. - # - def finished? - !@wait_queue.empty? - end - - # - # Waits for specified threads to terminate, and returns when one of - # the threads terminated. - # - def join(*threads) - join_nowait(*threads) - next_wait - end - - # - # Specifies the threads that this object will wait for, but does not actually - # wait. - # - def join_nowait(*threads) - threads.flatten! - @threads.concat threads - for th in threads - Thread.start(th) do |t| - begin - t.join - ensure - @wait_queue.push t - end - end - end - end - - # - # Waits until any of the specified threads has terminated, and returns the one - # that does. - # - # If there is no thread to wait, raises +ErrNoWaitingThread+. If +nonblock+ - # is true, and there is no terminated thread, raises +ErrNoFinishedThread+. - # - def next_wait(nonblock = nil) - ThreadsWait.fail ErrNoWaitingThread if @threads.empty? - begin - @threads.delete(th = @wait_queue.pop(nonblock)) - th - rescue ThreadError - ThreadsWait.fail ErrNoFinishedThread - end - end - - # - # Waits until all of the specified threads are terminated. If a block is - # supplied for the method, it is executed for each thread termination. - # - # Raises exceptions in the same manner as +next_wait+. - # - def all_waits - until @threads.empty? - th = next_wait - yield th if block_given? - end - end -end - -ThWait = ThreadsWait - - -# Documentation comments: -# - Source of documentation is evenly split between Nutshell, existing -# comments, and my own rephrasing. -# - I'm not particularly confident that the comments are all exactly correct. -# - The history, etc., up the top appears in the RDoc output. Perhaps it would -# be better to direct that not to appear, and put something else there -# instead. diff --git a/Src/StdLib/ruby/1.9.1/tracer.rb b/Src/StdLib/ruby/1.9.1/tracer.rb deleted file mode 100644 index 3e5d6e226..000000000 --- a/Src/StdLib/ruby/1.9.1/tracer.rb +++ /dev/null @@ -1,195 +0,0 @@ -# tracer.rb - -# $Release Version: 0.3$ -# $Revision: 1.12 $ -# by Keiju ISHITSUKA(keiju@ishitsuka.com) -# -# -- -# -# -# -require "thread" - -# -# tracer main class -# -class Tracer - class << self - attr_accessor :verbose - alias verbose? verbose - - attr_accessor :stdout - attr_reader :stdout_mutex - - # display process id? - attr_accessor :display_process_id - alias display_process_id? display_process_id - - # display thread id? - attr_accessor :display_thread_id - alias display_thread_id? display_thread_id - - # display builtin method call? - attr_accessor :display_c_call - alias display_c_call? display_c_call - end - Tracer::stdout = STDOUT - Tracer::verbose = false - Tracer::display_process_id = false - Tracer::display_thread_id = true - Tracer::display_c_call = false - - @stdout_mutex = Mutex.new - - EVENT_SYMBOL = { - "line" => "-", - "call" => ">", - "return" => "<", - "class" => "C", - "end" => "E", - "raise" => "^", - "c-call" => "}", - "c-return" => "{", - "unknown" => "?" - } - - def initialize - @threads = Hash.new - if defined? Thread.main - @threads[Thread.main.object_id] = 0 - else - @threads[Thread.current.object_id] = 0 - end - - @get_line_procs = {} - - @filters = [] - end - - def stdout - Tracer.stdout - end - - def on - if block_given? - on - begin - yield - ensure - off - end - else - set_trace_func method(:trace_func).to_proc - stdout.print "Trace on\n" if Tracer.verbose? - end - end - - def off - set_trace_func nil - stdout.print "Trace off\n" if Tracer.verbose? - end - - def add_filter(p = proc) - @filters.push p - end - - def set_get_line_procs(file, p = proc) - @get_line_procs[file] = p - end - - def get_line(file, line) - if p = @get_line_procs[file] - return p.call(line) - end - - unless list = SCRIPT_LINES__[file] - begin - f = File::open(file) - begin - SCRIPT_LINES__[file] = list = f.readlines - ensure - f.close - end - rescue - SCRIPT_LINES__[file] = list = [] - end - end - - if l = list[line - 1] - l - else - "-\n" - end - end - - def get_thread_no - if no = @threads[Thread.current.object_id] - no - else - @threads[Thread.current.object_id] = @threads.size - end - end - - def trace_func(event, file, line, id, binding, klass, *) - return if file == __FILE__ - - for p in @filters - return unless p.call event, file, line, id, binding, klass - end - - return unless Tracer::display_c_call? or - event != "c-call" && event != "c-return" - - Tracer::stdout_mutex.synchronize do - if EVENT_SYMBOL[event] - stdout.printf("<%d>", $$) if Tracer::display_process_id? - stdout.printf("#%d:", get_thread_no) if Tracer::display_thread_id? - if line == 0 - source = "?\n" - else - source = get_line(file, line) - end - printf("%s:%d:%s:%s: %s", - file, - line, - klass || '', - EVENT_SYMBOL[event], - source) - end - end - - end - - Single = new - def Tracer.on - if block_given? - Single.on{yield} - else - Single.on - end - end - - def Tracer.off - Single.off - end - - def Tracer.set_get_line_procs(file_name, p = proc) - Single.set_get_line_procs(file_name, p) - end - - def Tracer.add_filter(p = proc) - Single.add_filter(p) - end -end - -SCRIPT_LINES__ = {} unless defined? SCRIPT_LINES__ - -if $0 == __FILE__ - # direct call - - $0 = ARGV[0] - ARGV.shift - Tracer.on - require $0 -elsif caller.size <= 1 - Tracer.on -end diff --git a/Src/StdLib/ruby/1.9.1/ubygems.rb b/Src/StdLib/ruby/1.9.1/ubygems.rb deleted file mode 100644 index 66a8a589c..000000000 --- a/Src/StdLib/ruby/1.9.1/ubygems.rb +++ /dev/null @@ -1,10 +0,0 @@ -# This file allows for the running of rubygems with a nice -# command line look-and-feel: ruby -rubygems foo.rb -#-- -# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others. -# All rights reserved. -# See LICENSE.txt for permissions. -#++ - - -require 'rubygems' diff --git a/Src/StdLib/ruby/1.9.1/win32/registry.rb b/Src/StdLib/ruby/1.9.1/win32/registry.rb deleted file mode 100644 index 356deea77..000000000 --- a/Src/StdLib/ruby/1.9.1/win32/registry.rb +++ /dev/null @@ -1,845 +0,0 @@ -require 'dl/import' -module Win32 - -=begin rdoc -= Win32 Registry - -win32/registry is registry accessor library for Win32 platform. -It uses dl/import to call Win32 Registry APIs. - -== example - Win32::Registry::HKEY_CURRENT_USER.open('SOFTWARE\foo') do |reg| - value = reg['foo'] # read a value - value = reg['foo', Win32::Registry::REG_SZ] # read a value with type - type, value = reg.read('foo') # read a value - 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 - end - -= Reference - -== Win32::Registry class - ---- info - ---- num_keys - ---- max_key_length - ---- num_values - ---- max_value_name_length - ---- max_value_length - ---- descriptor_length - ---- wtime - Returns an item of key information. - -=== constants ---- HKEY_CLASSES_ROOT - ---- HKEY_CURRENT_USER - ---- HKEY_LOCAL_MACHINE - ---- HKEY_PERFORMANCE_DATA - ---- HKEY_CURRENT_CONFIG - ---- HKEY_DYN_DATA - - Win32::Registry object whose key is predefined key. -For detail, see the MSDN[http://msdn.microsoft.com/library/en-us/sysinfo/base/predefined_keys.asp] article. - -=end rdoc - - class Registry - - # - # For detail, see the MSDN[http://msdn.microsoft.com/library/en-us/sysinfo/base/registry.asp]. - # - # --- HKEY_* - # - # Predefined key ((*handle*)). - # These are Integer, not Win32::Registry. - # - # --- REG_* - # - # Registry value type. - # - # --- KEY_* - # - # Security access mask. - # - # --- KEY_OPTIONS_* - # - # Key options. - # - # --- REG_CREATED_NEW_KEY - # - # --- REG_OPENED_EXISTING_KEY - # - # If the key is created newly or opened existing key. - # See also Registry#disposition method. - module Constants - HKEY_CLASSES_ROOT = 0x80000000 - HKEY_CURRENT_USER = 0x80000001 - HKEY_LOCAL_MACHINE = 0x80000002 - HKEY_USERS = 0x80000003 - HKEY_PERFORMANCE_DATA = 0x80000004 - HKEY_PERFORMANCE_TEXT = 0x80000050 - HKEY_PERFORMANCE_NLSTEXT = 0x80000060 - HKEY_CURRENT_CONFIG = 0x80000005 - HKEY_DYN_DATA = 0x80000006 - - REG_NONE = 0 - REG_SZ = 1 - REG_EXPAND_SZ = 2 - REG_BINARY = 3 - REG_DWORD = 4 - REG_DWORD_LITTLE_ENDIAN = 4 - REG_DWORD_BIG_ENDIAN = 5 - REG_LINK = 6 - REG_MULTI_SZ = 7 - REG_RESOURCE_LIST = 8 - REG_FULL_RESOURCE_DESCRIPTOR = 9 - REG_RESOURCE_REQUIREMENTS_LIST = 10 - REG_QWORD = 11 - REG_QWORD_LITTLE_ENDIAN = 11 - - STANDARD_RIGHTS_READ = 0x00020000 - STANDARD_RIGHTS_WRITE = 0x00020000 - KEY_QUERY_VALUE = 0x0001 - KEY_SET_VALUE = 0x0002 - KEY_CREATE_SUB_KEY = 0x0004 - KEY_ENUMERATE_SUB_KEYS = 0x0008 - KEY_NOTIFY = 0x0010 - KEY_CREATE_LINK = 0x0020 - KEY_READ = STANDARD_RIGHTS_READ | - KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS | KEY_NOTIFY - KEY_WRITE = STANDARD_RIGHTS_WRITE | - KEY_SET_VALUE | KEY_CREATE_SUB_KEY - KEY_EXECUTE = KEY_READ - KEY_ALL_ACCESS = KEY_READ | KEY_WRITE | KEY_CREATE_LINK - - REG_OPTION_RESERVED = 0x0000 - REG_OPTION_NON_VOLATILE = 0x0000 - REG_OPTION_VOLATILE = 0x0001 - REG_OPTION_CREATE_LINK = 0x0002 - REG_OPTION_BACKUP_RESTORE = 0x0004 - REG_OPTION_OPEN_LINK = 0x0008 - REG_LEGAL_OPTION = REG_OPTION_RESERVED | - REG_OPTION_NON_VOLATILE | REG_OPTION_CREATE_LINK | - REG_OPTION_BACKUP_RESTORE | REG_OPTION_OPEN_LINK - - REG_CREATED_NEW_KEY = 1 - REG_OPENED_EXISTING_KEY = 2 - - REG_WHOLE_HIVE_VOLATILE = 0x0001 - REG_REFRESH_HIVE = 0x0002 - REG_NO_LAZY_FLUSH = 0x0004 - REG_FORCE_RESTORE = 0x0008 - - MAX_KEY_LENGTH = 514 - MAX_VALUE_LENGTH = 32768 - end - include Constants - include Enumerable - - # - # Error - # - class Error < ::StandardError - module Kernel32 - extend DL::Importer - dlload "kernel32.dll" - end - FormatMessageA = Kernel32.extern "int FormatMessageA(int, void *, int, int, void *, int, void *)", :stdcall - def initialize(code) - @code = code - msg = "\0".force_encoding(Encoding::ASCII_8BIT) * 1024 - len = FormatMessageA.call(0x1200, 0, code, 0, msg, 1024, 0) - msg = msg[0, len].force_encoding(Encoding.find(Encoding.locale_charmap)) - super msg.tr("\r", '').chomp - end - attr_reader :code - end - - # - # Predefined Keys - # - class PredefinedKey < Registry - def initialize(hkey, keyname) - @hkey = hkey - @parent = nil - @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 method 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.to_s) - end - end - - # - # Win32 APIs - # - module API - extend DL::Importer - dlload "advapi32.dll" - [ - "long RegOpenKeyExA(void *, void *, long, long, void *)", - "long RegCreateKeyExA(void *, void *, long, long, long, long, void *, void *)", - "long RegEnumValueA(void *, long, void *, void *, void *, void *, void *, void *)", - "long RegEnumKeyExA(void *, long, void *, void *, void *, void *, void *, void *)", - "long RegQueryValueExA(void *, void *, void *, void *, void *, void *)", - "long RegSetValueExA(void *, void *, long, long, void *, long)", - "long RegDeleteValue(void *, void *)", - "long RegDeleteKey(void *, void *)", - "long RegFlushKey(void *)", - "long RegCloseKey(void *)", - "long RegQueryInfoKey(void *, void *, void *, void *, void *, void *, void *, void *, void *, void *, void *, void *)", - ].each do |fn| - cfunc = extern fn, :stdcall - const_set cfunc.name.intern, cfunc - 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) - check RegCreateKeyExA.call(hkey, name, 0, 0, opt, desired, - 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) - wtime = ' ' * 8 - 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) - check RegQueryValueExA.call(hkey, name, 0, type, 0, size) - data = ' ' * unpackdw(size) - check RegQueryValueExA.call(hkey, name, 0, type, data, size) - [ unpackdw(type), data[0, unpackdw(size)] ] - end - - 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) - values = packdw(0) - maxvaluenamelen = packdw(0) - maxvaluelen = packdw(0) - secdescs = packdw(0) - wtime = ' ' * 8 - check RegQueryInfoKey.call(hkey, 0, 0, 0, subkeys, maxsubkeylen, 0, - values, maxvaluenamelen, maxvaluelen, secdescs, wtime) - [ unpackdw(subkeys), unpackdw(maxsubkeylen), unpackdw(values), - unpackdw(maxvaluenamelen), unpackdw(maxvaluelen), - unpackdw(secdescs), unpackqw(wtime) ] - end - end - - # - # Replace %\w+% into the environment value of what is contained between the %'s - # This method is used for REG_EXPAND_SZ. - # - # For detail, see expandEnvironmentStrings[http://msdn.microsoft.com/library/en-us/sysinfo/base/expandenvironmentstrings.asp] \Win32 \API. - # - 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 - REG_DWORD_BIG_ENDIAN REG_LINK REG_MULTI_SZ - REG_RESOURCE_LIST REG_FULL_RESOURCE_DESCRIPTOR - REG_RESOURCE_REQUIREMENTS_LIST REG_QWORD - ].each do |type| - @@type2name[Constants.const_get(type)] = type - end - - # - # Convert registry type value to readable string. - # - def self.type2name(type) - @@type2name[type] || type.to_s - end - - # - # Convert 64-bit FILETIME integer into Time object. - # - def self.wtime2time(wtime) - Time.at((wtime - 116444736000000000) / 10000000) - end - - # - # Convert Time object or Integer object into 64-bit FILETIME. - # - def self.time2wtime(time) - time.to_i * 10000000 + 116444736000000000 - end - - # - # constructor - # - private_class_method :new - - # - # --- Registry.open(key, subkey, desired = KEY_READ, opt = REG_OPTION_RESERVED) - # - # --- Registry.open(key, subkey, desired = KEY_READ, opt = REG_OPTION_RESERVED) { |reg| ... } - # - # Open the registry key subkey under key. - # key is Win32::Registry object of parent key. - # You can use predefined key HKEY_* (see Constants) - # desired and opt is access mask and key option. - # For detail, see the MSDN[http://msdn.microsoft.com/library/en-us/sysinfo/base/regopenkeyex.asp]. - # If block is given, the key is closed automatically. - def self.open(hkey, subkey, desired = KEY_READ, opt = REG_OPTION_RESERVED) - subkey = subkey.chomp('\\') - newkey = API.OpenKey(hkey.hkey, subkey, opt, desired) - obj = new(newkey, hkey, subkey, REG_OPENED_EXISTING_KEY) - if block_given? - begin - yield obj - ensure - obj.close - end - else - obj - end - end - - # - # --- 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 Constants) - # - # If subkey is already exists, key is opened and Registry#created? - # method will return false. - # - # If block is given, the key is closed automatically. - # - def self.create(hkey, subkey, desired = KEY_ALL_ACCESS, opt = REG_OPTION_RESERVED) - newkey, disp = API.CreateKey(hkey.hkey, subkey, opt, desired) - obj = new(newkey, hkey, subkey, disp) - if block_given? - begin - yield obj - ensure - obj.close - end - else - obj - end - end - - # - # finalizer - # - @@final = proc { |hkey| proc { API.CloseKey(hkey[0]) if hkey[0] } } - - # - # initialize - # - def initialize(hkey, parent, keyname, disposition) - @hkey = hkey - @parent = parent - @keyname = keyname - @disposition = disposition - @hkeyfinal = [ hkey ] - ObjectSpace.define_finalizer self, @@final.call(@hkeyfinal) - end - - # Returns key handle value. - attr_reader :hkey - # Win32::Registry object of parent key, or nil if predefeined key. - attr_reader :parent - # Same as subkey value of Registry.open or - # Registry.create method. - attr_reader :keyname - # Disposition value (REG_CREATED_NEW_KEY or REG_OPENED_EXISTING_KEY). - attr_reader :disposition - - # - # Returns if key is created ((*newly*)). - # (see Registry.create) -- basically you call create - # then when you call created? on the instance returned - # it will tell if it was successful or not - # - def created? - @disposition == REG_CREATED_NEW_KEY - end - - # - # Returns if key is not closed. - # - def open? - !@hkey.nil? - end - - # - # Full path of key such as 'HKEY_CURRENT_USER\SOFTWARE\foo\bar'. - # - def name - parent = self - name = @keyname - while parent = parent.parent - name = parent.keyname + '\\' + name - end - name - end - - def inspect - "\#" - end - - # - # marshalling is not allowed - # - def _dump(depth) - raise TypeError, "can't dump Win32::Registry" - end - - # - # Same as Win32::Registry.open (self, subkey, desired, opt) - # - def open(subkey, desired = KEY_READ, opt = REG_OPTION_RESERVED, &blk) - self.class.open(self, subkey, desired, opt, &blk) - end - - # - # Same as Win32::Registry.create (self, subkey, desired, opt) - # - def create(subkey, desired = KEY_ALL_ACCESS, opt = REG_OPTION_RESERVED, &blk) - self.class.create(self, subkey, desired, opt, &blk) - end - - # - # Close key. - # - # After close, most method raise an error. - # - def close - API.CloseKey(@hkey) - @hkey = @parent = @keyname = nil - @hkeyfinal[0] = nil - end - - # - # Enumerate values. - # - def each_value - index = 0 - while true - begin - subkey = API.EnumValue(@hkey, index) - rescue Error - break - end - begin - type, data = read(subkey) - rescue Error - next - end - yield subkey, type, data - index += 1 - end - index - end - alias each each_value - - # - # Enumerate subkeys. - # - # subkey is String which contains name of subkey. - # wtime is last write time as FILETIME (64-bit integer). - # (see Registry.wtime2time) - # - def each_key - index = 0 - while true - begin - subkey, wtime = API.EnumKey(@hkey, index) - rescue Error - break - end - yield subkey, wtime - index += 1 - end - index - end - - # - # return keys as an array - # - def keys - keys_ary = [] - each_key { |key,| keys_ary << key } - keys_ary - end - - # 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 Win32::Registry::Constants module) - # data is value data, its class is: - # :REG_SZ, REG_EXPAND_SZ - # String - # :REG_MULTI_SZ - # Array of String - # :REG_DWORD, REG_DWORD_BIG_ENDIAN, REG_QWORD - # Integer - # :REG_BINARY - # String (contains binary data) - # - # When rtype is specified, the value type must be included by - # rtype array, or TypeError is raised. - def read(name, *rtype) - type, data = API.QueryValue(@hkey, name) - unless rtype.empty? or rtype.include?(type) - raise TypeError, "Type mismatch (expect #{rtype.inspect} but #{type} present)" - end - case type - when REG_SZ, REG_EXPAND_SZ - [ type, data.chop ] - when REG_MULTI_SZ - [ type, data.split(/\0/) ] - when REG_BINARY - [ type, data ] - when REG_DWORD - [ type, API.unpackdw(data) ] - when REG_DWORD_BIG_ENDIAN - [ type, data.unpack('N')[0] ] - when REG_QWORD - [ type, API.unpackqw(data) ] - else - raise TypeError, "Type #{type} is not supported." - end - end - - # - # Read a registry value named name and return its value data. - # The class of value is same as #read 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 #read method. - # - def [](name, *rtype) - type, data = read(name, *rtype) - case type - when REG_SZ, REG_DWORD, REG_QWORD, REG_MULTI_SZ - data - when REG_EXPAND_SZ - Registry.expand_environ(data) - else - raise TypeError, "Type #{type} is not supported." - end - end - - # 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. - def read_s(name) - read(name, REG_SZ)[1] - end - - # - # 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. - # - def read_s_expand(name) - type, data = read(name, REG_SZ, REG_EXPAND_SZ) - if type == REG_EXPAND_SZ - Registry.expand_environ(data) - else - data - end - end - - # - # 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. - # - def read_i(name) - read(name, REG_DWORD, REG_DWORD_BIG_ENDIAN, REG_QWORD)[1] - end - - # - # 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. - # - def read_bin(name) - read(name, REG_BINARY)[1] - end - - # - # Write data to a registry value named name. - # When name is nil, write to the `default' value. - # - # type is type value. (see Registry::Constants module) - # Class of data must be same as which #read - # method returns. - # - def write(name, type, data) - case type - when REG_SZ, REG_EXPAND_SZ - data = data.to_s + "\0" - when REG_MULTI_SZ - data = data.to_a.join("\0") + "\0\0" - when REG_BINARY - data = data.to_s - when REG_DWORD - data = API.packdw(data.to_i) - when REG_DWORD_BIG_ENDIAN - data = [data.to_i].pack('N') - when REG_QWORD - data = API.packqw(data.to_i) - else - raise TypeError, "Unsupported type #{type}" - end - API.SetValue(@hkey, name, type, data, data.length) - end - - # - # Write 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 - # REG_DWORD - # :String - # REG_SZ - # :Array - # REG_MULTI_SZ - # - def []=(name, rtype, value = nil) - if value - write name, rtype, value - else - case value = rtype - when Integer - write name, REG_DWORD, value - when String - write name, REG_SZ, value - when Array - write name, REG_MULTI_SZ, value - else - raise TypeError, "Unexpected type #{value.class}" - end - end - value - end - - # - # 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). - # - def write_s(name, value) - write name, REG_SZ, value.to_s - end - - # - # 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). - # - def write_i(name, value) - write name, REG_DWORD, value.to_i - end - - # - # 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). - # - def write_bin(name, value) - write name, REG_BINARY, value.to_s - end - - # - # Delete a registry value named name. - # We can not delete the `default' value. - # - def delete_value(name) - API.DeleteValue(@hkey, name) - end - alias delete delete_value - - # - # 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. - # - def delete_key(name, recursive = false) - if recursive - open(name, KEY_ALL_ACCESS) do |reg| - reg.keys.each do |key| - begin - reg.delete_key(key, true) - rescue Error - # - end - end - end - API.DeleteKey(@hkey, name) - else - begin - API.EnumKey @hkey, 0 - rescue Error - return API.DeleteKey(@hkey, name) - end - raise Error.new(5) ## ERROR_ACCESS_DENIED - end - end - - # - # Write all the attributes into the registry file. - # - def flush - API.FlushKey @hkey - end - - # - # Returns key information as Array of: - # :num_keys - # The number of subkeys. - # :max_key_length - # Maximum length of name of subkeys. - # :num_values - # The number of values. - # :max_value_name_length - # Maximum length of name of values. - # :max_value_length - # Maximum length of value of values. - # :descriptor_length - # Length of security descriptor. - # :wtime - # Last write time as FILETIME(64-bit integer) - # - # For detail, see RegQueryInfoKey[http://msdn.microsoft.com/library/en-us/sysinfo/base/regqueryinfokey.asp] Win32 API. - # - def info - API.QueryInfoKey(@hkey) - end - - # - # Returns an item of key information. - # - %w[ - num_keys max_key_length - num_values max_value_name_length max_value_length - descriptor_length wtime - ].each_with_index do |s, i| - eval <<-__END__ - def #{s} - info[#{i}] - end - __END__ - end - end -end diff --git a/Src/StdLib/ruby/1.9.1/win32/resolv.rb b/Src/StdLib/ruby/1.9.1/win32/resolv.rb deleted file mode 100644 index 80fc8a09c..000000000 --- a/Src/StdLib/ruby/1.9.1/win32/resolv.rb +++ /dev/null @@ -1,379 +0,0 @@ -=begin -= Win32 DNS and DHCP I/F - -=end - -require "dl/import" -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? - search = nil - else - search.delete("") - search.uniq! - end - if nameserver.empty? - nameserver = nil - else - nameserver.delete("") - nameserver.delete("0.0.0.0") - nameserver.uniq! - end - [ search, nameserver ] - end - -module Kernel32 - extend DL::Importer - dlload "kernel32" -end -getv = Kernel32.extern "int GetVersionExA(void *)", :stdcall -info = [ 148, 0, 0, 0, 0 ].pack('V5') + "\0" * 128 -getv.call(info) -if info.unpack('V5')[4] == 2 # VER_PLATFORM_WIN32_NT -#==================================================================== -# Windows NT -#==================================================================== - module_eval <<-'__EOS__', __FILE__, __LINE__+1 - TCPIP_NT = 'SYSTEM\CurrentControlSet\Services\Tcpip\Parameters' - - class << self - private - def get_hosts_dir - Registry::HKEY_LOCAL_MACHINE.open(TCPIP_NT) do |reg| - reg.read_s_expand('DataBasePath') - end - end - - def get_info - search = nil - nameserver = [] - Registry::HKEY_LOCAL_MACHINE.open(TCPIP_NT) do |reg| - begin - slist = reg.read_s('SearchList') - search = slist.split(/,\s*/) unless slist.empty? - rescue Registry::Error - end - - if add_search = search.nil? - search = [] - begin - nvdom = reg.read_s('NV Domain') - unless nvdom.empty? - @search = [ nvdom ] - if reg.read_i('UseDomainNameDevolution') != 0 - if /^[\w\d]+\./ =~ nvdom - devo = $' - end - end - end - rescue Registry::Error - end - end - - reg.open('Interfaces') do |h| - h.each_key do |iface,| - h.open(iface) do |regif| - begin - [ 'NameServer', 'DhcpNameServer' ].each do |key| - begin - ns = regif.read_s(key) - rescue - else - unless ns.empty? - nameserver.concat(ns.split(/[,\s]\s*/)) - break - end - end - end - rescue Registry::Error - end - - if add_search - begin - [ 'Domain', 'DhcpDomain' ].each do |key| - dom = regif.read_s(key) - unless dom.empty? - search.concat(dom.split(/,\s*/)) - break - end - end - rescue Registry::Error - end - end - end - end - end - search << devo if add_search and devo - end - [ search.uniq, nameserver.uniq ] - end - end - __EOS__ -else -#==================================================================== -# Windows 9x -#==================================================================== - module_eval <<-'__EOS__', __FILE__, __LINE__+1 - 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 = [] - begin - Registry::HKEY_LOCAL_MACHINE.open(TCPIP_9X) do |reg| - if reg.read_s("EnableDNS") == "1" - domain = reg.read_s("Domain") - ns = reg.read_s("NameServer") - slist = reg.read_s("SearchList") - search << domain unless domain.empty? - search.concat(slist.split(/,\s*/)) - nameserver.concat(ns.split(/[,\s]\s*/)) - end - end - rescue Registry::Error - end - - dhcpinfo = get_dhcpinfo - search.concat(dhcpinfo[0]) - nameserver.concat(dhcpinfo[1]) - [ search, nameserver ] - end - - def get_dhcpinfo - macaddrs = {} - ipaddrs = {} - WsControl.get_iflist.each do |index, macaddr, *ipaddr| - macaddrs[macaddr] = 1 - ipaddr.each { |ipaddr| ipaddrs[ipaddr] = 1 } - end - iflist = [ macaddrs, ipaddrs ] - - search = [] - nameserver = [] - version = -1 - Registry::HKEY_LOCAL_MACHINE.open(DHCP_9X) do |reg| - begin - 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| - dom, ns = get_dhcpinfo_key(version, regdi, iflist) - search << dom if dom - nameserver.concat(ns) if ns - end - end - end - end - [ search, nameserver ] - end - - def get_dhcpinfo_95(reg) - dhcp = reg.read_bin("DhcpInfo") - [ - API.unpackdw(dhcp[4..7]), - API.unpackdw(dhcp[8..11]), - 1, - dhcp[45..50], - reg.read_bin("OptionInfo"), - ] - end - - def get_dhcpinfo_98(reg) - [ - API.unpackdw(reg.read_bin("DhcpIPAddress")), - API.unpackdw(reg.read_bin("DhcpSubnetMask")), - API.unpackdw(reg.read_bin("HardwareType")), - reg.read_bin("HardwareAddress"), - reg.read_bin("OptionInfo"), - ] - end - - def get_dhcpinfo_key(version, reg, iflist) - info = case version - when 1 - get_dhcpinfo_95(reg) - when 2 - get_dhcpinfo_98(reg) - else - begin - get_dhcpinfo_98(reg) - rescue Registry::Error - get_dhcpinfo_95(reg) - end - end - ipaddr, netmask, hwtype, macaddr, opt = info - throw :not_used unless - ipaddr and ipaddr != 0 and - netmask and netmask != 0 and - macaddr and macaddr.size == 6 and - hwtype == 1 and - iflist[0][macaddr] and iflist[1][ipaddr] - - size = opt.size - idx = 0 - while idx <= size - opttype = opt[idx] - optsize = opt[idx + 1] - optval = opt[idx + 2, optsize] - case opttype - when 0xFF ## term - break - when 0x0F ## domain - domain = optval.chomp("\0") - when 0x06 ## dns - nameserver = optval.scan(/..../).collect { |addr| - "%d.%d.%d.%d" % addr.unpack('C4') - } - end - idx += optsize + 2 - end - [ domain, nameserver ] - rescue Registry::Error - throw :not_used - end - end - - module WsControl - module WSock32 - extend DL::Importer - dlload "wsock32.dll" - end - WsControl = WSock32.extern "int WsControl(int, int, void *, void *, void *, void *", :stdcall - WSAGetLastError = WSock32.extern "int WSAGetLastError(void)", :stdcall - - MAX_TDI_ENTITIES = 512 - IPPROTO_TCP = 6 - WSCTL_TCP_QUERY_INFORMATION = 0 - INFO_CLASS_GENERIC = 0x100 - INFO_CLASS_PROTOCOL = 0x200 - INFO_TYPE_PROVIDER = 0x100 - ENTITY_LIST_ID = 0 - GENERIC_ENTITY = 0 - CL_NL_ENTITY = 0x301 - IF_ENTITY = 0x200 - ENTITY_TYPE_ID = 1 - CL_NL_IP = 0x303 - 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) - reqinfo = [ - ## TDIEntityID - tei_entity, tei_instance, - ## TDIObjectID - toi_class, toi_type, toi_id, - ## TCP_REQUEST_INFORMATION_EX - "" - ].pack('VVVVVa16') - reqsize = API.packdw(reqinfo.size) - buff = "\0" * buffsize - buffsize = API.packdw(buffsize) - result = WsControl.call( - IPPROTO_TCP, - WSCTL_TCP_QUERY_INFORMATION, - reqinfo, reqsize, - buff, buffsize) - if result != 0 - raise RuntimeError, "WsControl failed.(#{result})" - end - [ buff, API.unpackdw(buffsize) ] - end - private_class_method :wsctl - - def self.get_iflist - # Get TDI Entity List - entities, size = - wsctl(GENERIC_ENTITY, 0, - INFO_CLASS_GENERIC, - INFO_TYPE_PROVIDER, - ENTITY_LIST_ID, - MAX_TDI_ENTITIES * 8) # sizeof(TDIEntityID) - entities = entities[0, size]. - scan(/.{8}/). - collect { |e| e.unpack('VV') } - - # Get MIB Interface List - iflist = [] - ifcount = 0 - entities.each do |entity, instance| - if( (entity & IF_ENTITY)>0 ) - ifcount += 1 - etype, = wsctl(entity, instance, - INFO_CLASS_GENERIC, - INFO_TYPE_PROVIDER, - ENTITY_TYPE_ID, - 4) - if( (API.unpackdw(etype) & IF_MIB)==IF_MIB ) - ifentry, = wsctl(entity, instance, - INFO_CLASS_PROTOCOL, - INFO_TYPE_PROVIDER, - IF_MIB_STATS_ID, - 21 * 4 + 8 + 130) # sizeof(IFEntry) - iflist << [ - API.unpackdw(ifentry[0,4]), - ifentry[20, 6] - ] - end - end - end - - # Get IP Addresses - entities.each do |entity, instance| - if entity == CL_NL_ENTITY - etype, = wsctl(entity, instance, - INFO_CLASS_GENERIC, - INFO_TYPE_PROVIDER, - ENTITY_TYPE_ID, - 4) - if API.unpackdw(etype) == CL_NL_IP - ipentries, = wsctl(entity, instance, - INFO_CLASS_PROTOCOL, - INFO_TYPE_PROVIDER, - IP_MIB_ADDRTABLE_ENTRY_ID, - 24 * (ifcount+1)) # sizeof(IPAddrEntry) - ipentries.scan(/.{24}/) do |ipentry| - ipaddr, index = ipentry.unpack('VV') - if ifitem = iflist.assoc(index) - ifitem << ipaddr - end - end - end - end - end - iflist - end - end - __EOS__ -end -#==================================================================== - end -end diff --git a/Src/StdLib/ruby/1.9.1/win32/sspi.rb b/Src/StdLib/ruby/1.9.1/win32/sspi.rb deleted file mode 100644 index 4c54e7221..000000000 --- a/Src/StdLib/ruby/1.9.1/win32/sspi.rb +++ /dev/null @@ -1,330 +0,0 @@ -# -# = win32/sspi.rb -# -# Copyright (c) 2006-2007 Justin Bailey -# -# Written and maintained by Justin Bailey . -# -# 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. -# - -require 'Win32API' - -# Implements bindings to Win32 SSPI functions, focused on authentication to a proxy server over HTTP. -module Win32 - module SSPI - # Specifies how credential structure requested will be used. Only SECPKG_CRED_OUTBOUND is used - # here. - SECPKG_CRED_INBOUND = 0x00000001 - SECPKG_CRED_OUTBOUND = 0x00000002 - SECPKG_CRED_BOTH = 0x00000003 - - # Format of token. NETWORK format is used here. - SECURITY_NATIVE_DREP = 0x00000010 - SECURITY_NETWORK_DREP = 0x00000000 - - # InitializeSecurityContext Requirement flags - ISC_REQ_REPLAY_DETECT = 0x00000004 - ISC_REQ_SEQUENCE_DETECT = 0x00000008 - ISC_REQ_CONFIDENTIALITY = 0x00000010 - ISC_REQ_USE_SESSION_KEY = 0x00000020 - ISC_REQ_PROMPT_FOR_CREDS = 0x00000040 - ISC_REQ_CONNECTION = 0x00000800 - - # Win32 API Functions. Uses Win32API to bind methods to constants contained in class. - module API - # Can be called with AcquireCredentialsHandle.call() - AcquireCredentialsHandle = Win32API.new("secur32", "AcquireCredentialsHandle", 'ppLpppppp', 'L') - # Can be called with InitializeSecurityContext.call() - InitializeSecurityContext = Win32API.new("secur32", "InitializeSecurityContext", 'pppLLLpLpppp', 'L') - # Can be called with DeleteSecurityContext.call() - DeleteSecurityContext = Win32API.new("secur32", "DeleteSecurityContext", 'P', 'L') - # Can be called with FreeCredentialsHandle.call() - FreeCredentialsHandle = Win32API.new("secur32", "FreeCredentialsHandle", 'P', 'L') - end - - # SecHandle struct - class SecurityHandle - def upper - @struct.unpack("LL")[1] - end - - def lower - @struct.unpack("LL")[0] - end - - def to_p - @struct ||= "\0" * 8 - end - end - - # Some familiar aliases for the SecHandle structure - CredHandle = CtxtHandle = SecurityHandle - - # TimeStamp struct - class TimeStamp - attr_reader :struct - - def to_p - @struct ||= "\0" * 8 - end - end - - # Creates binary representaiton of a SecBufferDesc structure, - # including the SecBuffer contained inside. - class SecurityBuffer - - SECBUFFER_TOKEN = 2 # Security token - - TOKENBUFSIZE = 12288 - SECBUFFER_VERSION = 0 - - def initialize(buffer = nil) - @buffer = buffer || "\0" * TOKENBUFSIZE - @bufferSize = @buffer.length - @type = SECBUFFER_TOKEN - end - - def bufferSize - unpack - @bufferSize - end - - def bufferType - unpack - @type - end - - def token - unpack - @buffer - end - - def to_p - # Assumption is that when to_p is called we are going to get a packed structure. Therefore, - # set @unpacked back to nil so we know to unpack when accessors are next accessed. - @unpacked = nil - # Assignment of inner structure to variable is very important here. Without it, - # will not be able to unpack changes to the structure. Alternative, nested unpacks, - # does not work (i.e. @struct.unpack("LLP12")[2].unpack("LLP12") results in "no associated pointer") - @sec_buffer ||= [@bufferSize, @type, @buffer].pack("LLP") - @struct ||= [SECBUFFER_VERSION, 1, @sec_buffer].pack("LLP") - end - - private - - # Unpacks the SecurityBufferDesc structure into member variables. We - # only want to do this once per struct, so the struct is deleted - # after unpacking. - def unpack - if ! @unpacked && @sec_buffer && @struct - @bufferSize, @type = @sec_buffer.unpack("LL") - @buffer = @sec_buffer.unpack("LLP#{@bufferSize}")[2] - @struct = nil - @sec_buffer = nil - @unpacked = true - end - end - end - - # SEC_WINNT_AUTH_IDENTITY structure - class Identity - SEC_WINNT_AUTH_IDENTITY_ANSI = 0x1 - - attr_accessor :user, :domain, :password - - def initialize(user = nil, domain = nil, password = nil) - @user = user - @domain = domain - @password = password - @flags = SEC_WINNT_AUTH_IDENTITY_ANSI - end - - def to_p - [@user, @user ? @user.length : 0, - @domain, @domain ? @domain.length : 0, - @password, @password ? @password.length : 0, - @flags].pack("PLPLPLL") - end - end - - # Takes a return result from an SSPI function and interprets the value. - class SSPIResult - # Good results - SEC_E_OK = 0x00000000 - SEC_I_CONTINUE_NEEDED = 0x00090312 - - # These are generally returned by InitializeSecurityContext - SEC_E_INSUFFICIENT_MEMORY = 0x80090300 - SEC_E_INTERNAL_ERROR = 0x80090304 - SEC_E_INVALID_HANDLE = 0x80090301 - SEC_E_INVALID_TOKEN = 0x80090308 - SEC_E_LOGON_DENIED = 0x8009030C - SEC_E_NO_AUTHENTICATING_AUTHORITY = 0x80090311 - SEC_E_NO_CREDENTIALS = 0x8009030E - SEC_E_TARGET_UNKNOWN = 0x80090303 - SEC_E_UNSUPPORTED_FUNCTION = 0x80090302 - SEC_E_WRONG_PRINCIPAL = 0x80090322 - - # These are generally returned by AcquireCredentialsHandle - SEC_E_NOT_OWNER = 0x80090306 - SEC_E_SECPKG_NOT_FOUND = 0x80090305 - SEC_E_UNKNOWN_CREDENTIALS = 0x8009030D - - @@map = {} - constants.each { |v| @@map[self.const_get(v.to_s)] = v } - - attr_reader :value - - def initialize(value) - # convert to unsigned long - value = [value].pack("L").unpack("L").first - raise "#{value.to_s(16)} is not a recognized result" unless @@map.has_key? value - @value = value - end - - def to_s - @@map[@value].to_s - end - - def ok? - @value == SEC_I_CONTINUE_NEEDED || @value == SEC_E_OK - end - - def ==(other) - if other.is_a?(SSPIResult) - @value == other.value - elsif other.is_a?(Integer) - @value == @@map[other] - else - false - end - end - end - - # Handles "Negotiate" type authentication. Geared towards authenticating with a proxy server over HTTP - class NegotiateAuth - attr_accessor :credentials, :context, :contextAttributes, :user, :domain - - # Default request flags for SSPI functions - REQUEST_FLAGS = ISC_REQ_CONFIDENTIALITY | ISC_REQ_REPLAY_DETECT | ISC_REQ_CONNECTION - - # NTLM tokens start with this header always. Encoding alone adds "==" and newline, so remove those - B64_TOKEN_PREFIX = ["NTLMSSP"].pack("m").delete("=\n") - - # Given a connection and a request path, performs authentication as the current user and returns - # the response from a GET request. The connnection should be a Net::HTTP object, and it should - # have been constructed using the Net::HTTP.Proxy method, but anything that responds to "get" will work. - # If a user and domain are given, will authenticate as the given user. - # Returns the response received from the get method (usually Net::HTTPResponse) - def NegotiateAuth.proxy_auth_get(http, path, user = nil, domain = nil) - raise "http must respond to :get" unless http.respond_to?(:get) - nego_auth = self.new user, domain - - resp = http.get path, { "Proxy-Authorization" => "Negotiate " + nego_auth.get_initial_token } - if resp["Proxy-Authenticate"] - resp = http.get path, { "Proxy-Authorization" => "Negotiate " + nego_auth.complete_authentication(resp["Proxy-Authenticate"].split(" ").last.strip) } - end - - resp - end - - # Creates a new instance ready for authentication as the given user in the given domain. - # Defaults to current user and domain as defined by ENV["USERDOMAIN"] and ENV["USERNAME"] if - # no arguments are supplied. - def initialize(user = nil, domain = nil) - if user.nil? && domain.nil? && ENV["USERNAME"].nil? && ENV["USERDOMAIN"].nil? - raise "A username or domain must be supplied since they cannot be retrieved from the environment" - end - - @user = user || ENV["USERNAME"] - @domain = domain || ENV["USERDOMAIN"] - end - - # Gets the initial Negotiate token. Returns it as a base64 encoded string suitable for use in HTTP. Can - # be easily decoded, however. - def get_initial_token - raise "This object is no longer usable because its resources have been freed." if @cleaned_up - get_credentials - - outputBuffer = SecurityBuffer.new - @context = CtxtHandle.new - @contextAttributes = "\0" * 4 - - result = SSPIResult.new(API::InitializeSecurityContext.call(@credentials.to_p, nil, nil, - REQUEST_FLAGS,0, SECURITY_NETWORK_DREP, nil, 0, @context.to_p, outputBuffer.to_p, @contextAttributes, TimeStamp.new.to_p)) - - if result.ok? then - return encode_token(outputBuffer.token) - else - raise "Error: #{result.to_s}" - end - end - - # Takes a token and gets the next token in the Negotiate authentication chain. Token can be Base64 encoded or not. - # The token can include the "Negotiate" header and it will be stripped. - # Does not indicate if SEC_I_CONTINUE or SEC_E_OK was returned. - # Token returned is Base64 encoded w/ all new lines removed. - def complete_authentication(token) - raise "This object is no longer usable because its resources have been freed." if @cleaned_up - - # Nil token OK, just set it to empty string - token = "" if token.nil? - - if token.include? "Negotiate" - # If the Negotiate prefix is passed in, assume we are seeing "Negotiate " and get the token. - token = token.split(" ").last - end - - if token.include? B64_TOKEN_PREFIX - # indicates base64 encoded token - token = token.strip.unpack("m")[0] - end - - outputBuffer = SecurityBuffer.new - result = SSPIResult.new(API::InitializeSecurityContext.call(@credentials.to_p, @context.to_p, nil, - REQUEST_FLAGS, 0, SECURITY_NETWORK_DREP, SecurityBuffer.new(token).to_p, 0, - @context.to_p, - outputBuffer.to_p, @contextAttributes, TimeStamp.new.to_p)) - - if result.ok? then - return encode_token(outputBuffer.token) - else - raise "Error: #{result.to_s}" - end - ensure - # need to make sure we don't clean up if we've already cleaned up. - clean_up unless @cleaned_up - end - - private - - def clean_up - # free structures allocated - @cleaned_up = true - API::FreeCredentialsHandle.call(@credentials.to_p) - API::DeleteSecurityContext.call(@context.to_p) - @context = nil - @credentials = nil - @contextAttributes = nil - end - - # Gets credentials based on user, domain or both. If both are nil, an error occurs - def get_credentials - @credentials = CredHandle.new - ts = TimeStamp.new - @identity = Identity.new @user, @domain - result = SSPIResult.new(API::AcquireCredentialsHandle.call(nil, "Negotiate", SECPKG_CRED_OUTBOUND, nil, @identity.to_p, - nil, nil, @credentials.to_p, ts.to_p)) - raise "Error acquire credentials: #{result}" unless result.ok? - end - - def encode_token(t) - # encode64 will add newlines every 60 characters so we need to remove those. - [t].pack("m").delete("\n") - end - end - end -end \ No newline at end of file diff --git a/Src/StdLib/ruby/1.9.1/win32ole/property.rb b/Src/StdLib/ruby/1.9.1/win32ole/property.rb deleted file mode 100644 index 18b971ba3..000000000 --- a/Src/StdLib/ruby/1.9.1/win32ole/property.rb +++ /dev/null @@ -1,16 +0,0 @@ -# OLEProperty -# helper class of Property with arguments. -class OLEProperty - def initialize(obj, dispid, gettypes, settypes) - @obj = obj - @dispid = dispid - @gettypes = gettypes - @settypes = settypes - end - def [](*args) - @obj._getproperty(@dispid, args, @gettypes) - end - def []=(*args) - @obj._setproperty(@dispid, args, @settypes) - end -end diff --git a/Src/StdLib/ruby/1.9.1/xmlrpc/base64.rb b/Src/StdLib/ruby/1.9.1/xmlrpc/base64.rb deleted file mode 100644 index e46c85c8a..000000000 --- a/Src/StdLib/ruby/1.9.1/xmlrpc/base64.rb +++ /dev/null @@ -1,81 +0,0 @@ -=begin -= xmlrpc/base64.rb -Copyright (C) 2001, 2002, 2003 by Michael Neumann (mneumann@ntecs.de) - -Released under the same term of license as Ruby. - -= Classes -* (()) - -= XMLRPC::Base64 -== Description -This class is necessary for (('xmlrpc4r')) to determine that a string should -be transmitted base64-encoded and not as a raw-string. -You can use (({XMLRPC::Base64})) on the client and server-side as a -parameter and/or return-value. - -== Class Methods ---- XMLRPC::Base64.new( str, state = :dec ) - Creates a new (({XMLRPC::Base64})) instance with string ((|str|)) as the - internal string. When ((|state|)) is (({:dec})) it assumes that the - string ((|str|)) is not in base64 format (perhaps already decoded), - otherwise if ((|state|)) is (({:enc})) it decodes ((|str|)) - and stores it as the internal string. - ---- XMLRPC::Base64.decode( str ) - Decodes string ((|str|)) with base64 and returns that value. - ---- XMLRPC::Base64.encode( str ) - Encodes string ((|str|)) with base64 and returns that value. - -== Instance Methods ---- XMLRPC::Base64#decoded - Returns the internal string decoded. - ---- XMLRPC::Base64#encoded - Returns the internal string encoded with base64. - -=end - -module XMLRPC - -class Base64 - - def initialize(str, state = :dec) - case state - when :enc - @str = Base64.decode(str) - when :dec - @str = str - else - raise ArgumentError, "wrong argument; either :enc or :dec" - end - end - - def decoded - @str - end - - def encoded - Base64.encode(@str) - end - - - def Base64.decode(str) - str.gsub(/\s+/, "").unpack("m")[0] - end - - def Base64.encode(str) - [str].pack("m") - end - -end - - -end # module XMLRPC - - -=begin -= History - $Id: base64.rb 25189 2009-10-02 12:04:37Z akr $ -=end diff --git a/Src/StdLib/ruby/1.9.1/xmlrpc/client.rb b/Src/StdLib/ruby/1.9.1/xmlrpc/client.rb deleted file mode 100644 index 88bd4572d..000000000 --- a/Src/StdLib/ruby/1.9.1/xmlrpc/client.rb +++ /dev/null @@ -1,625 +0,0 @@ -=begin -= xmlrpc/client.rb -Copyright (C) 2001, 2002, 2003 by Michael Neumann (mneumann@ntecs.de) - -Released under the same term of license as Ruby. - -= Classes -* (()) -* (()) - - -= XMLRPC::Client -== Synopsis - require "xmlrpc/client" - - server = XMLRPC::Client.new("www.ruby-lang.org", "/RPC2", 80) - begin - param = server.call("michael.add", 4, 5) - puts "4 + 5 = #{param}" - rescue XMLRPC::FaultException => e - puts "Error:" - puts e.faultCode - puts e.faultString - end - -or - - require "xmlrpc/client" - - server = XMLRPC::Client.new("www.ruby-lang.org", "/RPC2", 80) - ok, param = server.call2("michael.add", 4, 5) - if ok then - puts "4 + 5 = #{param}" - else - puts "Error:" - puts param.faultCode - puts param.faultString - end - -== Description -Class (({XMLRPC::Client})) provides remote procedure calls to a XML-RPC server. -After setting the connection-parameters with (()) which -creates a new (({XMLRPC::Client})) instance, you can execute a remote procedure -by sending the (()) or (()) -message to this new instance. The given parameters indicate which method to -call on the remote-side and of course the parameters for the remote procedure. - -== Class Methods ---- XMLRPC::Client.new( host=nil, path=nil, port=nil, proxy_host=nil, proxy_port=nil, user=nil, password=nil, use_ssl=false, timeout =nil) - Creates an object which represents the remote XML-RPC server on the - given host ((|host|)). If the server is CGI-based, ((|path|)) is the - path to the CGI-script, which will be called, otherwise (in the - case of a standalone server) ((|path|)) should be (({"/RPC2"})). - ((|port|)) is the port on which the XML-RPC server listens. - If ((|proxy_host|)) is given, then a proxy server listening at - ((|proxy_host|)) is used. ((|proxy_port|)) is the port of the - proxy server. - - Default values for ((|host|)), ((|path|)) and ((|port|)) are 'localhost', '/RPC2' and - '80' respectively using SSL '443'. - - If ((|user|)) and ((|password|)) are given, each time a request is send, - a Authorization header is send. Currently only Basic Authentification is - implemented no Digest. - - If ((|use_ssl|)) is set to (({true})), comunication over SSL is enabled. - Note, that you need the SSL package from RAA installed. - - Parameter ((|timeout|)) is the time to wait for a XML-RPC response, defaults to 30. - ---- XMLRPC::Client.new2( uri, proxy=nil, timeout=nil) ---- XMLRPC::Client.new_from_uri( uri, proxy=nil, timeout=nil) -: uri - URI specifying protocol (http or https), host, port, path, user and password. - Example: https://user:password@host:port/path - -: proxy - Is of the form "host:port". - -: timeout - Defaults to 30. - ---- XMLRPC::Client.new3( hash={} ) ---- XMLRPC::Client.new_from_hash( hash={} ) - Parameter ((|hash|)) has following case-insensitive keys: - * host - * path - * port - * proxy_host - * proxy_port - * user - * password - * use_ssl - * timeout - - Calls (()) with the corresponding values. - -== Instance Methods ---- XMLRPC::Client#call( method, *args ) - Invokes the method named ((|method|)) with the parameters given by - ((|args|)) on the XML-RPC server. - The parameter ((|method|)) is converted into a (({String})) and should - be a valid XML-RPC method-name. - Each parameter of ((|args|)) must be of one of the following types, - where (({Hash})), (({Struct})) and (({Array})) can contain any of these listed ((:types:)): - * (({Fixnum})), (({Bignum})) - * (({TrueClass})), (({FalseClass})) ((({true})), (({false}))) - * (({String})), (({Symbol})) - * (({Float})) - * (({Hash})), (({Struct})) - * (({Array})) - * (({Date})), (({Time})), (({XMLRPC::DateTime})) - * (({XMLRPC::Base64})) - * A Ruby object which class includes XMLRPC::Marshallable (only if Config::ENABLE_MARSHALLABLE is (({true}))). - That object is converted into a hash, with one additional key/value pair "___class___" which contains the class name - for restoring later that object. - - The method returns the return-value from the RPC - ((-stands for Remote Procedure Call-)). - The type of the return-value is one of the above shown, - only that a (({Bignum})) is only allowed when it fits in 32-bit and - that a XML-RPC (('dateTime.iso8601')) type is always returned as - a ((<(({XMLRPC::DateTime}))|URL:datetime.html>)) object and - a (({Struct})) is never returned, only a (({Hash})), the same for a (({Symbol})), where - always a (({String})) is returned. - A (({XMLRPC::Base64})) is returned as a (({String})) from xmlrpc4r version 1.6.1 on. - - If the remote procedure returned a fault-structure, then a - (({XMLRPC::FaultException})) exception is raised, which has two accessor-methods - (({faultCode})) and (({faultString})) of type (({Integer})) and (({String})). - ---- XMLRPC::Client#call2( method, *args ) - The difference between this method and (()) is, that - this method do ((*not*)) raise a (({XMLRPC::FaultException})) exception. - The method returns an array of two values. The first value indicates if - the second value is a return-value ((({true}))) or an object of type - (({XMLRPC::FaultException})). - Both are explained in (()). - - Simple to remember: The "2" in "call2" denotes the number of values it returns. - ---- XMLRPC::Client#multicall( *methods ) - You can use this method to execute several methods on a XMLRPC server which supports - the multi-call extension. - Example: - - s.multicall( - ['michael.add', 3, 4], - ['michael.sub', 4, 5] - ) - # => [7, -1] - ---- XMLRPC::Client#multicall2( *methods ) - Same as (()), but returns like (()) two parameters - instead of raising an (({XMLRPC::FaultException})). - ---- XMLRPC::Client#proxy( prefix, *args ) - Returns an object of class (({XMLRPC::Client::Proxy})), initialized with - ((|prefix|)) and ((|args|)). A proxy object returned by this method behaves - like (()), i.e. a call on that object will raise a - (({XMLRPC::FaultException})) when a fault-structure is returned by that call. - ---- XMLRPC::Client#proxy2( prefix, *args ) - Almost the same like (()) only that a call on the returned - (({XMLRPC::Client::Proxy})) object behaves like (()), i.e. - a call on that object will return two parameters. - - - - ---- XMLRPC::Client#call_async(...) ---- XMLRPC::Client#call2_async(...) ---- XMLRPC::Client#multicall_async(...) ---- XMLRPC::Client#multicall2_async(...) ---- XMLRPC::Client#proxy_async(...) ---- XMLRPC::Client#proxy2_async(...) - In contrast to corresponding methods without "_async", these can be - called concurrently and use for each request a new connection, where the - non-asynchronous counterparts use connection-alive (one connection for all requests) - if possible. - - Note, that you have to use Threads to call these methods concurrently. - The following example calls two methods concurrently: - - Thread.new { - p client.call_async("michael.add", 4, 5) - } - - Thread.new { - p client.call_async("michael.div", 7, 9) - } - - ---- XMLRPC::Client#timeout ---- XMLRPC::Client#user ---- XMLRPC::Client#password - Return the corresponding attributes. - ---- XMLRPC::Client#timeout= (new_timeout) ---- XMLRPC::Client#user= (new_user) ---- XMLRPC::Client#password= (new_password) - Set the corresponding attributes. - - ---- XMLRPC::Client#set_writer( writer ) - Sets the XML writer to use for generating XML output. - Should be an instance of a class from module (({XMLRPC::XMLWriter})). - If this method is not called, then (({XMLRPC::Config::DEFAULT_WRITER})) is used. - ---- XMLRPC::Client#set_parser( parser ) - Sets the XML parser to use for parsing XML documents. - Should be an instance of a class from module (({XMLRPC::XMLParser})). - If this method is not called, then (({XMLRPC::Config::DEFAULT_PARSER})) is used. - ---- XMLRPC::Client#cookie ---- XMLRPC::Client#cookie= (cookieString) - Get and set the HTTP Cookie header. - ---- XMLRPC::Client#http_header_extra= (additionalHeaders) - Set extra HTTP headers that are included in the request. - ---- XMLRPC::Client#http_header_extra - Access the via (()) assigned header. - ---- XMLRPC::Client#http_last_response - Returns the (({Net::HTTPResponse})) object of the last RPC. - -= XMLRPC::Client::Proxy -== Synopsis - require "xmlrpc/client" - - server = XMLRPC::Client.new("www.ruby-lang.org", "/RPC2", 80) - - michael = server.proxy("michael") - michael2 = server.proxy("michael", 4) - - # both calls should return the same value '9'. - p michael.add(4,5) - p michael2.add(5) - -== Description -Class (({XMLRPC::Client::Proxy})) makes XML-RPC calls look nicer! -You can call any method onto objects of that class - the object handles -(({method_missing})) and will forward the method call to a XML-RPC server. -Don't use this class directly, but use instead method (()) or -(()). - -== Class Methods ---- XMLRPC::Client::Proxy.new( server, prefix, args=[], meth=:call, delim="." ) - Creates an object which provides (({method_missing})). - - ((|server|)) must be of type (({XMLRPC::Client})), which is the XML-RPC server to be used - for a XML-RPC call. ((|prefix|)) and ((|delim|)) will be prepended to the methodname - called onto this object. - - Parameter ((|meth|)) is the method (call, call2, call_async, call2_async) to use for - a RPC. - - ((|args|)) are arguments which are automatically given - to every XML-RPC call before the arguments provides through (({method_missing})). - -== Instance Methods -Every method call is forwarded to the XML-RPC server defined in (()). - -Note: Inherited methods from class (({Object})) cannot be used as XML-RPC names, because they get around -(({method_missing})). - - - -= History - $Id: client.rb 25189 2009-10-02 12:04:37Z akr $ - -=end - - - -require "xmlrpc/parser" -require "xmlrpc/create" -require "xmlrpc/config" -require "xmlrpc/utils" # ParserWriterChooseMixin -require "net/http" - -module XMLRPC - - class Client - - USER_AGENT = "XMLRPC::Client (Ruby #{RUBY_VERSION})" - - include ParserWriterChooseMixin - include ParseContentType - - - # Constructors ------------------------------------------------------------------- - - def initialize(host=nil, path=nil, port=nil, proxy_host=nil, proxy_port=nil, - user=nil, password=nil, use_ssl=nil, timeout=nil) - - @http_header_extra = nil - @http_last_response = nil - @cookie = nil - - @host = host || "localhost" - @path = path || "/RPC2" - @proxy_host = proxy_host - @proxy_port = proxy_port - @proxy_host ||= 'localhost' if @proxy_port != nil - @proxy_port ||= 8080 if @proxy_host != nil - @use_ssl = use_ssl || false - @timeout = timeout || 30 - - if use_ssl - require "net/https" - @port = port || 443 - else - @port = port || 80 - end - - @user, @password = user, password - - set_auth - - # convert ports to integers - @port = @port.to_i if @port != nil - @proxy_port = @proxy_port.to_i if @proxy_port != nil - - # HTTP object for synchronous calls - Net::HTTP.version_1_2 - @http = Net::HTTP.new(@host, @port, @proxy_host, @proxy_port) - @http.use_ssl = @use_ssl if @use_ssl - @http.read_timeout = @timeout - @http.open_timeout = @timeout - - @parser = nil - @create = nil - end - - - class << self - - def new2(uri, proxy=nil, timeout=nil) - if match = /^([^:]+):\/\/(([^@]+)@)?([^\/]+)(\/.*)?$/.match(uri) - proto = match[1] - user, passwd = (match[3] || "").split(":") - host, port = match[4].split(":") - path = match[5] - - if proto != "http" and proto != "https" - raise "Wrong protocol specified. Only http or https allowed!" - end - - else - raise "Wrong URI as parameter!" - end - - proxy_host, proxy_port = (proxy || "").split(":") - - self.new(host, path, port, proxy_host, proxy_port, user, passwd, (proto == "https"), timeout) - end - - alias new_from_uri new2 - - def new3(hash={}) - - # convert all keys into lowercase strings - h = {} - hash.each { |k,v| h[k.to_s.downcase] = v } - - self.new(h['host'], h['path'], h['port'], h['proxy_host'], h['proxy_port'], h['user'], h['password'], - h['use_ssl'], h['timeout']) - end - - alias new_from_hash new3 - - end - - - # Attribute Accessors ------------------------------------------------------------------- - - # add additional HTTP headers to the request - attr_accessor :http_header_extra - - # makes last HTTP response accessible - attr_reader :http_last_response - - # Cookie support - attr_accessor :cookie - - - attr_reader :timeout, :user, :password - - def timeout=(new_timeout) - @timeout = new_timeout - @http.read_timeout = @timeout - @http.open_timeout = @timeout - end - - def user=(new_user) - @user = new_user - set_auth - end - - def password=(new_password) - @password = new_password - set_auth - end - - # Call methods -------------------------------------------------------------- - - def call(method, *args) - ok, param = call2(method, *args) - if ok - param - else - raise param - end - end - - def call2(method, *args) - request = create().methodCall(method, *args) - data = do_rpc(request, false) - parser().parseMethodResponse(data) - end - - def call_async(method, *args) - ok, param = call2_async(method, *args) - if ok - param - else - raise param - end - end - - def call2_async(method, *args) - request = create().methodCall(method, *args) - data = do_rpc(request, true) - parser().parseMethodResponse(data) - end - - - # Multicall methods -------------------------------------------------------------- - - def multicall(*methods) - ok, params = multicall2(*methods) - if ok - params - else - raise params - end - end - - def multicall2(*methods) - gen_multicall(methods, false) - end - - def multicall_async(*methods) - ok, params = multicall2_async(*methods) - if ok - params - else - raise params - end - end - - def multicall2_async(*methods) - gen_multicall(methods, true) - end - - - # Proxy generating methods ------------------------------------------ - - def proxy(prefix=nil, *args) - Proxy.new(self, prefix, args, :call) - end - - def proxy2(prefix=nil, *args) - Proxy.new(self, prefix, args, :call2) - end - - def proxy_async(prefix=nil, *args) - Proxy.new(self, prefix, args, :call_async) - end - - def proxy2_async(prefix=nil, *args) - Proxy.new(self, prefix, args, :call2_async) - end - - - private # ---------------------------------------------------------- - - def set_auth - if @user.nil? - @auth = nil - else - a = "#@user" - a << ":#@password" if @password != nil - @auth = ("Basic " + [a].pack("m")).chomp - end - end - - def do_rpc(request, async=false) - header = { - "User-Agent" => USER_AGENT, - "Content-Type" => "text/xml; charset=utf-8", - "Content-Length" => request.size.to_s, - "Connection" => (async ? "close" : "keep-alive") - } - - header["Cookie"] = @cookie if @cookie - header.update(@http_header_extra) if @http_header_extra - - if @auth != nil - # add authorization header - header["Authorization"] = @auth - end - - resp = nil - @http_last_response = nil - - if async - # use a new HTTP object for each call - Net::HTTP.version_1_2 - http = Net::HTTP.new(@host, @port, @proxy_host, @proxy_port) - http.use_ssl = @use_ssl if @use_ssl - http.read_timeout = @timeout - http.open_timeout = @timeout - - # post request - http.start { - resp = http.post2(@path, request, header) - } - else - # reuse the HTTP object for each call => connection alive is possible - # we must start connection explicitely first time so that http.request - # does not assume that we don't want keepalive - @http.start if not @http.started? - - # post request - resp = @http.post2(@path, request, header) - end - - @http_last_response = resp - - data = resp.body - - if resp.code == "401" - # Authorization Required - raise "Authorization failed.\nHTTP-Error: #{resp.code} #{resp.message}" - elsif resp.code[0,1] != "2" - raise "HTTP-Error: #{resp.code} #{resp.message}" - end - - ct = parse_content_type(resp["Content-Type"]).first - if ct != "text/xml" - if ct == "text/html" - raise "Wrong content-type (received '#{ct}' but expected 'text/xml'): \n#{data}" - else - raise "Wrong content-type (received '#{ct}' but expected 'text/xml')" - end - end - - expected = resp["Content-Length"] || "" - if data.nil? or data.size == 0 - raise "Wrong size. Was #{data.size}, should be #{expected}" - elsif expected != "" and expected.to_i != data.size and resp["Transfer-Encoding"].nil? - raise "Wrong size. Was #{data.size}, should be #{expected}" - end - - set_cookies = resp.get_fields("Set-Cookie") - if set_cookies and !set_cookies.empty? - require 'webrick/cookie' - @cookie = set_cookies.collect do |set_cookie| - cookie = WEBrick::Cookie.parse_set_cookie(set_cookie) - WEBrick::Cookie.new(cookie.name, cookie.value).to_s - end.join("; ") - end - - return data - end - - def gen_multicall(methods=[], async=false) - meth = :call2 - meth = :call2_async if async - - ok, params = self.send(meth, "system.multicall", - methods.collect {|m| {'methodName' => m[0], 'params' => m[1..-1]} } - ) - - if ok - params = params.collect do |param| - if param.is_a? Array - param[0] - elsif param.is_a? Hash - XMLRPC::FaultException.new(param["faultCode"], param["faultString"]) - else - raise "Wrong multicall return value" - end - end - end - - return ok, params - end - - - - class Proxy - - def initialize(server, prefix, args=[], meth=:call, delim=".") - @server = server - @prefix = prefix ? prefix + delim : "" - @args = args - @meth = meth - end - - def method_missing(mid, *args) - pre = @prefix + mid.to_s - arg = @args + args - @server.send(@meth, pre, *arg) - end - - end # class Proxy - - end # class Client - -end # module XMLRPC - diff --git a/Src/StdLib/ruby/1.9.1/xmlrpc/config.rb b/Src/StdLib/ruby/1.9.1/xmlrpc/config.rb deleted file mode 100644 index d24142ed4..000000000 --- a/Src/StdLib/ruby/1.9.1/xmlrpc/config.rb +++ /dev/null @@ -1,40 +0,0 @@ -# -# $Id: config.rb 25189 2009-10-02 12:04:37Z akr $ -# Configuration file for XML-RPC for Ruby -# - -module XMLRPC - - module Config - - DEFAULT_WRITER = XMLWriter::Simple # or XMLWriter::XMLParser - - # available parser: - # * XMLParser::NQXMLTreeParser - # * XMLParser::NQXMLStreamParser - # * XMLParser::XMLTreeParser - # * XMLParser::XMLStreamParser (fastest) - # * XMLParser::REXMLStreamParser - # * XMLParser::XMLScanStreamParser - DEFAULT_PARSER = XMLParser::REXMLStreamParser - - # enable tag - ENABLE_NIL_CREATE = false - ENABLE_NIL_PARSER = false - - # allows integers greater than 32-bit if true - ENABLE_BIGINT = false - - # enable marshalling ruby objects which include XMLRPC::Marshallable - ENABLE_MARSHALLING = true - - # enable multiCall extension by default - ENABLE_MULTICALL = false - - # enable Introspection extension by default - ENABLE_INTROSPECTION = false - - end - -end - diff --git a/Src/StdLib/ruby/1.9.1/xmlrpc/create.rb b/Src/StdLib/ruby/1.9.1/xmlrpc/create.rb deleted file mode 100644 index 652c654ef..000000000 --- a/Src/StdLib/ruby/1.9.1/xmlrpc/create.rb +++ /dev/null @@ -1,283 +0,0 @@ -# -# Creates XML-RPC call/response documents -# -# Copyright (C) 2001, 2002, 2003 by Michael Neumann (mneumann@ntecs.de) -# -# $Id: create.rb 25189 2009-10-02 12:04:37Z akr $ -# - -require "date" -require "xmlrpc/base64" - -module XMLRPC - - module XMLWriter - - class Abstract - def ele(name, *children) - element(name, nil, *children) - end - - def tag(name, txt) - element(name, nil, text(txt)) - end - end - - - class Simple < Abstract - - def document_to_str(doc) - doc - end - - def document(*params) - params.join("") - end - - def pi(name, *params) - "" - end - - def element(name, attrs, *children) - raise "attributes not yet implemented" unless attrs.nil? - if children.empty? - "<#{name}/>" - else - "<#{name}>" + children.join("") + "" - end - end - - def text(txt) - cleaned = txt.dup - cleaned.gsub!(/&/, '&') - cleaned.gsub!(//, '>') - cleaned - end - - end # class Simple - - - class XMLParser < Abstract - - def initialize - require "xmltreebuilder" - end - - def document_to_str(doc) - doc.to_s - end - - def document(*params) - XML::SimpleTree::Document.new(*params) - end - - def pi(name, *params) - XML::SimpleTree::ProcessingInstruction.new(name, *params) - end - - def element(name, attrs, *children) - XML::SimpleTree::Element.new(name, attrs, *children) - end - - def text(txt) - XML::SimpleTree::Text.new(txt) - end - - end # class XMLParser - - Classes = [Simple, XMLParser] - - # yields an instance of each installed XML writer - def self.each_installed_writer - XMLRPC::XMLWriter::Classes.each do |klass| - begin - yield klass.new - rescue LoadError - end - end - end - - end # module XMLWriter - - class Create - - def initialize(xml_writer = nil) - @writer = xml_writer || Config::DEFAULT_WRITER.new - end - - - def methodCall(name, *params) - name = name.to_s - - if name !~ /[a-zA-Z0-9_.:\/]+/ - raise ArgumentError, "Wrong XML-RPC method-name" - end - - parameter = params.collect do |param| - @writer.ele("param", conv2value(param)) - end - - tree = @writer.document( - @writer.pi("xml", 'version="1.0"'), - @writer.ele("methodCall", - @writer.tag("methodName", name), - @writer.ele("params", *parameter) - ) - ) - - @writer.document_to_str(tree) + "\n" - end - - - - # - # generates a XML-RPC methodResponse document - # - # if is_ret == false then the params array must - # contain only one element, which is a structure - # of a fault return-value. - # - # if is_ret == true then a normal - # return-value of all the given params is created. - # - def methodResponse(is_ret, *params) - - if is_ret - resp = params.collect do |param| - @writer.ele("param", conv2value(param)) - end - - resp = [@writer.ele("params", *resp)] - else - if params.size != 1 or params[0] === XMLRPC::FaultException - raise ArgumentError, "no valid fault-structure given" - end - resp = @writer.ele("fault", conv2value(params[0].to_h)) - end - - - tree = @writer.document( - @writer.pi("xml", 'version="1.0"'), - @writer.ele("methodResponse", resp) - ) - - @writer.document_to_str(tree) + "\n" - end - - - - ##################################### - private - ##################################### - - # - # converts a Ruby object into - # a XML-RPC tag - # - def conv2value(param) - - val = case param - when Integer - if Config::ENABLE_BIGINT or (param >= -(2**31) and param <= (2**31-1)) - @writer.tag("i4", param.to_s) - else - raise "Integer is too big! Must be signed 32-bit integer!" - end - when TrueClass, FalseClass - @writer.tag("boolean", param ? "1" : "0") - - when Symbol - @writer.tag("string", param.to_s) - - when String - @writer.tag("string", param) - - when NilClass - if Config::ENABLE_NIL_CREATE - @writer.ele("nil") - else - raise "Wrong type NilClass. Not allowed!" - end - - when Float - @writer.tag("double", param.to_s) - - when Struct - h = param.members.collect do |key| - value = param[key] - @writer.ele("member", - @writer.tag("name", key.to_s), - conv2value(value) - ) - end - - @writer.ele("struct", *h) - - when Hash - # TODO: can a Hash be empty? - - h = param.collect do |key, value| - @writer.ele("member", - @writer.tag("name", key.to_s), - conv2value(value) - ) - end - - @writer.ele("struct", *h) - - when Array - # TODO: can an Array be empty? - a = param.collect {|v| conv2value(v) } - - @writer.ele("array", - @writer.ele("data", *a) - ) - - when Time, Date, ::DateTime - @writer.tag("dateTime.iso8601", param.strftime("%Y%m%dT%H:%M:%S")) - - when XMLRPC::DateTime - @writer.tag("dateTime.iso8601", - format("%.4d%02d%02dT%02d:%02d:%02d", *param.to_a)) - - when XMLRPC::Base64 - @writer.tag("base64", param.encoded) - - else - if Config::ENABLE_MARSHALLING and param.class.included_modules.include? XMLRPC::Marshallable - # convert Ruby object into Hash - ret = {"___class___" => param.class.name} - param.instance_variables.each {|v| - name = v[1..-1] - val = param.instance_variable_get(v) - - if val.nil? - ret[name] = val if Config::ENABLE_NIL_CREATE - else - ret[name] = val - end - } - return conv2value(ret) - else - ok, pa = wrong_type(param) - if ok - return conv2value(pa) - else - raise "Wrong type!" - end - end - end - - @writer.ele("value", val) - end - - def wrong_type(value) - false - end - - - end # class Create - -end # module XMLRPC - diff --git a/Src/StdLib/ruby/1.9.1/xmlrpc/datetime.rb b/Src/StdLib/ruby/1.9.1/xmlrpc/datetime.rb deleted file mode 100644 index 6dd820b76..000000000 --- a/Src/StdLib/ruby/1.9.1/xmlrpc/datetime.rb +++ /dev/null @@ -1,142 +0,0 @@ -=begin -= xmlrpc/datetime.rb -Copyright (C) 2001, 2002, 2003 by Michael Neumann (mneumann@ntecs.de) - -Released under the same term of license as Ruby. - -= Classes -* (()) - -= XMLRPC::DateTime -== Description -This class is important to handle XMLRPC (('dateTime.iso8601')) values, -correcly, because normal UNIX-dates (class (({Date}))) only handle dates -from year 1970 on, and class (({Time})) handles dates without the time -component. (({XMLRPC::DateTime})) is able to store a XMLRPC -(('dateTime.iso8601')) value correctly. - -== Class Methods ---- XMLRPC::DateTime.new( year, month, day, hour, min, sec ) - Creates a new (({XMLRPC::DateTime})) instance with the - parameters ((|year|)), ((|month|)), ((|day|)) as date and - ((|hour|)), ((|min|)), ((|sec|)) as time. - Raises (({ArgumentError})) if a parameter is out of range, or ((|year|)) is not - of type (({Integer})). - -== Instance Methods ---- XMLRPC::DateTime#year ---- XMLRPC::DateTime#month ---- XMLRPC::DateTime#day ---- XMLRPC::DateTime#hour ---- XMLRPC::DateTime#min ---- XMLRPC::DateTime#sec - Return the value of the specified date/time component. - ---- XMLRPC::DateTime#mon - Alias for (()). - ---- XMLRPC::DateTime#year=( value ) ---- XMLRPC::DateTime#month=( value ) ---- XMLRPC::DateTime#day=( value ) ---- XMLRPC::DateTime#hour=( value ) ---- XMLRPC::DateTime#min=( value ) ---- XMLRPC::DateTime#sec=( value ) - Set ((|value|)) as the new date/time component. - Raises (({ArgumentError})) if ((|value|)) is out of range, or in the case - of (({XMLRPC::DateTime#year=})) if ((|value|)) is not of type (({Integer})). - ---- XMLRPC::DateTime#mon=( value ) - Alias for (()). - ---- XMLRPC::DateTime#to_time - Return a (({Time})) object of the date/time which (({self})) represents. - If the (('year')) is below 1970, this method returns (({nil})), - because (({Time})) cannot handle years below 1970. - The used timezone is GMT. - ---- XMLRPC::DateTime#to_date - Return a (({Date})) object of the date which (({self})) represents. - The (({Date})) object do ((*not*)) contain the time component (only date). - ---- XMLRPC::DateTime#to_a - Returns all date/time components in an array. - Returns (({[year, month, day, hour, min, sec]})). -=end - -require "date" - -module XMLRPC - -class DateTime - - attr_reader :year, :month, :day, :hour, :min, :sec - - def year= (value) - raise ArgumentError, "date/time out of range" unless value.is_a? Integer - @year = value - end - - def month= (value) - raise ArgumentError, "date/time out of range" unless (1..12).include? value - @month = value - end - - def day= (value) - raise ArgumentError, "date/time out of range" unless (1..31).include? value - @day = value - end - - def hour= (value) - raise ArgumentError, "date/time out of range" unless (0..24).include? value - @hour = value - end - - def min= (value) - raise ArgumentError, "date/time out of range" unless (0..59).include? value - @min = value - end - - def sec= (value) - raise ArgumentError, "date/time out of range" unless (0..59).include? value - @sec = value - end - - alias mon month - alias mon= month= - - - def initialize(year, month, day, hour, min, sec) - self.year, self.month, self.day = year, month, day - self.hour, self.min, self.sec = hour, min, sec - end - - def to_time - if @year >= 1970 - Time.gm(*to_a) - else - nil - end - end - - def to_date - Date.new(*to_a[0,3]) - end - - def to_a - [@year, @month, @day, @hour, @min, @sec] - end - - def ==(o) - self.to_a == Array(o) rescue false - end - -end - - -end # module XMLRPC - - -=begin -= History - $Id: datetime.rb 25189 2009-10-02 12:04:37Z akr $ -=end diff --git a/Src/StdLib/ruby/1.9.1/xmlrpc/httpserver.rb b/Src/StdLib/ruby/1.9.1/xmlrpc/httpserver.rb deleted file mode 100644 index daaa36ab6..000000000 --- a/Src/StdLib/ruby/1.9.1/xmlrpc/httpserver.rb +++ /dev/null @@ -1,178 +0,0 @@ -# -# Implements a simple HTTP-server by using John W. Small's (jsmall@laser.net) -# ruby-generic-server. -# -# Copyright (C) 2001, 2002, 2003 by Michael Neumann (mneumann@ntecs.de) -# -# $Id: httpserver.rb 25189 2009-10-02 12:04:37Z akr $ -# - - -require "gserver" - -class HttpServer < GServer - - ## - # handle_obj specifies the object, that receives calls to request_handler - # and ip_auth_handler - def initialize(handle_obj, port = 8080, host = DEFAULT_HOST, maxConnections = 4, - stdlog = $stdout, audit = true, debug = true) - @handler = handle_obj - super(port, host, maxConnections, stdlog, audit, debug) - end - -private - - # Constants ----------------------------------------------- - - CRLF = "\r\n" - HTTP_PROTO = "HTTP/1.0" - SERVER_NAME = "HttpServer (Ruby #{RUBY_VERSION})" - - DEFAULT_HEADER = { - "Server" => SERVER_NAME - } - - ## - # Mapping of status code and error message - # - StatusCodeMapping = { - 200 => "OK", - 400 => "Bad Request", - 403 => "Forbidden", - 405 => "Method Not Allowed", - 411 => "Length Required", - 500 => "Internal Server Error" - } - - # Classes ------------------------------------------------- - - class Request - attr_reader :data, :header, :method, :path, :proto - - def initialize(data, method=nil, path=nil, proto=nil) - @header, @data = Table.new, data - @method, @path, @proto = method, path, proto - end - - def content_length - len = @header['Content-Length'] - return nil if len.nil? - return len.to_i - end - - end - - class Response - attr_reader :header - attr_accessor :body, :status, :status_message - - def initialize(status=200) - @status = status - @status_message = nil - @header = Table.new - end - end - - - ## - # a case-insensitive Hash class for HTTP header - # - class Table - include Enumerable - - def initialize(hash={}) - @hash = hash - update(hash) - end - - def [](key) - @hash[key.to_s.capitalize] - end - - def []=(key, value) - @hash[key.to_s.capitalize] = value - end - - def update(hash) - hash.each {|k,v| self[k] = v} - self - end - - def each - @hash.each {|k,v| yield k.capitalize, v } - end - - def writeTo(port) - each { |k,v| port << "#{k}: #{v}" << CRLF } - end - end # class Table - - - # Helper Methods ------------------------------------------ - - def http_header(header=nil) - new_header = Table.new(DEFAULT_HEADER) - new_header.update(header) unless header.nil? - - new_header["Connection"] = "close" - new_header["Date"] = http_date(Time.now) - - new_header - end - - def http_date( aTime ) - aTime.gmtime.strftime( "%a, %d %b %Y %H:%M:%S GMT" ) - end - - def http_resp(status_code, status_message=nil, header=nil, body=nil) - status_message ||= StatusCodeMapping[status_code] - - str = "" - str << "#{HTTP_PROTO} #{status_code} #{status_message}" << CRLF - http_header(header).writeTo(str) - str << CRLF - str << body unless body.nil? - str - end - - # Main Serve Loop ----------------------------------------- - - def serve(io) - # perform IP authentification - unless @handler.ip_auth_handler(io) - io << http_resp(403, "Forbidden") - return - end - - # parse first line - if io.gets =~ /^(\S+)\s+(\S+)\s+(\S+)/ - request = Request.new(io, $1, $2, $3) - else - io << http_resp(400, "Bad Request") - return - end - - # parse HTTP headers - while (line=io.gets) !~ /^(\n|\r)/ - if line =~ /^([\w-]+):\s*(.*)$/ - request.header[$1] = $2.strip - end - end - - io.binmode - response = Response.new - - # execute request handler - @handler.request_handler(request, response) - - # write response back to the client - io << http_resp(response.status, response.status_message, - response.header, response.body) - - rescue Exception => e - io << http_resp(500, "Internal Server Error") - end - -end # class HttpServer - diff --git a/Src/StdLib/ruby/1.9.1/xmlrpc/marshal.rb b/Src/StdLib/ruby/1.9.1/xmlrpc/marshal.rb deleted file mode 100644 index 8c4053672..000000000 --- a/Src/StdLib/ruby/1.9.1/xmlrpc/marshal.rb +++ /dev/null @@ -1,76 +0,0 @@ -# -# Marshalling of XML-RPC methodCall and methodResponse -# -# Copyright (C) 2001, 2002, 2003 by Michael Neumann (mneumann@ntecs.de) -# -# $Id: marshal.rb 25189 2009-10-02 12:04:37Z akr $ -# - -require "xmlrpc/parser" -require "xmlrpc/create" -require "xmlrpc/config" -require "xmlrpc/utils" - -module XMLRPC - - class Marshal - include ParserWriterChooseMixin - - # class methods ------------------------------- - - class << self - - def dump_call( methodName, *params ) - new.dump_call( methodName, *params ) - end - - def dump_response( param ) - new.dump_response( param ) - end - - def load_call( stringOrReadable ) - new.load_call( stringOrReadable ) - end - - def load_response( stringOrReadable ) - new.load_response( stringOrReadable ) - end - - alias dump dump_response - alias load load_response - - end # class self - - # instance methods ---------------------------- - - def initialize( parser = nil, writer = nil ) - set_parser( parser ) - set_writer( writer ) - end - - def dump_call( methodName, *params ) - create.methodCall( methodName, *params ) - end - - def dump_response( param ) - create.methodResponse( ! param.kind_of?( XMLRPC::FaultException ) , param ) - end - - ## - # returns [ methodname, params ] - # - def load_call( stringOrReadable ) - parser.parseMethodCall( stringOrReadable ) - end - - ## - # returns paramOrFault - # - def load_response( stringOrReadable ) - parser.parseMethodResponse( stringOrReadable )[1] - end - - end # class Marshal - -end - diff --git a/Src/StdLib/ruby/1.9.1/xmlrpc/parser.rb b/Src/StdLib/ruby/1.9.1/xmlrpc/parser.rb deleted file mode 100644 index f01655194..000000000 --- a/Src/StdLib/ruby/1.9.1/xmlrpc/parser.rb +++ /dev/null @@ -1,813 +0,0 @@ -# -# Parser for XML-RPC call and response -# -# Copyright (C) 2001, 2002, 2003 by Michael Neumann (mneumann@ntecs.de) -# -# $Id: parser.rb 27235 2010-04-06 03:01:52Z naruse $ -# - - -require "date" -require "xmlrpc/base64" -require "xmlrpc/datetime" - - -# add some methods to NQXML::Node -module NQXML - class Node - - def removeChild(node) - @children.delete(node) - end - def childNodes - @children - end - def hasChildNodes - not @children.empty? - end - def [] (index) - @children[index] - end - - def nodeType - if @entity.instance_of? NQXML::Text then :TEXT - elsif @entity.instance_of? NQXML::Comment then :COMMENT - #elsif @entity.instance_of? NQXML::Element then :ELEMENT - elsif @entity.instance_of? NQXML::Tag then :ELEMENT - else :ELSE - end - end - - def nodeValue - #TODO: error when wrong Entity-type - @entity.text - end - def nodeName - #TODO: error when wrong Entity-type - @entity.name - end - end # class Node -end # module NQXML - -module XMLRPC - - class FaultException < StandardError - attr_reader :faultCode, :faultString - - alias message faultString - - def initialize(faultCode, faultString) - @faultCode = faultCode - @faultString = faultString - end - - # returns a hash - def to_h - {"faultCode" => @faultCode, "faultString" => @faultString} - end - end - - module Convert - def self.int(str) - str.to_i - end - - def self.boolean(str) - case str - when "0" then false - when "1" then true - else - raise "RPC-value of type boolean is wrong" - end - end - - def self.double(str) - str.to_f - end - - def self.dateTime(str) - case str - when /^(-?\d\d\d\d)-?(\d\d)-?(\d\d)T(\d\d):(\d\d):(\d\d)(?:Z|([+-])(\d\d):?(\d\d))?$/ - a = [$1, $2, $3, $4, $5, $6].collect{|i| i.to_i} - if $7 - ofs = $8.to_i*3600 + $9.to_i*60 - ofs = -ofs if $7=='+' - utc = Time.utc(*a) + ofs - a = [ utc.year, utc.month, utc.day, utc.hour, utc.min, utc.sec ] - end - XMLRPC::DateTime.new(*a) - when /^(-?\d\d)-?(\d\d)-?(\d\d)T(\d\d):(\d\d):(\d\d)(Z|([+-]\d\d):(\d\d))?$/ - a = [$1, $2, $3, $4, $5, $6].collect{|i| i.to_i} - if a[0] < 70 - a[0] += 2000 - else - a[0] += 1900 - end - if $7 - ofs = $8.to_i*3600 + $9.to_i*60 - ofs = -ofs if $7=='+' - utc = Time.utc(*a) + ofs - a = [ utc.year, utc.month, utc.day, utc.hour, utc.min, utc.sec ] - end - XMLRPC::DateTime.new(*a) - else - raise "wrong dateTime.iso8601 format " + str - end - end - - def self.base64(str) - XMLRPC::Base64.decode(str) - end - - def self.struct(hash) - # convert to marhalled object - klass = hash["___class___"] - if klass.nil? or Config::ENABLE_MARSHALLING == false - hash - else - begin - mod = Module - klass.split("::").each {|const| mod = mod.const_get(const.strip)} - - obj = mod.allocate - - hash.delete "___class___" - hash.each {|key, value| - obj.instance_variable_set("@#{ key }", value) if key =~ /^([a-zA-Z_]\w*)$/ - } - obj - rescue - hash - end - end - end - - def self.fault(hash) - if hash.kind_of? Hash and hash.size == 2 and - hash.has_key? "faultCode" and hash.has_key? "faultString" and - hash["faultCode"].kind_of? Integer and hash["faultString"].kind_of? String - - XMLRPC::FaultException.new(hash["faultCode"], hash["faultString"]) - else - raise "wrong fault-structure: #{hash.inspect}" - end - end - - end # module Convert - - module XMLParser - - class AbstractTreeParser - - def parseMethodResponse(str) - methodResponse_document(createCleanedTree(str)) - end - - def parseMethodCall(str) - methodCall_document(createCleanedTree(str)) - end - - private - - # - # remove all whitespaces but in the tags i4, int, boolean.... - # and all comments - # - def removeWhitespacesAndComments(node) - remove = [] - childs = node.childNodes.to_a - childs.each do |nd| - case _nodeType(nd) - when :TEXT - # TODO: add nil? - unless %w(i4 int boolean string double dateTime.iso8601 base64).include? node.nodeName - - if node.nodeName == "value" - if not node.childNodes.to_a.detect {|n| _nodeType(n) == :ELEMENT}.nil? - remove << nd if nd.nodeValue.strip == "" - end - else - remove << nd if nd.nodeValue.strip == "" - end - end - when :COMMENT - remove << nd - else - removeWhitespacesAndComments(nd) - end - end - - remove.each { |i| node.removeChild(i) } - end - - - def nodeMustBe(node, name) - cmp = case name - when Array - name.include?(node.nodeName) - when String - name == node.nodeName - else - raise "error" - end - - if not cmp then - raise "wrong xml-rpc (name)" - end - - node - end - - # - # returns, when successfully the only child-node - # - def hasOnlyOneChild(node, name=nil) - if node.childNodes.to_a.size != 1 - raise "wrong xml-rpc (size)" - end - if name != nil then - nodeMustBe(node.firstChild, name) - end - end - - - def assert(b) - if not b then - raise "assert-fail" - end - end - - # the node `node` has empty string or string - def text_zero_one(node) - nodes = node.childNodes.to_a.size - - if nodes == 1 - text(node.firstChild) - elsif nodes == 0 - "" - else - raise "wrong xml-rpc (size)" - end - end - - - def integer(node) - #TODO: check string for float because to_i returnsa - # 0 when wrong string - nodeMustBe(node, %w(i4 int)) - hasOnlyOneChild(node) - - Convert.int(text(node.firstChild)) - end - - def boolean(node) - nodeMustBe(node, "boolean") - hasOnlyOneChild(node) - - Convert.boolean(text(node.firstChild)) - end - - def v_nil(node) - nodeMustBe(node, "nil") - assert( node.childNodes.to_a.size == 0 ) - nil - end - - def string(node) - nodeMustBe(node, "string") - text_zero_one(node) - end - - def double(node) - #TODO: check string for float because to_f returnsa - # 0.0 when wrong string - nodeMustBe(node, "double") - hasOnlyOneChild(node) - - Convert.double(text(node.firstChild)) - end - - def dateTime(node) - nodeMustBe(node, "dateTime.iso8601") - hasOnlyOneChild(node) - - Convert.dateTime( text(node.firstChild) ) - end - - def base64(node) - nodeMustBe(node, "base64") - #hasOnlyOneChild(node) - - Convert.base64(text_zero_one(node)) - end - - def member(node) - nodeMustBe(node, "member") - assert( node.childNodes.to_a.size == 2 ) - - [ name(node[0]), value(node[1]) ] - end - - def name(node) - nodeMustBe(node, "name") - #hasOnlyOneChild(node) - text_zero_one(node) - end - - def array(node) - nodeMustBe(node, "array") - hasOnlyOneChild(node, "data") - data(node.firstChild) - end - - def data(node) - nodeMustBe(node, "data") - - node.childNodes.to_a.collect do |val| - value(val) - end - end - - def param(node) - nodeMustBe(node, "param") - hasOnlyOneChild(node, "value") - value(node.firstChild) - end - - def methodResponse(node) - nodeMustBe(node, "methodResponse") - hasOnlyOneChild(node, %w(params fault)) - child = node.firstChild - - case child.nodeName - when "params" - [ true, params(child,false) ] - when "fault" - [ false, fault(child) ] - else - raise "unexpected error" - end - - end - - def methodName(node) - nodeMustBe(node, "methodName") - hasOnlyOneChild(node) - text(node.firstChild) - end - - def params(node, call=true) - nodeMustBe(node, "params") - - if call - node.childNodes.to_a.collect do |n| - param(n) - end - else # response (only one param) - hasOnlyOneChild(node) - param(node.firstChild) - end - end - - def fault(node) - nodeMustBe(node, "fault") - hasOnlyOneChild(node, "value") - f = value(node.firstChild) - Convert.fault(f) - end - - - - # _nodeType is defined in the subclass - def text(node) - assert( _nodeType(node) == :TEXT ) - assert( node.hasChildNodes == false ) - assert( node.nodeValue != nil ) - - node.nodeValue.to_s - end - - def struct(node) - nodeMustBe(node, "struct") - - hash = {} - node.childNodes.to_a.each do |me| - n, v = member(me) - hash[n] = v - end - - Convert.struct(hash) - end - - - def value(node) - nodeMustBe(node, "value") - nodes = node.childNodes.to_a.size - if nodes == 0 - return "" - elsif nodes > 1 - raise "wrong xml-rpc (size)" - end - - child = node.firstChild - - case _nodeType(child) - when :TEXT - text_zero_one(node) - when :ELEMENT - case child.nodeName - when "i4", "int" then integer(child) - when "boolean" then boolean(child) - when "string" then string(child) - when "double" then double(child) - when "dateTime.iso8601" then dateTime(child) - when "base64" then base64(child) - when "struct" then struct(child) - when "array" then array(child) - when "nil" - if Config::ENABLE_NIL_PARSER - v_nil(child) - else - raise "wrong/unknown XML-RPC type 'nil'" - end - else - raise "wrong/unknown XML-RPC type" - end - else - raise "wrong type of node" - end - - end - - def methodCall(node) - nodeMustBe(node, "methodCall") - assert( (1..2).include?( node.childNodes.to_a.size ) ) - name = methodName(node[0]) - - if node.childNodes.to_a.size == 2 then - pa = params(node[1]) - else # no parameters given - pa = [] - end - [name, pa] - end - - end # module TreeParserMixin - - class AbstractStreamParser - def parseMethodResponse(str) - parser = @parser_class.new - parser.parse(str) - raise "No valid method response!" if parser.method_name != nil - if parser.fault != nil - # is a fault structure - [false, parser.fault] - else - # is a normal return value - raise "Missing return value!" if parser.params.size == 0 - raise "Too many return values. Only one allowed!" if parser.params.size > 1 - [true, parser.params[0]] - end - end - - def parseMethodCall(str) - parser = @parser_class.new - parser.parse(str) - raise "No valid method call - missing method name!" if parser.method_name.nil? - [parser.method_name, parser.params] - end - end - - module StreamParserMixin - attr_reader :params - attr_reader :method_name - attr_reader :fault - - def initialize(*a) - super(*a) - @params = [] - @values = [] - @val_stack = [] - - @names = [] - @name = [] - - @structs = [] - @struct = {} - - @method_name = nil - @fault = nil - - @data = nil - end - - def startElement(name, attrs=[]) - @data = nil - case name - when "value" - @value = nil - when "nil" - raise "wrong/unknown XML-RPC type 'nil'" unless Config::ENABLE_NIL_PARSER - @value = :nil - when "array" - @val_stack << @values - @values = [] - when "struct" - @names << @name - @name = [] - - @structs << @struct - @struct = {} - end - end - - def endElement(name) - @data ||= "" - case name - when "string" - @value = @data - when "i4", "int" - @value = Convert.int(@data) - when "boolean" - @value = Convert.boolean(@data) - when "double" - @value = Convert.double(@data) - when "dateTime.iso8601" - @value = Convert.dateTime(@data) - when "base64" - @value = Convert.base64(@data) - when "value" - @value = @data if @value.nil? - @values << (@value == :nil ? nil : @value) - when "array" - @value = @values - @values = @val_stack.pop - when "struct" - @value = Convert.struct(@struct) - - @name = @names.pop - @struct = @structs.pop - when "name" - @name[0] = @data - when "member" - @struct[@name[0]] = @values.pop - - when "param" - @params << @values[0] - @values = [] - - when "fault" - @fault = Convert.fault(@values[0]) - - when "methodName" - @method_name = @data - end - - @data = nil - end - - def character(data) - if @data - @data << data - else - @data = data - end - end - - end # module StreamParserMixin - - # --------------------------------------------------------------------------- - class XMLStreamParser < AbstractStreamParser - def initialize - require "xmlparser" - @parser_class = Class.new(::XMLParser) { - include StreamParserMixin - } - end - end # class XMLStreamParser - # --------------------------------------------------------------------------- - class NQXMLStreamParser < AbstractStreamParser - def initialize - require "nqxml/streamingparser" - @parser_class = XMLRPCParser - end - - class XMLRPCParser - include StreamParserMixin - - def parse(str) - parser = NQXML::StreamingParser.new(str) - parser.each do |ele| - case ele - when NQXML::Text - @data = ele.text - #character(ele.text) - when NQXML::Tag - if ele.isTagEnd - endElement(ele.name) - else - startElement(ele.name, ele.attrs) - end - end - end # do - end # method parse - end # class XMLRPCParser - - end # class NQXMLStreamParser - # --------------------------------------------------------------------------- - class XMLTreeParser < AbstractTreeParser - - def initialize - require "xmltreebuilder" - - # The new XMLParser library (0.6.2+) uses a slightly different DOM implementation. - # The following code removes the differences between both versions. - if defined? XML::DOM::Builder - return if defined? XML::DOM::Node::DOCUMENT # code below has been already executed - klass = XML::DOM::Node - klass.const_set("DOCUMENT", klass::DOCUMENT_NODE) - klass.const_set("TEXT", klass::TEXT_NODE) - klass.const_set("COMMENT", klass::COMMENT_NODE) - klass.const_set("ELEMENT", klass::ELEMENT_NODE) - end - end - - private - - def _nodeType(node) - tp = node.nodeType - if tp == XML::SimpleTree::Node::TEXT then :TEXT - elsif tp == XML::SimpleTree::Node::COMMENT then :COMMENT - elsif tp == XML::SimpleTree::Node::ELEMENT then :ELEMENT - else :ELSE - end - end - - - def methodResponse_document(node) - assert( node.nodeType == XML::SimpleTree::Node::DOCUMENT ) - hasOnlyOneChild(node, "methodResponse") - - methodResponse(node.firstChild) - end - - def methodCall_document(node) - assert( node.nodeType == XML::SimpleTree::Node::DOCUMENT ) - hasOnlyOneChild(node, "methodCall") - - methodCall(node.firstChild) - end - - def createCleanedTree(str) - doc = XML::SimpleTreeBuilder.new.parse(str) - doc.documentElement.normalize - removeWhitespacesAndComments(doc) - doc - end - - end # class XMLParser - # --------------------------------------------------------------------------- - class NQXMLTreeParser < AbstractTreeParser - - def initialize - require "nqxml/treeparser" - end - - private - - def _nodeType(node) - node.nodeType - end - - def methodResponse_document(node) - methodResponse(node) - end - - def methodCall_document(node) - methodCall(node) - end - - def createCleanedTree(str) - doc = ::NQXML::TreeParser.new(str).document.rootNode - removeWhitespacesAndComments(doc) - doc - end - - end # class NQXMLTreeParser - # --------------------------------------------------------------------------- - class REXMLStreamParser < AbstractStreamParser - def initialize - require "rexml/document" - @parser_class = StreamListener - end - - class StreamListener - include StreamParserMixin - - alias :tag_start :startElement - alias :tag_end :endElement - alias :text :character - alias :cdata :character - - def method_missing(*a) - # ignore - end - - def parse(str) - parser = REXML::Document.parse_stream(str, self) - end - end - - end - # --------------------------------------------------------------------------- - class XMLScanStreamParser < AbstractStreamParser - def initialize - require "xmlscan/parser" - @parser_class = XMLScanParser - end - - class XMLScanParser - include StreamParserMixin - - Entities = { - "lt" => "<", - "gt" => ">", - "amp" => "&", - "quot" => '"', - "apos" => "'" - } - - def parse(str) - parser = XMLScan::XMLParser.new(self) - parser.parse(str) - end - - alias :on_stag :startElement - alias :on_etag :endElement - - def on_stag_end(name); end - - def on_stag_end_empty(name) - startElement(name) - endElement(name) - end - - def on_chardata(str) - character(str) - end - - def on_cdata(str) - character(str) - end - - def on_entityref(ent) - str = Entities[ent] - if str - character(str) - else - raise "unknown entity" - end - end - - def on_charref(code) - character(code.chr) - end - - def on_charref_hex(code) - character(code.chr) - end - - def method_missing(*a) - end - - # TODO: call/implement? - # valid_name? - # valid_chardata? - # valid_char? - # parse_error - - end - end - # --------------------------------------------------------------------------- - XMLParser = XMLTreeParser - NQXMLParser = NQXMLTreeParser - - Classes = [XMLStreamParser, XMLTreeParser, - NQXMLStreamParser, NQXMLTreeParser, - REXMLStreamParser, XMLScanStreamParser] - - # yields an instance of each installed parser - def self.each_installed_parser - XMLRPC::XMLParser::Classes.each do |klass| - begin - yield klass.new - rescue LoadError - end - end - end - - end # module XMLParser - - -end # module XMLRPC - diff --git a/Src/StdLib/ruby/1.9.1/xmlrpc/server.rb b/Src/StdLib/ruby/1.9.1/xmlrpc/server.rb deleted file mode 100644 index 29ebd3b2e..000000000 --- a/Src/StdLib/ruby/1.9.1/xmlrpc/server.rb +++ /dev/null @@ -1,778 +0,0 @@ -=begin -= xmlrpc/server.rb -Copyright (C) 2001, 2002, 2003, 2005 by Michael Neumann (mneumann@ntecs.de) - -Released under the same term of license as Ruby. - -= Classes -* (()) -* (()) -* (()) -* (()) -* (()) - -= XMLRPC::BasicServer -== Description -Is the base class for all XML-RPC server-types (CGI, standalone). -You can add handler and set a default handler. -Do not use this server, as this is/should be an abstract class. - -=== How the method to call is found -The arity (number of accepted arguments) of a handler (method or (({Proc})) object) is -compared to the given arguments submitted by the client for a RPC ((-Remote Procedure Call-)). -A handler is only called if it accepts the number of arguments, otherwise the search -for another handler will go on. When at the end no handler was found, -the (()) will be called. -With this technique it is possible to do overloading by number of parameters, but -only for (({Proc})) handler, because you cannot define two methods of the same name in -the same class. - - -== Class Methods ---- XMLRPC::BasicServer.new( class_delim="." ) - Creates a new (({XMLRPC::BasicServer})) instance, which should not be - done, because (({XMLRPC::BasicServer})) is an abstract class. This - method should be called from a subclass indirectly by a (({super})) call - in the method (({initialize})). The paramter ((|class_delim|)) is used - in (()) when an object is - added as handler, to delimit the object-prefix and the method-name. - -== Instance Methods ---- XMLRPC::BasicServer#add_handler( name, signature=nil, help=nil ) { aBlock } - Adds ((|aBlock|)) to the list of handlers, with ((|name|)) as the name of the method. - Parameters ((|signature|)) and ((|help|)) are used by the Introspection method if specified, - where ((|signature|)) is either an Array containing strings each representing a type of it's - signature (the first is the return value) or an Array of Arrays if the method has multiple - signatures. Value type-names are "int, boolean, double, string, dateTime.iso8601, base64, array, struct". - - Parameter ((|help|)) is a String with informations about how to call this method etc. - - A handler method or code-block can return the types listed at - (()). - When a method fails, it can tell it the client by throwing an - (({XMLRPC::FaultException})) like in this example: - s.add_handler("michael.div") do |a,b| - if b == 0 - raise XMLRPC::FaultException.new(1, "division by zero") - else - a / b - end - end - The client gets in the case of (({b==0})) an object back of type - (({XMLRPC::FaultException})) that has a ((|faultCode|)) and ((|faultString|)) - field. - ---- XMLRPC::BasicServer#add_handler( prefix, obj ) - This is the second form of (()). - To add an object write: - server.add_handler("michael", MyHandlerClass.new) - All public methods of (({MyHandlerClass})) are accessible to - the XML-RPC clients by (('michael."name of method"')). This is - where the ((|class_delim|)) in (()) - has it's role, a XML-RPC method-name is defined by - ((|prefix|)) + ((|class_delim|)) + (('"name of method"')). - ---- XMLRPC::BasicServer#add_handler( interface, obj ) - This is the third form of (()). - - Use (({XMLRPC::interface})) to generate an ServiceInterface object, which - represents an interface (with signature and help text) for a handler class. - - Parameter ((|interface|)) must be of type (({XMLRPC::ServiceInterface})). - Adds all methods of ((|obj|)) which are defined in ((|interface|)) to the - server. - - This is the recommended way of adding services to a server! - - ---- XMLRPC::BasicServer#get_default_handler - Returns the default-handler, which is called when no handler for - a method-name is found. - It is a (({Proc})) object or (({nil})). - ---- XMLRPC::BasicServer#set_default_handler ( &handler ) - Sets ((|handler|)) as the default-handler, which is called when - no handler for a method-name is found. ((|handler|)) is a code-block. - The default-handler is called with the (XML-RPC) method-name as first argument, and - the other arguments are the parameters given by the client-call. - - If no block is specified the default of (({XMLRPC::BasicServer})) is used, which raises a - XMLRPC::FaultException saying "method missing". - - ---- XMLRPC::BasicServer#set_writer( writer ) - Sets the XML writer to use for generating XML output. - Should be an instance of a class from module (({XMLRPC::XMLWriter})). - If this method is not called, then (({XMLRPC::Config::DEFAULT_WRITER})) is used. - ---- XMLRPC::BasicServer#set_parser( parser ) - Sets the XML parser to use for parsing XML documents. - Should be an instance of a class from module (({XMLRPC::XMLParser})). - If this method is not called, then (({XMLRPC::Config::DEFAULT_PARSER})) is used. - ---- XMLRPC::BasicServer#add_introspection - Adds the introspection handlers "system.listMethods", "system.methodSignature" and "system.methodHelp", - where only the first one works. - ---- XMLRPC::BasicServer#add_multicall - Adds the multi-call handler "system.multicall". - ---- XMLRPC::BasicServer#get_service_hook - Returns the service-hook, which is called on each service request (RPC) unless it's (({nil})). - ---- XMLRPC::BasicServer#set_service_hook ( &handler ) - A service-hook is called for each service request (RPC). - You can use a service-hook for example to wrap existing methods and catch exceptions of them or - convert values to values recognized by XMLRPC. You can disable it by passing (({nil})) as parameter - ((|handler|)) . - - The service-hook is called with a (({Proc})) object and with the parameters for this (({Proc})). - An example: - - server.set_service_hook {|obj, *args| - begin - ret = obj.call(*args) # call the original service-method - # could convert the return value - rescue - # rescue exceptions - end - } - -=end - - - -require "xmlrpc/parser" -require "xmlrpc/create" -require "xmlrpc/config" -require "xmlrpc/utils" # ParserWriterChooseMixin - - - -module XMLRPC - - -class BasicServer - - include ParserWriterChooseMixin - include ParseContentType - - ERR_METHOD_MISSING = 1 - ERR_UNCAUGHT_EXCEPTION = 2 - ERR_MC_WRONG_PARAM = 3 - ERR_MC_MISSING_PARAMS = 4 - ERR_MC_MISSING_METHNAME = 5 - ERR_MC_RECURSIVE_CALL = 6 - ERR_MC_WRONG_PARAM_PARAMS = 7 - ERR_MC_EXPECTED_STRUCT = 8 - - - def initialize(class_delim=".") - @handler = [] - @default_handler = nil - @service_hook = nil - - @class_delim = class_delim - @create = nil - @parser = nil - - add_multicall if Config::ENABLE_MULTICALL - add_introspection if Config::ENABLE_INTROSPECTION - end - - def add_handler(prefix, obj_or_signature=nil, help=nil, &block) - if block_given? - # proc-handler - @handler << [prefix, block, obj_or_signature, help] - else - if prefix.kind_of? String - # class-handler - raise ArgumentError, "Expected non-nil value" if obj_or_signature.nil? - @handler << [prefix + @class_delim, obj_or_signature] - elsif prefix.kind_of? XMLRPC::Service::BasicInterface - # class-handler with interface - # add all methods - @handler += prefix.get_methods(obj_or_signature, @class_delim) - else - raise ArgumentError, "Wrong type for parameter 'prefix'" - end - end - self - end - - def get_service_hook - @service_hook - end - - def set_service_hook(&handler) - @service_hook = handler - self - end - - def get_default_handler - @default_handler - end - - def set_default_handler (&handler) - @default_handler = handler - self - end - - def add_multicall - add_handler("system.multicall", %w(array array), "Multicall Extension") do |arrStructs| - unless arrStructs.is_a? Array - raise XMLRPC::FaultException.new(ERR_MC_WRONG_PARAM, "system.multicall expects an array") - end - - arrStructs.collect {|call| - if call.is_a? Hash - methodName = call["methodName"] - params = call["params"] - - if params.nil? - multicall_fault(ERR_MC_MISSING_PARAMS, "Missing params") - elsif methodName.nil? - multicall_fault(ERR_MC_MISSING_METHNAME, "Missing methodName") - else - if methodName == "system.multicall" - multicall_fault(ERR_MC_RECURSIVE_CALL, "Recursive system.multicall forbidden") - else - unless params.is_a? Array - multicall_fault(ERR_MC_WRONG_PARAM_PARAMS, "Parameter params have to be an Array") - else - ok, val = call_method(methodName, *params) - if ok - # correct return value - [val] - else - # exception - multicall_fault(val.faultCode, val.faultString) - end - end - end - end - - else - multicall_fault(ERR_MC_EXPECTED_STRUCT, "system.multicall expected struct") - end - } - end # end add_handler - self - end - - def add_introspection - add_handler("system.listMethods",%w(array), "List methods available on this XML-RPC server") do - methods = [] - @handler.each do |name, obj| - if obj.kind_of? Proc - methods << name - else - obj.class.public_instance_methods(false).each do |meth| - methods << "#{name}#{meth}" - end - end - end - methods - end - - add_handler("system.methodSignature", %w(array string), "Returns method signature") do |meth| - sigs = [] - @handler.each do |name, obj, sig| - if obj.kind_of? Proc and sig != nil and name == meth - if sig[0].kind_of? Array - # sig contains multiple signatures, e.g. [["array"], ["array", "string"]] - sig.each {|s| sigs << s} - else - # sig is a single signature, e.g. ["array"] - sigs << sig - end - end - end - sigs.uniq! || sigs # remove eventually duplicated signatures - end - - add_handler("system.methodHelp", %w(string string), "Returns help on using this method") do |meth| - help = nil - @handler.each do |name, obj, sig, hlp| - if obj.kind_of? Proc and name == meth - help = hlp - break - end - end - help || "" - end - - self - end - - - - def process(data) - method, params = parser().parseMethodCall(data) - handle(method, *params) - end - - private # -------------------------------------------------------------- - - def multicall_fault(nr, str) - {"faultCode" => nr, "faultString" => str} - end - - # - # method dispatch - # - def dispatch(methodname, *args) - for name, obj in @handler - if obj.kind_of? Proc - next unless methodname == name - else - next unless methodname =~ /^#{name}(.+)$/ - next unless obj.respond_to? $1 - obj = obj.method($1) - end - - if check_arity(obj, args.size) - if @service_hook.nil? - return obj.call(*args) - else - return @service_hook.call(obj, *args) - end - end - end - - if @default_handler.nil? - raise XMLRPC::FaultException.new(ERR_METHOD_MISSING, "Method #{methodname} missing or wrong number of parameters!") - else - @default_handler.call(methodname, *args) - end - end - - - # - # returns true, if the arity of "obj" matches - # - def check_arity(obj, n_args) - ary = obj.arity - - if ary >= 0 - n_args == ary - else - n_args >= (ary+1).abs - end - end - - - - def call_method(methodname, *args) - begin - [true, dispatch(methodname, *args)] - rescue XMLRPC::FaultException => e - [false, e] - rescue Exception => e - [false, XMLRPC::FaultException.new(ERR_UNCAUGHT_EXCEPTION, "Uncaught exception #{e.message} in method #{methodname}")] - end - end - - # - # - # - def handle(methodname, *args) - create().methodResponse(*call_method(methodname, *args)) - end - - -end - - -=begin -= XMLRPC::CGIServer -== Synopsis - require "xmlrpc/server" - - s = XMLRPC::CGIServer.new - - s.add_handler("michael.add") do |a,b| - a + b - end - - s.add_handler("michael.div") do |a,b| - if b == 0 - raise XMLRPC::FaultException.new(1, "division by zero") - else - a / b - end - end - - s.set_default_handler do |name, *args| - raise XMLRPC::FaultException.new(-99, "Method #{name} missing" + - " or wrong number of parameters!") - end - - s.serve - -== Description -Implements a CGI-based XML-RPC server. - -== Superclass -(()) - -== Class Methods ---- XMLRPC::CGIServer.new( *a ) - Creates a new (({XMLRPC::CGIServer})) instance. All parameters given - are by-passed to (()). You can only create - ((*one*)) (({XMLRPC::CGIServer})) instance, because more than one makes - no sense. - -== Instance Methods ---- XMLRPC::CGIServer#serve - Call this after you have added all you handlers to the server. - This method processes a XML-RPC methodCall and sends the answer - back to the client. - Make sure that you don't write to standard-output in a handler, or in - any other part of your program, this would case a CGI-based server to fail! -=end - -class CGIServer < BasicServer - @@obj = nil - - def CGIServer.new(*a) - @@obj = super(*a) if @@obj.nil? - @@obj - end - - def initialize(*a) - super(*a) - end - - def serve - catch(:exit_serve) { - length = ENV['CONTENT_LENGTH'].to_i - - http_error(405, "Method Not Allowed") unless ENV['REQUEST_METHOD'] == "POST" - http_error(400, "Bad Request") unless parse_content_type(ENV['CONTENT_TYPE']).first == "text/xml" - http_error(411, "Length Required") unless length > 0 - - # TODO: do we need a call to binmode? - $stdin.binmode if $stdin.respond_to? :binmode - data = $stdin.read(length) - - http_error(400, "Bad Request") if data.nil? or data.size != length - - http_write(process(data), "Content-type" => "text/xml; charset=utf-8") - } - end - - - private - - def http_error(status, message) - err = "#{status} #{message}" - msg = <<-"MSGEND" - - - #{err} - - -

#{err}

-

Unexpected error occured while processing XML-RPC request!

- - - MSGEND - - http_write(msg, "Status" => err, "Content-type" => "text/html") - throw :exit_serve # exit from the #serve method - end - - def http_write(body, header) - h = {} - header.each {|key, value| h[key.to_s.capitalize] = value} - h['Status'] ||= "200 OK" - h['Content-length'] ||= body.size.to_s - - str = "" - h.each {|key, value| str << "#{key}: #{value}\r\n"} - str << "\r\n#{body}" - - print str - end - -end - -=begin -= XMLRPC::ModRubyServer -== Description -Implements a XML-RPC server, which works with Apache mod_ruby. - -Use it in the same way as CGIServer! - -== Superclass -(()) -=end - -class ModRubyServer < BasicServer - - def initialize(*a) - @ap = Apache::request - super(*a) - end - - def serve - catch(:exit_serve) { - header = {} - @ap.headers_in.each {|key, value| header[key.capitalize] = value} - - length = header['Content-length'].to_i - - http_error(405, "Method Not Allowed") unless @ap.request_method == "POST" - http_error(400, "Bad Request") unless parse_content_type(header['Content-type']).first == "text/xml" - http_error(411, "Length Required") unless length > 0 - - # TODO: do we need a call to binmode? - @ap.binmode - data = @ap.read(length) - - http_error(400, "Bad Request") if data.nil? or data.size != length - - http_write(process(data), 200, "Content-type" => "text/xml; charset=utf-8") - } - end - - - private - - def http_error(status, message) - err = "#{status} #{message}" - msg = <<-"MSGEND" - - - #{err} - - -

#{err}

-

Unexpected error occured while processing XML-RPC request!

- - - MSGEND - - http_write(msg, status, "Status" => err, "Content-type" => "text/html") - throw :exit_serve # exit from the #serve method - end - - def http_write(body, status, header) - h = {} - header.each {|key, value| h[key.to_s.capitalize] = value} - h['Status'] ||= "200 OK" - h['Content-length'] ||= body.size.to_s - - h.each {|key, value| @ap.headers_out[key] = value } - @ap.content_type = h["Content-type"] - @ap.status = status.to_i - @ap.send_http_header - - @ap.print body - end - -end - -=begin -= XMLRPC::Server -== Synopsis - require "xmlrpc/server" - - s = XMLRPC::Server.new(8080) - - s.add_handler("michael.add") do |a,b| - a + b - end - - s.add_handler("michael.div") do |a,b| - if b == 0 - raise XMLRPC::FaultException.new(1, "division by zero") - else - a / b - end - end - - s.set_default_handler do |name, *args| - raise XMLRPC::FaultException.new(-99, "Method #{name} missing" + - " or wrong number of parameters!") - end - - s.serve - -== Description -Implements a standalone XML-RPC server. The method (({serve}))) is left if a SIGHUP is sent to the -program. - -== Superclass -(()) - -== Class Methods ---- XMLRPC::Server.new( port=8080, host="127.0.0.1", maxConnections=4, stdlog=$stdout, audit=true, debug=true, *a ) - Creates a new (({XMLRPC::Server})) instance, which is a XML-RPC server listening on - port ((|port|)) and accepts requests for the host ((|host|)), which is by default only the localhost. - The server is not started, to start it you have to call (()). - - Parameters ((|audit|)) and ((|debug|)) are obsolete! - - All additionally given parameters in ((|*a|)) are by-passed to (()). - -== Instance Methods ---- XMLRPC::Server#serve - Call this after you have added all you handlers to the server. - This method starts the server to listen for XML-RPC requests and answer them. - ---- XMLRPC::Server#shutdown - Stops and shuts the server down. - -=end - -class WEBrickServlet < BasicServer; end # forward declaration - -class Server < WEBrickServlet - - def initialize(port=8080, host="127.0.0.1", maxConnections=4, stdlog=$stdout, audit=true, debug=true, *a) - super(*a) - require 'webrick' - @server = WEBrick::HTTPServer.new(:Port => port, :BindAddress => host, :MaxClients => maxConnections, - :Logger => WEBrick::Log.new(stdlog)) - @server.mount("/", self) - end - - def serve - signals = %w[INT TERM HUP] & Signal.list.keys - signals.each { |signal| trap(signal) { @server.shutdown } } - - @server.start - end - - def shutdown - @server.shutdown - end - -end - -=begin -= XMLRPC::WEBrickServlet -== Synopsis - - require "webrick" - require "xmlrpc/server" - - s = XMLRPC::WEBrickServlet.new - s.add_handler("michael.add") do |a,b| - a + b - end - - s.add_handler("michael.div") do |a,b| - if b == 0 - raise XMLRPC::FaultException.new(1, "division by zero") - else - a / b - end - end - - s.set_default_handler do |name, *args| - raise XMLRPC::FaultException.new(-99, "Method #{name} missing" + - " or wrong number of parameters!") - end - - httpserver = WEBrick::HTTPServer.new(:Port => 8080) - httpserver.mount("/RPC2", s) - trap("HUP") { httpserver.shutdown } # use 1 instead of "HUP" on Windows - httpserver.start - -== Instance Methods - ---- XMLRPC::WEBrickServlet#set_valid_ip( *ip_addr ) - Specifies the valid IP addresses that are allowed to connect to the server. - Each IP is either a (({String})) or a (({Regexp})). - ---- XMLRPC::WEBrickServlet#get_valid_ip - Return the via method (()) specified - valid IP addresses. - -== Description -Implements a servlet for use with WEBrick, a pure Ruby (HTTP-) server framework. - -== Superclass -(()) - -=end - -class WEBrickServlet < BasicServer - def initialize(*a) - super - require "webrick/httpstatus" - @valid_ip = nil - end - - # deprecated from WEBrick/1.2.2. - # but does not break anything. - def require_path_info? - false - end - - def get_instance(config, *options) - # TODO: set config & options - self - end - - def set_valid_ip(*ip_addr) - if ip_addr.size == 1 and ip_addr[0].nil? - @valid_ip = nil - else - @valid_ip = ip_addr - end - end - - def get_valid_ip - @valid_ip - end - - def service(request, response) - - if @valid_ip - raise WEBrick::HTTPStatus::Forbidden unless @valid_ip.any? { |ip| request.peeraddr[3] =~ ip } - end - - if request.request_method != "POST" - raise WEBrick::HTTPStatus::MethodNotAllowed, - "unsupported method `#{request.request_method}'." - end - - if parse_content_type(request['Content-type']).first != "text/xml" - raise WEBrick::HTTPStatus::BadRequest - end - - length = (request['Content-length'] || 0).to_i - - raise WEBrick::HTTPStatus::LengthRequired unless length > 0 - - data = request.body - - if data.nil? or data.size != length - raise WEBrick::HTTPStatus::BadRequest - end - - resp = process(data) - if resp.nil? or resp.size <= 0 - raise WEBrick::HTTPStatus::InternalServerError - end - - response.status = 200 - response['Content-Length'] = resp.size - response['Content-Type'] = "text/xml; charset=utf-8" - response.body = resp - end -end - - -end # module XMLRPC - - -=begin -= History - $Id: server.rb 26986 2010-03-20 03:30:59Z nobu $ -=end - diff --git a/Src/StdLib/ruby/1.9.1/xmlrpc/utils.rb b/Src/StdLib/ruby/1.9.1/xmlrpc/utils.rb deleted file mode 100644 index a48ae8696..000000000 --- a/Src/StdLib/ruby/1.9.1/xmlrpc/utils.rb +++ /dev/null @@ -1,165 +0,0 @@ -# -# Defines ParserWriterChooseMixin, which makes it possible to choose a -# different XML writer and/or XML parser then the default one. -# The Mixin is used in client.rb (class Client) and server.rb (class -# BasicServer) -# -# Copyright (C) 2001, 2002, 2003 by Michael Neumann (mneumann@ntecs.de) -# -# $Id: utils.rb 27537 2010-04-28 18:51:35Z jeg2 $ -# - -module XMLRPC - - # - # This module enables a user-class to be marshalled - # by XML-RPC for Ruby into a Hash, with one additional - # key/value pair "___class___" => ClassName - # - module Marshallable - end - - - module ParserWriterChooseMixin - - def set_writer(writer) - @create = Create.new(writer) - self - end - - def set_parser(parser) - @parser = parser - self - end - - private - - def create - # if set_writer was not already called then call it now - if @create.nil? then - set_writer(Config::DEFAULT_WRITER.new) - end - @create - end - - def parser - # if set_parser was not already called then call it now - if @parser.nil? then - set_parser(Config::DEFAULT_PARSER.new) - end - @parser - end - - end # module ParserWriterChooseMixin - - - module Service - - # - # base class for Service Interface definitions, used - # by BasicServer#add_handler - # - - class BasicInterface - attr_reader :prefix, :methods - - def initialize(prefix) - @prefix = prefix - @methods = [] - end - - def add_method(sig, help=nil, meth_name=nil) - mname = nil - sig = [sig] if sig.kind_of? String - - sig = sig.collect do |s| - name, si = parse_sig(s) - raise "Wrong signatures!" if mname != nil and name != mname - mname = name - si - end - - @methods << [mname, meth_name || mname, sig, help] - end - - private # --------------------------------- - - def parse_sig(sig) - # sig is a String - if sig =~ /^\s*(\w+)\s+([^(]+)(\(([^)]*)\))?\s*$/ - params = [$1] - name = $2.strip - $4.split(",").each {|i| params << i.strip} if $4 != nil - return name, params - else - raise "Syntax error in signature" - end - end - - end # class BasicInterface - - # - # class which wraps a Service Interface definition, used - # by BasicServer#add_handler - # - class Interface < BasicInterface - def initialize(prefix, &p) - raise "No interface specified" if p.nil? - super(prefix) - instance_eval(&p) - end - - def get_methods(obj, delim=".") - prefix = @prefix + delim - @methods.collect { |name, meth, sig, help| - [prefix + name.to_s, obj.method(meth).to_proc, sig, help] - } - end - - private # --------------------------------- - - def meth(*a) - add_method(*a) - end - - end # class Interface - - class PublicInstanceMethodsInterface < BasicInterface - def initialize(prefix) - super(prefix) - end - - def get_methods(obj, delim=".") - prefix = @prefix + delim - obj.class.public_instance_methods(false).collect { |name| - [prefix + name.to_s, obj.method(name).to_proc, nil, nil] - } - end - end - - - end # module Service - - - # - # short-form to create a Service::Interface - # - def self.interface(prefix, &p) - Service::Interface.new(prefix, &p) - end - - # short-cut for creating a PublicInstanceMethodsInterface - def self.iPIMethods(prefix) - Service::PublicInstanceMethodsInterface.new(prefix) - end - - - module ParseContentType - def parse_content_type(str) - a, *b = str.split(";") - return a.strip.downcase, *b - end - end - -end # module XMLRPC - diff --git a/Src/StdLib/ruby/1.9.1/yaml/syck.rb b/Src/StdLib/ruby/1.9.1/yaml/syck.rb deleted file mode 100644 index 655f70a97..000000000 --- a/Src/StdLib/ruby/1.9.1/yaml/syck.rb +++ /dev/null @@ -1,14 +0,0 @@ -# $Id$ -# -# = yaml/syck.rb: -# - -require 'stringio' -require 'syck.so' -require 'syck/error' -require 'syck/syck' -require 'syck/tag' -require 'syck/stream' -require 'syck/constants' -require 'syck/rubytypes' -require 'syck/types' diff --git a/Tests/Libraries/ParseTreeTests/pt_testcase.rb b/Tests/Libraries/ParseTreeTests/pt_testcase.rb deleted file mode 100644 index 7c5c8109e..000000000 --- a/Tests/Libraries/ParseTreeTests/pt_testcase.rb +++ /dev/null @@ -1,4417 +0,0 @@ -$TESTING = true - -require 'minitest/unit' -require 'sexp_processor' # for deep_clone - -# key: -# wwtt = what were they thinking? - -# TODO: 1.8.7 support {|&b|} syntax - -class Examples - attr_reader :reader - attr_writer :writer - - def a_method(x); x+1; end - alias an_alias a_method - - define_method(:bmethod_noargs) do - x + 1 - end - - define_method(:unsplatted) do |x| - x + 1 - end - - define_method :splatted do |*args| - y = args.first - y + 42 - end - - define_method :dmethod_added, instance_method(:a_method) if - RUBY_VERSION < "1.9" -end - -class ParseTreeTestCase < MiniTest::Unit::TestCase - attr_accessor :processor # to be defined by subclass - - def setup - super - @processor = nil - end - - def after_process_hook klass, node, data, input_name, output_name - end - - def before_process_hook klass, node, data, input_name, output_name - end - - def self.add_test name, data, klass = self.name[4..-1] - name = name.to_s - klass = klass.to_s - - if testcases.has_key? name then - if testcases[name].has_key? klass then - warn "testcase #{klass}##{name} already has data" - else - testcases[name][klass] = data - end - else - warn "testcase #{name} does not exist" - end - end - - def self.add_tests name, hash - name = name.to_s - - hash.each do |klass, data| - warn "testcase #{klass}##{name} already has data" if - testcases[name].has_key? klass - testcases[name][klass] = data - end - end - - def self.clone_same - @@testcases.each do |node, data| - data.each do |key, val| - if val == :same then - prev_key = self.previous(key) - data[key] = data[prev_key].deep_clone - end - end - end - end - - def self.copy_test_case nonverbose, klass - verbose = nonverbose + "_mri_verbose_flag" - testcases[verbose][klass] = testcases[nonverbose][klass] - end - - def self.generate_test klass, node, data, input_name, output_name - klass.send(:define_method, "test_#{node}".to_sym) do - flunk "Processor is nil" if processor.nil? - - assert data.has_key?(input_name), "Unknown input data" - assert data.has_key?(output_name), "Missing test data" - - $missing[node] << output_name unless data.has_key? output_name - - input = data[input_name].deep_clone - expected = data[output_name].deep_clone - - case expected - when :unsupported then - assert_raises(UnsupportedNodeError) do - processor.process(input) - end - else - extra_expected = [] - extra_input = [] - - _, expected, extra_expected = *expected if - Array === expected and expected.first == :defx - _, input, extra_input = *input if - Array === input and input.first == :defx - - # OMG... I can't believe I have to do this this way. these - # hooks are here instead of refactoring this define_method - # body into an assertion. It'll allow subclasses to hook in - # and add behavior before or after the processor does it's - # thing. If you go the body refactor route, some of the - # RawParseTree test casese fail for completely bogus reasons. - - before_process_hook klass, node, data, input_name, output_name - refute_nil data[input_name], "testcase does not exist?" - @result = processor.process input - assert_equal(expected, @result, - "failed on input: #{data[input_name].inspect}") - after_process_hook klass, node, data, input_name, output_name - - extra_input.each do |extra| - processor.process(extra) - end - extra = processor.extra_methods rescue [] - assert_equal extra_expected, extra - end - end - end - - def self.generate_tests klass - install_missing_reporter - clone_same - - output_name = klass.name.to_s.sub(/^Test/, '') - - input_name = self.previous(output_name) - - @@testcases.each do |node, data| - next if [:skip, :unsupported].include? data[input_name] - next if data[output_name] == :skip - - generate_test klass, node, data, input_name, output_name - end - end - - def self.inherited klass - super - - generate_tests klass unless klass.name =~ /TestCase/ - end - - def self.install_missing_reporter - unless defined? $missing then - $missing = Hash.new { |h,k| h[k] = [] } - at_exit { - at_exit { - warn "" - $missing.sort.each do |name, klasses| - warn "add_tests(#{name.inspect}," - klasses.map! { |klass| " #{klass.inspect} => :same" } - warn klasses.join("\n") + ")" - end - warn "" - } - } - end - end - - def self.previous(key, extra=0) # FIX: remove R2C code - idx = @@testcase_order.index(key) - - raise "Unknown class #{key} in @@testcase_order" if idx.nil? - - case key - when "RubyToRubyC" then - idx -= 1 - end - @@testcase_order[idx - 1 - extra] - end - - def self.testcase_order; @@testcase_order; end - def self.testcases; @@testcases; end - - def self.unsupported_tests *tests - tests.flatten.each do |name| - add_test name, :unsupported - end - end - - ############################################################ - # Shared TestCases: - - @@testcase_order = %w(Ruby RawParseTree ParseTree) - - @@testcases = Hash.new { |h,k| h[k] = {} } - - add_tests("alias", - "Ruby" => "class X\n alias :y :x\nend", - "RawParseTree" => [:class, :X, nil, - [:scope, [:alias, [:lit, :y], [:lit, :x]]]], - "ParseTree" => s(:class, :X, nil, - s(:scope, s(:alias, s(:lit, :y), s(:lit, :x))))) - - add_tests("alias_ugh", - "Ruby" => "class X\n alias y x\nend", - "RawParseTree" => [:class, :X, nil, - [:scope, [:alias, [:lit, :y], [:lit, :x]]]], - "ParseTree" => s(:class, :X, nil, - s(:scope, s(:alias, s(:lit, :y), s(:lit, :x)))), - "Ruby2Ruby" => "class X\n alias :y :x\nend") - - add_tests("and", - "Ruby" => "(a and b)", - "RawParseTree" => [:and, [:vcall, :a], [:vcall, :b]], - "ParseTree" => s(:and, - s(:call, nil, :a, s(:arglist)), - s(:call, nil, :b, s(:arglist)))) - - add_tests("argscat_inside", - "Ruby" => "a = [b, *c]", - "RawParseTree" => [:lasgn, :a, - [:argscat, - [:array, [:vcall, :b]], [:vcall, :c]]], - "ParseTree" => s(:lasgn, :a, - s(:array, - s(:call, nil, :b, s(:arglist)), - s(:splat, s(:call, nil, :c, s(:arglist)))))) - - add_tests("argscat_svalue", - "Ruby" => "a = b, c, *d", - "RawParseTree" => [:lasgn, :a, - [:svalue, - [:argscat, - [:array, [:vcall, :b], [:vcall, :c]], - [:vcall, :d]]]], - "ParseTree" => s(:lasgn, :a, - s(:svalue, - s(:array, - s(:call, nil, :b, s(:arglist)), - s(:call, nil, :c, s(:arglist)), - s(:splat, - s(:call, nil, :d, s(:arglist))))))) - - add_tests("argspush", - "Ruby" => "a[*b] = c", - "RawParseTree" => [:attrasgn, - [:vcall, :a], - :[]=, - [:argspush, - [:splat, - [:vcall, :b]], - [:vcall, :c]]], - "ParseTree" => s(:attrasgn, - s(:call, nil, :a, s(:arglist)), - :[]=, - s(:arglist, - s(:splat, - s(:call, nil, :b, s(:arglist))), - s(:call, nil, :c, s(:arglist))))) - - add_tests("array", - "Ruby" => "[1, :b, \"c\"]", - "RawParseTree" => [:array, [:lit, 1], [:lit, :b], [:str, "c"]], - "ParseTree" => s(:array, s(:lit, 1), s(:lit, :b), s(:str, "c"))) - - add_tests("array_pct_W", - "Ruby" => "%W[a b c]", - "RawParseTree" => [:array, [:str, "a"], [:str, "b"], [:str, "c"]], - "ParseTree" => s(:array, - s(:str, "a"), s(:str, "b"), s(:str, "c")), - "Ruby2Ruby" => "[\"a\", \"b\", \"c\"]") - - add_tests("array_pct_W_dstr", - "Ruby" => "%W[a #\{@b} c]", - "RawParseTree" => [:array, - [:str, "a"], - [:dstr, "", [:evstr, [:ivar, :@b]]], - [:str, "c"]], - "ParseTree" => s(:array, - s(:str, "a"), - s(:dstr, "", s(:evstr, s(:ivar, :@b))), - s(:str, "c")), - "Ruby2Ruby" => "[\"a\", \"#\{@b}\", \"c\"]") - - add_tests("array_pct_w", - "Ruby" => "%w[a b c]", - "RawParseTree" => [:array, [:str, "a"], [:str, "b"], [:str, "c"]], - "ParseTree" => s(:array, - s(:str, "a"), s(:str, "b"), s(:str, "c")), - "Ruby2Ruby" => "[\"a\", \"b\", \"c\"]") - - add_tests("array_pct_w_dstr", - "Ruby" => "%w[a #\{@b} c]", - "RawParseTree" => [:array, - [:str, "a"], - [:str, "#\{@b}"], - [:str, "c"]], - "ParseTree" => s(:array, - s(:str, "a"), - s(:str, "#\{@b}"), - s(:str, "c")), - "Ruby2Ruby" => "[\"a\", \"\\\#{@b}\", \"c\"]") # TODO: huh? - - add_tests("attrasgn", - "Ruby" => "y = 0\n42.method = y\n", - "RawParseTree" => [:block, - [:lasgn, :y, [:lit, 0]], - [:attrasgn, [:lit, 42], :method=, - [:array, [:lvar, :y]]]], - "ParseTree" => s(:block, - s(:lasgn, :y, s(:lit, 0)), - s(:attrasgn, s(:lit, 42), :method=, - s(:arglist, s(:lvar, :y))))) - - add_tests("attrasgn_index_equals", - "Ruby" => "a[42] = 24", - "RawParseTree" => [:attrasgn, [:vcall, :a], :[]=, - [:array, [:lit, 42], [:lit, 24]]], - "ParseTree" => s(:attrasgn, - s(:call, nil, :a, s(:arglist)), - :[]=, - s(:arglist, s(:lit, 42), s(:lit, 24)))) - - add_tests("attrasgn_index_equals_space", - "Ruby" => "a = []; a [42] = 24", - "RawParseTree" => [:block, - [:lasgn, :a, [:zarray]], - [:attrasgn, [:lvar, :a], :[]=, - [:array, [:lit, 42], [:lit, 24]]]], - "ParseTree" => s(:block, - s(:lasgn, :a, s(:array)), - s(:attrasgn, s(:lvar, :a), :[]=, - s(:arglist, s(:lit, 42), s(:lit, 24)))), - "Ruby2Ruby" => "a = []\na[42] = 24\n") - - add_tests("attrset", - "Ruby" => [Examples, :writer=], - "RawParseTree" => [:defn, :writer=, [:attrset, :@writer]], - "ParseTree" => s(:defn, :writer=, - s(:args, :arg), - s(:attrset, :@writer)), - "Ruby2Ruby" => "attr_writer :writer") - - add_tests("back_ref", - "Ruby" => "[$&, $`, $', $+]", - "RawParseTree" => [:array, - [:back_ref, :&], - [:back_ref, :"`"], - [:back_ref, :"'"], - [:back_ref, :+]], - "ParseTree" => s(:array, - s(:back_ref, :&), - s(:back_ref, :"`"), - s(:back_ref, :"'"), - s(:back_ref, :+))) - - add_tests("begin", - "Ruby" => "begin\n (1 + 1)\nend", - "RawParseTree" => [:call, [:lit, 1], :+, [:array, [:lit, 1]]], - "ParseTree" => s(:call, s(:lit, 1), :+, - s(:arglist, s(:lit, 1))), - "Ruby2Ruby" => "(1 + 1)") - - add_tests("begin_def", - "Ruby" => "def m\n begin\n\n end\nend", - "RawParseTree" => [:defn, :m, [:scope, [:block, [:args], [:nil]]]], - "ParseTree" => s(:defn, :m, s(:args), - s(:scope, s(:block, s(:nil)))), - "Ruby2Ruby" => "def m\n # do nothing\nend") - - add_tests("begin_rescue_ensure", - "Ruby" => "begin\n a\nrescue\n # do nothing\nensure\n # do nothing\nend", - "RawParseTree" => [:ensure, - [:rescue, - [:vcall, :a], - [:resbody, nil]], - [:nil]], - "ParseTree" => s(:ensure, - s(:rescue, - s(:call, nil, :a, s(:arglist)), - s(:resbody, s(:array), nil)), - s(:nil))) - - add_tests("begin_rescue_ensure_all_empty", - "Ruby" => "begin\n # do nothing\nrescue\n # do nothing\nensure\n # do nothing\nend", - "RawParseTree" => [:ensure, - [:rescue, - [:resbody, nil]], - [:nil]], - "ParseTree" => s(:ensure, - s(:rescue, - s(:resbody, s(:array), nil)), - s(:nil))) - - add_tests("begin_rescue_twice", - "Ruby" => "begin\n a\nrescue => mes\n # do nothing\nend\nbegin\n b\nrescue => mes\n # do nothing\nend\n", - "RawParseTree" => [:block, - [:rescue, - [:vcall, :a], - [:resbody, nil, - [:lasgn, :mes, [:gvar, :$!]]]], - [:rescue, - [:vcall, :b], - [:resbody, nil, - [:lasgn, :mes, [:gvar, :$!]]]]], - "ParseTree" => s(:block, - s(:rescue, - s(:call, nil, :a, s(:arglist)), - s(:resbody, - s(:array, s(:lasgn, :mes, s(:gvar, :$!))), - nil)), - s(:rescue, - s(:call, nil, :b, s(:arglist)), - s(:resbody, - s(:array, - s(:lasgn, :mes, s(:gvar, :$!))), - nil)))) - - add_tests("begin_rescue_twice_mri_verbose_flag", - "RawParseTree" => [:block, - [:rescue, # no begin - [:vcall, :a], - [:resbody, nil, - [:lasgn, :mes, [:gvar, :$!]]]], - [:rescue, - [:vcall, :b], - [:resbody, nil, - [:lasgn, :mes, [:gvar, :$!]]]]]) - - copy_test_case "begin_rescue_twice", "Ruby" - copy_test_case "begin_rescue_twice", "ParseTree" - - add_tests("block_attrasgn", - "Ruby" => "def self.setup(ctx)\n bind = allocate\n bind.context = ctx\n return bind\nend", - "RawParseTree" => [:defs, [:self], :setup, - [:scope, - [:block, - [:args, :ctx], - [:lasgn, :bind, [:vcall, :allocate]], - [:attrasgn, [:lvar, :bind], :context=, - [:array, [:lvar, :ctx]]], - [:return, [:lvar, :bind]]]]], - "ParseTree" => s(:defs, s(:self), :setup, - s(:args, :ctx), - s(:scope, - s(:block, - s(:lasgn, :bind, - s(:call, nil, :allocate, s(:arglist))), - s(:attrasgn, s(:lvar, :bind), :context=, - s(:arglist, s(:lvar, :ctx))), - s(:return, s(:lvar, :bind)))))) - - - add_tests("block_lasgn", - "Ruby" => "x = (y = 1\n(y + 2))", - "RawParseTree" => [:lasgn, :x, - [:block, - [:lasgn, :y, [:lit, 1]], - [:call, [:lvar, :y], :+, [:array, [:lit, 2]]]]], - "ParseTree" => s(:lasgn, :x, - s(:block, - s(:lasgn, :y, s(:lit, 1)), - s(:call, s(:lvar, :y), :+, - s(:arglist, s(:lit, 2)))))) - - add_tests("block_mystery_block", - "Ruby" => "a(b) do\n if b then\n true\n else\n c = false\n d { |x| c = true }\n c\n end\nend", - "RawParseTree" => [:iter, - [:fcall, :a, [:array, [:vcall, :b]]], - nil, - [:if, - [:vcall, :b], - [:true], - [:block, - [:dasgn_curr, :c, [:false]], - [:iter, - [:fcall, :d], - [:dasgn_curr, :x], - [:dasgn, :c, [:true]]], - [:dvar, :c]]]], - "ParseTree" => s(:iter, - s(:call, nil, :a, - s(:arglist, s(:call, nil, :b, s(:arglist)))), - nil, - s(:if, - s(:call, nil, :b, s(:arglist)), - s(:true), - s(:block, - s(:lasgn, :c, s(:false)), - s(:iter, - s(:call, nil, :d, s(:arglist)), - s(:lasgn, :x), - s(:lasgn, :c, s(:true))), - s(:lvar, :c))))) - - add_tests("block_pass_args_and_splat", - "Ruby" => "def blah(*args, &block)\n other(42, *args, &block)\nend", - "RawParseTree" => [:defn, :blah, - [:scope, - [:block, - [:args, :"*args"], - [:block_arg, :block], - [:block_pass, - [:lvar, :block], - [:fcall, :other, - [:argscat, - [:array, [:lit, 42]], [:lvar, :args]]]]]]], - "ParseTree" => s(:defn, :blah, - s(:args, :"*args", :"&block"), - s(:scope, - s(:block, - s(:call, nil, :other, - s(:arglist, - s(:lit, 42), - s(:splat, s(:lvar, :args)), - s(:block_pass, s(:lvar, :block)))))))) - - add_tests("block_pass_call_0", - "Ruby" => "a.b(&c)", - "RawParseTree" => [:block_pass, - [:vcall, :c], [:call, [:vcall, :a], :b]], - "ParseTree" => s(:call, - s(:call, nil, :a, s(:arglist)), - :b, - s(:arglist, - s(:block_pass, - s(:call, nil, :c, s(:arglist)))))) - - add_tests("block_pass_call_1", - "Ruby" => "a.b(4, &c)", - "RawParseTree" => [:block_pass, - [:vcall, :c], - [:call, [:vcall, :a], :b, [:array, [:lit, 4]]]], - "ParseTree" => s(:call, - s(:call, nil, :a, s(:arglist)), - :b, - s(:arglist, - s(:lit, 4), - s(:block_pass, - s(:call, nil, :c, s(:arglist)))))) - - add_tests("block_pass_call_n", - "Ruby" => "a.b(1, 2, 3, &c)", - "RawParseTree" => [:block_pass, - [:vcall, :c], - [:call, [:vcall, :a], :b, - [:array, [:lit, 1], [:lit, 2], [:lit, 3]]]], - "ParseTree" => s(:call, - s(:call, nil, :a, s(:arglist)), - :b, - s(:arglist, - s(:lit, 1), s(:lit, 2), s(:lit, 3), - s(:block_pass, - s(:call, nil, :c, s(:arglist)))))) - - add_tests("block_pass_fcall_0", - "Ruby" => "a(&b)", - "RawParseTree" => [:block_pass, [:vcall, :b], [:fcall, :a]], - "ParseTree" => s(:call, nil, :a, - s(:arglist, - s(:block_pass, - s(:call, nil, :b, s(:arglist)))))) - - add_tests("block_pass_fcall_1", - "Ruby" => "a(4, &b)", - "RawParseTree" => [:block_pass, - [:vcall, :b], - [:fcall, :a, [:array, [:lit, 4]]]], - "ParseTree" => s(:call, nil, :a, - s(:arglist, - s(:lit, 4), - s(:block_pass, - s(:call, nil, :b, s(:arglist)))))) - - add_tests("block_pass_fcall_n", - "Ruby" => "a(1, 2, 3, &b)", - "RawParseTree" => [:block_pass, - [:vcall, :b], - [:fcall, :a, - [:array, [:lit, 1], [:lit, 2], [:lit, 3]]]], - "ParseTree" => s(:call, nil, :a, - s(:arglist, - s(:lit, 1), s(:lit, 2), s(:lit, 3), - s(:block_pass, - s(:call, nil, :b, s(:arglist)))))) - - add_tests("block_pass_omgwtf", - "Ruby" => "define_attr_method(:x, :sequence_name, &Proc.new { |*args| nil })", - "RawParseTree" => [:block_pass, - [:iter, - [:call, [:const, :Proc], :new], - [:masgn, nil, [:dasgn_curr, :args], nil], - [:nil]], - [:fcall, :define_attr_method, - [:array, [:lit, :x], [:lit, :sequence_name]]]], - "ParseTree" => s(:call, nil, :define_attr_method, - s(:arglist, - s(:lit, :x), - s(:lit, :sequence_name), - s(:block_pass, - s(:iter, - s(:call, s(:const, :Proc), :new, - s(:arglist)), - s(:masgn, - s(:array, s(:splat, s(:lasgn, :args)))), - s(:nil)))))) - - add_tests("block_pass_splat", - "Ruby" => "def blah(*args, &block)\n other(*args, &block)\nend", - "RawParseTree" => [:defn, :blah, - [:scope, - [:block, - [:args, :"*args"], - [:block_arg, :block], - [:block_pass, - [:lvar, :block], - [:fcall, :other, - [:splat, [:lvar, :args]]]]]]], - "ParseTree" => s(:defn, :blah, - s(:args, :"*args", :"&block"), - s(:scope, - s(:block, - s(:call, nil, :other, - s(:arglist, - s(:splat, s(:lvar, :args)), - s(:block_pass, s(:lvar, :block)))))))) - - add_tests("block_pass_thingy", - "Ruby" => "r.read_body(dest, &block)", - "RawParseTree" => [:block_pass, - [:vcall, :block], - [:call, [:vcall, :r], :read_body, - [:array, [:vcall, :dest]]]], - "ParseTree" => s(:call, - s(:call, nil, :r, s(:arglist)), - :read_body, - s(:arglist, - s(:call, nil, :dest, s(:arglist)), - s(:block_pass, - s(:call, nil, :block, s(:arglist)))))) - - add_tests("block_stmt_after", - "Ruby" => "def f\n begin\n b\n rescue\n c\n end\n\n d\nend", - "RawParseTree" => [:defn, :f, - [:scope, - [:block, - [:args], - [:rescue, - [:vcall, :b], - [:resbody, nil, [:vcall, :c]]], - [:vcall, :d]]]], - "ParseTree" => s(:defn, :f, - s(:args), - s(:scope, - s(:block, - s(:rescue, - s(:call, nil, :b, s(:arglist)), - s(:resbody, - s(:array), - s(:call, nil, :c, s(:arglist)))), - s(:call, nil, :d, s(:arglist))))), - "Ruby2Ruby" => "def f\n b rescue c\n d\nend") - - add_tests("block_stmt_after_mri_verbose_flag", - "RawParseTree" => [:defn, :f, - [:scope, - [:block, - [:args], - [:rescue, # no begin - [:vcall, :b], - [:resbody, nil, [:vcall, :c]]], - [:vcall, :d]]]]) - - copy_test_case "block_stmt_after", "Ruby" - copy_test_case "block_stmt_after", "ParseTree" - copy_test_case "block_stmt_after", "Ruby2Ruby" - - add_tests("block_stmt_before", - "Ruby" => "def f\n a\n begin\n b\n rescue\n c\n end\nend", - "RawParseTree" => [:defn, :f, - [:scope, - [:block, - [:args], - [:vcall, :a], - [:rescue, [:vcall, :b], - [:resbody, nil, [:vcall, :c]]]]]], - "ParseTree" => s(:defn, :f, - s(:args), - s(:scope, - s(:block, - s(:call, nil, :a, s(:arglist)), - s(:rescue, s(:call, nil, :b, s(:arglist)), - s(:resbody, - s(:array), - s(:call, nil, :c, s(:arglist))))))), - "Ruby2Ruby" => "def f\n a\n b rescue c\nend") - - # oddly... this one doesn't HAVE any differences when verbose... new? - copy_test_case "block_stmt_before", "Ruby" - copy_test_case "block_stmt_before", "ParseTree" - copy_test_case "block_stmt_before", "RawParseTree" - copy_test_case "block_stmt_before", "Ruby2Ruby" - - add_tests("block_stmt_both", - "Ruby" => "def f\n a\n begin\n b\n rescue\n c\n end\n d\nend", - "RawParseTree" => [:defn, :f, - [:scope, - [:block, - [:args], - [:vcall, :a], - [:rescue, - [:vcall, :b], - [:resbody, - nil, - [:vcall, :c]]], - [:vcall, :d]]]], - "ParseTree" => s(:defn, :f, s(:args), - s(:scope, - s(:block, - s(:call, nil, :a, s(:arglist)), - s(:rescue, - s(:call, nil, :b, s(:arglist)), - s(:resbody, - s(:array), - s(:call, nil, :c, s(:arglist)))), - s(:call, nil, :d, s(:arglist))))), - "Ruby2Ruby" => "def f\n a\n b rescue c\n d\nend") - - add_tests("block_stmt_both_mri_verbose_flag", - "RawParseTree" => [:defn, :f, - [:scope, - [:block, - [:args], - [:vcall, :a], - [:rescue, # no begin - [:vcall, :b], - [:resbody, - nil, - [:vcall, :c]]], - [:vcall, :d]]]]) - - copy_test_case "block_stmt_both", "Ruby" - copy_test_case "block_stmt_both", "ParseTree" - copy_test_case "block_stmt_both", "Ruby2Ruby" - - add_tests("bmethod", - "Ruby" => [Examples, :unsplatted], - "RawParseTree" => [:defn, :unsplatted, - [:bmethod, - [:dasgn_curr, :x], - [:call, [:dvar, :x], :+, [:array, [:lit, 1]]]]], - "ParseTree" => s(:defn, :unsplatted, - s(:args, :x), - s(:scope, - s(:block, - s(:call, - s(:lvar, :x), - :+, - s(:arglist, s(:lit, 1)))))), - "Ruby2Ruby" => "def unsplatted(x)\n (x + 1)\nend") - - add_tests("bmethod_noargs", - "Ruby" => [Examples, :bmethod_noargs], - "RawParseTree" => [:defn, :bmethod_noargs, - [:bmethod, - nil, - [:call, - [:vcall, :x], :"+", [:array, [:lit, 1]]]]], - "ParseTree" => s(:defn, :bmethod_noargs, - s(:args), - s(:scope, - s(:block, - s(:call, - s(:call, nil, :x, s(:arglist)), - :"+", - s(:arglist, s(:lit, 1)))))), - "Ruby2Ruby" => "def bmethod_noargs\n (x + 1)\nend") - - add_tests("bmethod_splat", - "Ruby" => [Examples, :splatted], - "RawParseTree" => [:defn, :splatted, - [:bmethod, - [:masgn, nil, [:dasgn_curr, :args], nil], - [:block, - [:dasgn_curr, :y, - [:call, [:dvar, :args], :first]], - [:call, [:dvar, :y], :+, - [:array, [:lit, 42]]]]]], - "ParseTree" => s(:defn, :splatted, - s(:args, :"*args"), - s(:scope, - s(:block, - s(:lasgn, :y, - s(:call, s(:lvar, :args), :first, - s(:arglist))), - s(:call, s(:lvar, :y), :+, - s(:arglist, s(:lit, 42)))))), - "Ruby2Ruby" => "def splatted(*args)\n y = args.first\n (y + 42)\nend") - - add_tests("break", - "Ruby" => "loop { break if true }", - "RawParseTree" => [:iter, - [:fcall, :loop], nil, - [:if, [:true], [:break], nil]], - "ParseTree" => s(:iter, - s(:call, nil, :loop, s(:arglist)), nil, - s(:if, s(:true), s(:break), nil))) - - add_tests("break_arg", - "Ruby" => "loop { break 42 if true }", - "RawParseTree" => [:iter, - [:fcall, :loop], nil, - [:if, [:true], [:break, [:lit, 42]], nil]], - "ParseTree" => s(:iter, - s(:call, nil, :loop, s(:arglist)), nil, - s(:if, s(:true), s(:break, s(:lit, 42)), nil))) - - add_tests("call", - "Ruby" => "self.method", - "RawParseTree" => [:call, [:self], :method], - "ParseTree" => s(:call, s(:self), :method, s(:arglist))) - - add_tests("call_arglist", - "Ruby" => "o.puts(42)", - "RawParseTree" => [:call, [:vcall, :o], :puts, - [:array, [:lit, 42]]], - "ParseTree" => s(:call, s(:call, nil, :o, s(:arglist)), :puts, - s(:arglist, s(:lit, 42)))) - - add_tests("call_arglist_hash", - "Ruby" => "o.m(:a => 1, :b => 2)", - "RawParseTree" => [:call, - [:vcall, :o], :m, - [:array, - [:hash, - [:lit, :a], [:lit, 1], - [:lit, :b], [:lit, 2]]]], - "ParseTree" => s(:call, - s(:call, nil, :o, s(:arglist)), :m, - s(:arglist, - s(:hash, - s(:lit, :a), s(:lit, 1), - s(:lit, :b), s(:lit, 2))))) - - add_tests("call_arglist_norm_hash", - "Ruby" => "o.m(42, :a => 1, :b => 2)", - "RawParseTree" => [:call, - [:vcall, :o], :m, - [:array, - [:lit, 42], - [:hash, - [:lit, :a], [:lit, 1], - [:lit, :b], [:lit, 2]]]], - "ParseTree" => s(:call, - s(:call, nil, :o, s(:arglist)), :m, - s(:arglist, - s(:lit, 42), - s(:hash, - s(:lit, :a), s(:lit, 1), - s(:lit, :b), s(:lit, 2))))) - - add_tests("call_arglist_norm_hash_splat", - "Ruby" => "o.m(42, :a => 1, :b => 2, *c)", - "RawParseTree" => [:call, - [:vcall, :o], :m, - [:argscat, - [:array, - [:lit, 42], - [:hash, - [:lit, :a], [:lit, 1], - [:lit, :b], [:lit, 2]]], - [:vcall, :c]]], - "ParseTree" => s(:call, - s(:call, nil, :o, s(:arglist)), :m, - s(:arglist, - s(:lit, 42), - s(:hash, - s(:lit, :a), s(:lit, 1), - s(:lit, :b), s(:lit, 2)), - s(:splat, s(:call, nil, :c, s(:arglist)))))) - - add_tests("call_arglist_space", - "Ruby" => "a (1,2,3)", - "RawParseTree" => [:fcall, :a, - [:array, [:lit, 1], [:lit, 2], [:lit, 3]]], - "ParseTree" => s(:call, nil, :a, - s(:arglist, - s(:lit, 1), s(:lit, 2), s(:lit, 3))), - "Ruby2Ruby" => "a(1, 2, 3)") - - add_tests("call_command", - "Ruby" => "1.b(c)", - "RawParseTree" => [:call, [:lit, 1], :b, [:array, [:vcall, :c]]], - "ParseTree" => s(:call, - s(:lit, 1), - :b, - s(:arglist, s(:call, nil, :c, s(:arglist))))) - - add_tests("call_expr", - "Ruby" => "(v = (1 + 1)).zero?", - "RawParseTree" => [:call, - [:lasgn, :v, - [:call, [:lit, 1], :+, [:array, [:lit, 1]]]], - :zero?], - "ParseTree" => s(:call, - s(:lasgn, :v, - s(:call, s(:lit, 1), :+, - s(:arglist, s(:lit, 1)))), - :zero?, s(:arglist))) - - add_tests("call_index", - "Ruby" => "a = []\na[42]\n", - "RawParseTree" => [:block, - [:lasgn, :a, [:zarray]], - [:call, [:lvar, :a], :[], [:array, [:lit, 42]]]], - "ParseTree" => s(:block, - s(:lasgn, :a, s(:array)), - s(:call, s(:lvar, :a), :[], - s(:arglist, s(:lit, 42))))) - - add_tests("call_index_no_args", - "Ruby" => "a[]", - "RawParseTree" => [:call, [:vcall, :a], :[]], - "ParseTree" => s(:call, s(:call, nil, :a, s(:arglist)), - :[], s(:arglist))) - - add_tests("call_index_space", - "Ruby" => "a = []\na [42]\n", - "RawParseTree" => [:block, - [:lasgn, :a, [:zarray]], - [:call, [:lvar, :a], :[], [:array, [:lit, 42]]]], - "ParseTree" => s(:block, - s(:lasgn, :a, s(:array)), - s(:call, s(:lvar, :a), :[], - s(:arglist, s(:lit, 42)))), - "Ruby2Ruby" => "a = []\na[42]\n") - - add_tests("call_unary_neg", - "Ruby" => "-2**31", - "RawParseTree" => [:call, - [:call, [:lit, 2], :**, [:array, [:lit, 31]]], - :-@], - "ParseTree" => s(:call, - s(:call, - s(:lit, 2), - :**, - s(:arglist, s(:lit, 31))), - :-@, s(:arglist)), - "Ruby2Ruby" => "-(2 ** 31)") - - add_tests("case", - "Ruby" => "var = 2\nresult = \"\"\ncase var\nwhen 1 then\n puts(\"something\")\n result = \"red\"\nwhen 2, 3 then\n result = \"yellow\"\nwhen 4 then\n # do nothing\nelse\n result = \"green\"\nend\ncase result\nwhen \"red\" then\n var = 1\nwhen \"yellow\" then\n var = 2\nwhen \"green\" then\n var = 3\nelse\n # do nothing\nend\n", - "RawParseTree" => [:block, - [:lasgn, :var, [:lit, 2]], - [:lasgn, :result, [:str, ""]], - [:case, - [:lvar, :var], - [:when, - [:array, [:lit, 1]], - [:block, - [:fcall, :puts, - [:array, [:str, "something"]]], - [:lasgn, :result, [:str, "red"]]]], - [:when, - [:array, [:lit, 2], [:lit, 3]], - [:lasgn, :result, [:str, "yellow"]]], - [:when, [:array, [:lit, 4]], nil], - [:lasgn, :result, [:str, "green"]]], - [:case, - [:lvar, :result], - [:when, [:array, [:str, "red"]], - [:lasgn, :var, [:lit, 1]]], - [:when, [:array, [:str, "yellow"]], - [:lasgn, :var, [:lit, 2]]], - [:when, [:array, [:str, "green"]], - [:lasgn, :var, [:lit, 3]]], - nil]], - "ParseTree" => s(:block, - s(:lasgn, :var, s(:lit, 2)), - s(:lasgn, :result, s(:str, "")), - s(:case, - s(:lvar, :var), - s(:when, - s(:array, s(:lit, 1)), - s(:block, - s(:call, nil, :puts, - s(:arglist, s(:str, "something"))), - s(:lasgn, :result, s(:str, "red")))), - s(:when, - s(:array, s(:lit, 2), s(:lit, 3)), - s(:lasgn, :result, s(:str, "yellow"))), - s(:when, s(:array, s(:lit, 4)), nil), - s(:lasgn, :result, s(:str, "green"))), - s(:case, - s(:lvar, :result), - s(:when, s(:array, s(:str, "red")), - s(:lasgn, :var, s(:lit, 1))), - s(:when, s(:array, s(:str, "yellow")), - s(:lasgn, :var, s(:lit, 2))), - s(:when, s(:array, s(:str, "green")), - s(:lasgn, :var, s(:lit, 3))), - nil))) - - add_tests("case_nested", - "Ruby" => "var1 = 1\nvar2 = 2\nresult = nil\ncase var1\nwhen 1 then\n case var2\n when 1 then\n result = 1\n when 2 then\n result = 2\n else\n result = 3\n end\nwhen 2 then\n case var2\n when 1 then\n result = 4\n when 2 then\n result = 5\n else\n result = 6\n end\nelse\n result = 7\nend\n", - "RawParseTree" => [:block, - [:lasgn, :var1, [:lit, 1]], - [:lasgn, :var2, [:lit, 2]], - [:lasgn, :result, [:nil]], - [:case, - [:lvar, :var1], - [:when, [:array, [:lit, 1]], - [:case, - [:lvar, :var2], - [:when, [:array, [:lit, 1]], - [:lasgn, :result, [:lit, 1]]], - [:when, [:array, [:lit, 2]], - [:lasgn, :result, [:lit, 2]]], - [:lasgn, :result, [:lit, 3]]]], - [:when, [:array, [:lit, 2]], - [:case, - [:lvar, :var2], - [:when, [:array, [:lit, 1]], - [:lasgn, :result, [:lit, 4]]], - [:when, [:array, [:lit, 2]], - [:lasgn, :result, [:lit, 5]]], - [:lasgn, :result, [:lit, 6]]]], - [:lasgn, :result, [:lit, 7]]]], - "ParseTree" => s(:block, - s(:lasgn, :var1, s(:lit, 1)), - s(:lasgn, :var2, s(:lit, 2)), - s(:lasgn, :result, s(:nil)), - s(:case, - s(:lvar, :var1), - s(:when, s(:array, s(:lit, 1)), - s(:case, - s(:lvar, :var2), - s(:when, s(:array, s(:lit, 1)), - s(:lasgn, :result, s(:lit, 1))), - s(:when, s(:array, s(:lit, 2)), - s(:lasgn, :result, s(:lit, 2))), - s(:lasgn, :result, s(:lit, 3)))), - s(:when, s(:array, s(:lit, 2)), - s(:case, - s(:lvar, :var2), - s(:when, s(:array, s(:lit, 1)), - s(:lasgn, :result, s(:lit, 4))), - s(:when, s(:array, s(:lit, 2)), - s(:lasgn, :result, s(:lit, 5))), - s(:lasgn, :result, s(:lit, 6)))), - s(:lasgn, :result, s(:lit, 7))))) - - add_tests("case_nested_inner_no_expr", - "Ruby" => "case a\nwhen b then\n case\n when (d and e) then\n f\n else\n # do nothing\n end\nelse\n # do nothing\nend", - "RawParseTree" => [:case, [:vcall, :a], - [:when, [:array, [:vcall, :b]], - [:case, nil, - [:when, - [:array, [:and, [:vcall, :d], [:vcall, :e]]], - [:vcall, :f]], - nil]], - nil], - "ParseTree" => s(:case, s(:call, nil, :a, s(:arglist)), - s(:when, - s(:array, s(:call, nil, :b, s(:arglist))), - s(:case, nil, - s(:when, - s(:array, - s(:and, - s(:call, nil, :d, s(:arglist)), - s(:call, nil, :e, s(:arglist)))), - s(:call, nil, :f, s(:arglist))), - nil)), - nil)) - - add_tests("case_no_expr", - "Ruby" => "case\nwhen (a == 1) then\n :a\nwhen (a == 2) then\n :b\nelse\n :c\nend", - "RawParseTree" => [:case, nil, - [:when, - [:array, - [:call, [:vcall, :a], :==, - [:array, [:lit, 1]]]], - [:lit, :a]], - [:when, - [:array, - [:call, [:vcall, :a], :==, - [:array, [:lit, 2]]]], - [:lit, :b]], - [:lit, :c]], - "ParseTree" => s(:case, nil, - s(:when, - s(:array, - s(:call, - s(:call, nil, :a, s(:arglist)), - :==, - s(:arglist, s(:lit, 1)))), - s(:lit, :a)), - s(:when, - s(:array, - s(:call, - s(:call, nil, :a, s(:arglist)), - :==, - s(:arglist, s(:lit, 2)))), - s(:lit, :b)), - s(:lit, :c))) - - add_tests("case_splat", - "Ruby" => "case a\nwhen :b, *c then\n d\nelse\n e\nend", - "RawParseTree" => [:case, [:vcall, :a], - [:when, - [:array, - [:lit, :b], [:when, [:vcall, :c], nil]], # wtf? - [:vcall, :d]], - [:vcall, :e]], - "ParseTree" => s(:case, s(:call, nil, :a, s(:arglist)), - s(:when, - s(:array, - s(:lit, :b), - s(:when, - s(:call, nil, :c, s(:arglist)), - nil)), # wtf? - s(:call, nil, :d, s(:arglist))), - s(:call, nil, :e, s(:arglist)))) - - add_tests("cdecl", - "Ruby" => "X = 42", - "RawParseTree" => [:cdecl, :X, [:lit, 42]], - "ParseTree" => s(:cdecl, :X, s(:lit, 42))) - - add_tests("class_plain", - "Ruby" => "class X\n puts((1 + 1))\n def blah\n puts(\"hello\")\n end\nend", - "RawParseTree" => [:class, - :X, - nil, - [:scope, - [:block, - [:fcall, :puts, - [:array, - [:call, [:lit, 1], :+, - [:array, [:lit, 1]]]]], - [:defn, :blah, - [:scope, - [:block, - [:args], - [:fcall, :puts, - [:array, [:str, "hello"]]]]]]]]], - "ParseTree" => s(:class, - :X, - nil, - s(:scope, - s(:block, - s(:call, nil, :puts, - s(:arglist, - s(:call, s(:lit, 1), :+, - s(:arglist, s(:lit, 1))))), - s(:defn, :blah, - s(:args), - s(:scope, - s(:block, - s(:call, nil, :puts, - s(:arglist, - s(:str, "hello")))))))))) - - add_tests("class_scoped", - "Ruby" => "class X::Y\n c\nend", - "RawParseTree" => [:class, [:colon2, [:const, :X], :Y], nil, - [:scope, [:vcall, :c]]], - "ParseTree" => s(:class, s(:colon2, s(:const, :X), :Y), nil, - s(:scope, s(:call, nil, :c, s(:arglist))))) - - add_tests("class_scoped3", - "Ruby" => "class ::Y\n c\nend", - "RawParseTree" => [:class, [:colon3, :Y], nil, - [:scope, [:vcall, :c]]], - "ParseTree" => s(:class, s(:colon3, :Y), nil, - s(:scope, s(:call, nil, :c, s(:arglist))))) - - add_tests("class_super_array", - "Ruby" => "class X < Array\nend", - "RawParseTree" => [:class, - :X, - [:const, :Array], - [:scope]], - "ParseTree" => s(:class, - :X, - s(:const, :Array), - s(:scope))) - - add_tests("class_super_expr", - "Ruby" => "class X < expr\nend", - "RawParseTree" => [:class, - :X, - [:vcall, :expr], - [:scope]], - "ParseTree" => s(:class, - :X, - s(:call, nil, :expr, s(:arglist)), - s(:scope))) - - add_tests("class_super_object", - "Ruby" => "class X < Object\nend", - "RawParseTree" => [:class, - :X, - [:const, :Object], - [:scope]], - "ParseTree" => s(:class, - :X, - s(:const, :Object), - s(:scope))) - - add_tests("colon2", - "Ruby" => "X::Y", - "RawParseTree" => [:colon2, [:const, :X], :Y], - "ParseTree" => s(:colon2, s(:const, :X), :Y)) - - add_tests("colon3", - "Ruby" => "::X", - "RawParseTree" => [:colon3, :X], - "ParseTree" => s(:colon3, :X)) - - add_tests("const", - "Ruby" => "X", - "RawParseTree" => [:const, :X], - "ParseTree" => s(:const, :X)) - - add_tests("constX", - "Ruby" => "X = 1", - "RawParseTree" => [:cdecl, :X, [:lit, 1]], - "ParseTree" => s(:cdecl, :X, s(:lit, 1))) - - add_tests("constY", - "Ruby" => "::X = 1", - "RawParseTree" => [:cdecl, [:colon3, :X], [:lit, 1]], - "ParseTree" => s(:cdecl, s(:colon3, :X), s(:lit, 1))) - - add_tests("constZ", - "Ruby" => "X::Y = 1", - "RawParseTree" => [:cdecl, [:colon2, [:const, :X], :Y], [:lit, 1]], - "ParseTree" => s(:cdecl, - s(:colon2, s(:const, :X), :Y), - s(:lit, 1))) - - add_tests("cvar", - "Ruby" => "@@x", - "RawParseTree" => [:cvar, :@@x], - "ParseTree" => s(:cvar, :@@x)) - - add_tests("cvasgn", - "Ruby" => "def x\n @@blah = 1\nend", - "RawParseTree" => [:defn, :x, - [:scope, - [:block, [:args], - [:cvasgn, :@@blah, [:lit, 1]]]]], - "ParseTree" => s(:defn, :x, - s(:args), - s(:scope, - s(:block, - s(:cvasgn, :@@blah, s(:lit, 1)))))) - - add_tests("cvasgn_cls_method", - "Ruby" => "def self.quiet_mode=(boolean)\n @@quiet_mode = boolean\nend", - "RawParseTree" => [:defs, [:self], :quiet_mode=, - [:scope, - [:block, - [:args, :boolean], - [:cvasgn, :@@quiet_mode, [:lvar, :boolean]]]]], - "ParseTree" => s(:defs, s(:self), :quiet_mode=, - s(:args, :boolean), - s(:scope, - s(:block, - s(:cvasgn, :@@quiet_mode, - s(:lvar, :boolean)))))) - - add_tests("cvdecl", - "Ruby" => "class X\n @@blah = 1\nend", - "RawParseTree" => [:class, :X, nil, - [:scope, [:cvdecl, :@@blah, [:lit, 1]]]], - "ParseTree" => s(:class, :X, nil, - s(:scope, s(:cvdecl, :@@blah, s(:lit, 1))))) - - add_tests("dasgn_0", - "Ruby" => "a.each { |x| b.each { |y| x = (x + 1) } if true }", - "RawParseTree" => [:iter, - [:call, [:vcall, :a], :each], - [:dasgn_curr, :x], - [:if, [:true], - [:iter, - [:call, [:vcall, :b], :each], - [:dasgn_curr, :y], - [:dasgn, :x, - [:call, [:dvar, :x], :+, - [:array, [:lit, 1]]]]], - nil]], - "ParseTree" => s(:iter, - s(:call, s(:call, nil, :a, s(:arglist)), :each, - s(:arglist)), - s(:lasgn, :x), - s(:if, s(:true), - s(:iter, - s(:call, s(:call, nil, :b, s(:arglist)), - :each, - s(:arglist)), - s(:lasgn, :y), - s(:lasgn, :x, - s(:call, s(:lvar, :x), :+, - s(:arglist, s(:lit, 1))))), - nil))) - - add_tests("dasgn_1", - "Ruby" => "a.each { |x| b.each { |y| c = (c + 1) } if true }", - "RawParseTree" => [:iter, - [:call, [:vcall, :a], :each], - [:dasgn_curr, :x], - [:if, [:true], - [:iter, - [:call, [:vcall, :b], :each], - [:dasgn_curr, :y], - [:dasgn_curr, :c, - [:call, [:dvar, :c], :+, - [:array, [:lit, 1]]]]], - nil]], - "ParseTree" => s(:iter, - s(:call, s(:call, nil, :a, s(:arglist)), :each, - s(:arglist)), - s(:lasgn, :x), - s(:if, s(:true), - s(:iter, - s(:call, s(:call, nil, :b, s(:arglist)), - :each, - s(:arglist)), - s(:lasgn, :y), - s(:lasgn, :c, - s(:call, s(:lvar, :c), :+, - s(:arglist, s(:lit, 1))))), - nil))) - - add_tests("dasgn_2", - "Ruby" => "a.each do |x|\n if true then\n c = 0\n b.each { |y| c = (c + 1) }\n end\nend", # FIX: hate that extra newline! - "RawParseTree" => [:iter, - [:call, [:vcall, :a], :each], - [:dasgn_curr, :x], - [:if, [:true], - [:block, - [:dasgn_curr, :c, [:lit, 0]], - [:iter, - [:call, [:vcall, :b], :each], - [:dasgn_curr, :y], - [:dasgn, :c, - [:call, [:dvar, :c], :+, - [:array, [:lit, 1]]]]]], - nil]], - "ParseTree" => s(:iter, - s(:call, s(:call, nil, :a, s(:arglist)), :each, - s(:arglist)), - s(:lasgn, :x), - s(:if, s(:true), - s(:block, - s(:lasgn, :c, s(:lit, 0)), - s(:iter, - s(:call, s(:call, nil, :b, s(:arglist)), - :each, - s(:arglist)), - s(:lasgn, :y), - s(:lasgn, :c, - s(:call, s(:lvar, :c), :+, - s(:arglist, s(:lit, 1)))))), - nil))) - - add_tests("dasgn_curr", - "Ruby" => "data.each do |x, y|\n a = 1\n b = a\n b = a = x\nend", - "RawParseTree" => [:iter, - [:call, [:vcall, :data], :each], - [:masgn, - [:array, [:dasgn_curr, :x], [:dasgn_curr, :y]], - nil, nil], - [:block, - [:dasgn_curr, :a, [:lit, 1]], - [:dasgn_curr, :b, [:dvar, :a]], - [:dasgn_curr, :b, - [:dasgn_curr, :a, [:dvar, :x]]]]], - "ParseTree" => s(:iter, - s(:call, s(:call, nil, :data, - s(:arglist)), :each, s(:arglist)), - s(:masgn, - s(:array, s(:lasgn, :x), s(:lasgn, :y))), - s(:block, - s(:lasgn, :a, s(:lit, 1)), - s(:lasgn, :b, s(:lvar, :a)), - s(:lasgn, :b, s(:lasgn, :a, s(:lvar, :x)))))) - - add_tests("dasgn_icky", - "Ruby" => "a do\n v = nil\n assert_block(full_message) do\n begin\n yield\n rescue Exception => v\n break\n end\n end\nend", - "RawParseTree" => [:iter, - [:fcall, :a], - nil, - [:block, - [:dasgn_curr, :v, [:nil]], - [:iter, - [:fcall, :assert_block, - [:array, [:vcall, :full_message]]], - nil, - [:rescue, - [:yield], - [:resbody, - [:array, [:const, :Exception]], - [:block, - [:dasgn, :v, - [:gvar, :$!]], [:break]]]]]]], - "ParseTree" => s(:iter, - s(:call, nil, :a, s(:arglist)), - nil, - s(:block, - s(:lasgn, :v, s(:nil)), - s(:iter, - s(:call, nil, :assert_block, - s(:arglist, - s(:call, nil, :full_message, - s(:arglist)))), - nil, - s(:rescue, - s(:yield), - s(:resbody, - s(:array, - s(:const, :Exception), - s(:lasgn, :v, s(:gvar, :$!))), - s(:break))))))) - - add_tests("dasgn_mixed", - "Ruby" => "t = 0\nns.each { |n| t += n }\n", - "RawParseTree" => [:block, - [:lasgn, :t, [:lit, 0]], - [:iter, - [:call, [:vcall, :ns], :each], - [:dasgn_curr, :n], - [:lasgn, :t, - [:call, [:lvar, :t], :+, - [:array, [:dvar, :n]]]]]], - "ParseTree" => s(:block, - s(:lasgn, :t, s(:lit, 0)), - s(:iter, - s(:call, s(:call, nil, :ns, - s(:arglist)), :each, s(:arglist)), - s(:lasgn, :n), - s(:lasgn, :t, - s(:call, s(:lvar, :t), :+, - s(:arglist, s(:lvar, :n)))))), - "Ruby2Ruby" => "t = 0\nns.each { |n| t = (t + n) }\n") - - add_tests("defined", - "Ruby" => "defined? $x", - "RawParseTree" => [:defined, [:gvar, :$x]], - "ParseTree" => s(:defined, s(:gvar, :$x))) - - # TODO: make all the defn_args* p their arglist - add_tests("defn_args_block", - "Ruby" => "def f(&block)\n # do nothing\nend", - "RawParseTree" => [:defn, :f, - [:scope, - [:block, - [:args], - [:block_arg, :block], - [:nil]]]], - "ParseTree" => s(:defn, :f, - s(:args, :"&block"), - s(:scope, s(:block, s(:nil))))) - - add_tests("defn_args_mand", - "Ruby" => "def f(mand)\n # do nothing\nend", - "RawParseTree" => [:defn, :f, - [:scope, - [:block, - [:args, :mand], - [:nil]]]], - "ParseTree" => s(:defn, :f, - s(:args, :mand), - s(:scope, s(:block, s(:nil))))) - - add_tests("defn_args_mand_block", - "Ruby" => "def f(mand, &block)\n # do nothing\nend", - "RawParseTree" => [:defn, :f, - [:scope, - [:block, - [:args, :mand], - [:block_arg, :block], - [:nil]]]], - "ParseTree" => s(:defn, :f, - s(:args, :mand, :"&block"), - s(:scope, s(:block, s(:nil))))) - - add_tests("defn_args_mand_opt", - "Ruby" => "def f(mand, opt = 42)\n # do nothing\nend", - "RawParseTree" => [:defn, :f, - [:scope, - [:block, - [:args, :mand, :opt, - [:block, - [:lasgn, :opt, [:lit, 42]]]], - [:nil]]]], - "ParseTree" => s(:defn, :f, - s(:args, :mand, :opt, - s(:block, - s(:lasgn, :opt, s(:lit, 42)))), - s(:scope, s(:block, s(:nil))))) - - add_tests("defn_args_mand_opt_block", - "Ruby" => "def f(mand, opt = 42, &block)\n # do nothing\nend", - "RawParseTree" => [:defn, :f, - [:scope, - [:block, - [:args, :mand, :opt, - [:block, - [:lasgn, :opt, [:lit, 42]]]], - [:block_arg, :block], - [:nil]]]], - "ParseTree" => s(:defn, :f, - s(:args, :mand, :opt, :"&block", - s(:block, - s(:lasgn, :opt, s(:lit, 42)))), - s(:scope, s(:block, s(:nil))))) - - add_tests("defn_args_mand_opt_splat", - "Ruby" => "def f(mand, opt = 42, *rest)\n # do nothing\nend", - "RawParseTree" => [:defn, :f, - [:scope, - [:block, - [:args, :mand, :opt, :"*rest", - [:block, - [:lasgn, :opt, [:lit, 42]]]], - [:nil]]]], - "ParseTree" => s(:defn, :f, - s(:args, :mand, :opt, :"*rest", - s(:block, - s(:lasgn, :opt, s(:lit, 42)))), - s(:scope, s(:block, s(:nil))))) - - add_tests("defn_args_mand_opt_splat_block", - "Ruby" => "def f(mand, opt = 42, *rest, &block)\n # do nothing\nend", - "RawParseTree" => [:defn, :f, - [:scope, - [:block, - [:args, :mand, :opt, :"*rest", - [:block, - [:lasgn, :opt, [:lit, 42]]]], - [:block_arg, :block], - [:nil]]]], - "ParseTree" => s(:defn, :f, - s(:args, :mand, :opt, :"*rest", :"&block", - s(:block, - s(:lasgn, :opt, s(:lit, 42)))), - s(:scope, s(:block, s(:nil))))) - - add_tests("defn_args_mand_opt_splat_no_name", - "Ruby" => "def x(a, b = 42, *)\n # do nothing\nend", - "RawParseTree" => [:defn, :x, - [:scope, - [:block, - [:args, :a, :b, :"*", - [:block, [:lasgn, :b, [:lit, 42]]]], - [:nil]]]], - "ParseTree" => s(:defn, :x, - s(:args, :a, :b, :"*", - s(:block, s(:lasgn, :b, s(:lit, 42)))), - s(:scope, - s(:block, - s(:nil))))) - - add_tests("defn_args_mand_splat", - "Ruby" => "def f(mand, *rest)\n # do nothing\nend", - "RawParseTree" => [:defn, :f, - [:scope, - [:block, - [:args, :mand, :"*rest"], - [:nil]]]], - "ParseTree" => s(:defn, :f, - s(:args, :mand, :"*rest"), - s(:scope, s(:block, s(:nil))))) - - add_tests("defn_args_mand_splat_block", - "Ruby" => "def f(mand, *rest, &block)\n # do nothing\nend", - "RawParseTree" => [:defn, :f, - [:scope, - [:block, - [:args, :mand, :"*rest"], - [:block_arg, :block], - [:nil]]]], - "ParseTree" => s(:defn, :f, - s(:args, :mand, :"*rest", :"&block"), - s(:scope, s(:block, s(:nil))))) - - add_tests("defn_args_mand_splat_no_name", - "Ruby" => "def x(a, *args)\n p(a, args)\nend", - "RawParseTree" => [:defn, :x, - [:scope, - [:block, - [:args, :a, :"*args"], - [:fcall, :p, - [:array, [:lvar, :a], [:lvar, :args]]]]]], - "ParseTree" => s(:defn, :x, - s(:args, :a, :"*args"), - s(:scope, - s(:block, - s(:call, nil, :p, - s(:arglist, s(:lvar, :a), s(:lvar, :args))))))) - - add_tests("defn_args_none", - "Ruby" => "def empty\n # do nothing\nend", - "RawParseTree" => [:defn, :empty, - [:scope, [:block, [:args], [:nil]]]], - "ParseTree" => s(:defn, :empty, - s(:args), - s(:scope, s(:block, s(:nil))))) - - add_tests("defn_args_opt", - "Ruby" => "def f(opt = 42)\n # do nothing\nend", - "RawParseTree" => [:defn, :f, - [:scope, - [:block, - [:args, :opt, - [:block, - [:lasgn, :opt, [:lit, 42]]]], - [:nil]]]], - "ParseTree" => s(:defn, :f, - s(:args, :opt, - s(:block, - s(:lasgn, :opt, s(:lit, 42)))), - s(:scope, s(:block, s(:nil))))) - - add_tests("defn_args_opt_block", - "Ruby" => "def f(opt = 42, &block)\n # do nothing\nend", - "RawParseTree" => [:defn, :f, - [:scope, - [:block, - [:args, :opt, - [:block, - [:lasgn, :opt, [:lit, 42]]]], - [:block_arg, :block], - [:nil]]]], - "ParseTree" => s(:defn, :f, - s(:args, :opt, :"&block", - s(:block, - s(:lasgn, :opt, s(:lit, 42)))), - s(:scope, s(:block, s(:nil))))) - - add_tests("defn_args_opt_splat", - "Ruby" => "def f(opt = 42, *rest)\n # do nothing\nend", - "RawParseTree" => [:defn, :f, - [:scope, - [:block, - [:args, :opt, :"*rest", - [:block, - [:lasgn, :opt, [:lit, 42]]]], - [:nil]]]], - "ParseTree" => s(:defn, :f, - s(:args, :opt, :"*rest", - s(:block, - s(:lasgn, :opt, s(:lit, 42)))), - s(:scope, s(:block, s(:nil))))) - - add_tests("defn_args_opt_splat_block", - "Ruby" => "def f(opt = 42, *rest, &block)\n # do nothing\nend", - "RawParseTree" => [:defn, :f, - [:scope, - [:block, - [:args, :opt, :"*rest", - [:block, - [:lasgn, :opt, [:lit, 42]]]], - [:block_arg, :block], - [:nil]]]], - "ParseTree" => s(:defn, :f, - s(:args, :opt, :"*rest", :"&block", - s(:block, - s(:lasgn, :opt, s(:lit, 42)))), - s(:scope, s(:block, s(:nil))))) - - add_tests("defn_args_opt_splat_no_name", - "Ruby" => "def x(b = 42, *)\n # do nothing\nend", - "RawParseTree" => [:defn, :x, - [:scope, - [:block, - [:args, :b, :"*", - [:block, [:lasgn, :b, [:lit, 42]]]], - [:nil]]]], - "ParseTree" => s(:defn, :x, - s(:args, :b, :"*", - s(:block, s(:lasgn, :b, s(:lit, 42)))), - s(:scope, - s(:block, - s(:nil))))) - - add_tests("defn_args_splat", - "Ruby" => "def f(*rest)\n # do nothing\nend", - "RawParseTree" => [:defn, :f, - [:scope, - [:block, - [:args, :"*rest"], - [:nil]]]], - "ParseTree" => s(:defn, :f, - s(:args, :"*rest"), - s(:scope, s(:block, s(:nil))))) - - add_tests("defn_args_splat_no_name", - "Ruby" => "def x(*)\n # do nothing\nend", - "RawParseTree" => [:defn, :x, - [:scope, - [:block, - [:args, :"*"], - [:nil]]]], - "ParseTree" => s(:defn, :x, - s(:args, :"*"), - s(:scope, - s(:block, - s(:nil))))) - - add_tests("defn_or", - "Ruby" => "def |(o)\n # do nothing\nend", - "RawParseTree" => [:defn, :|, - [:scope, [:block, [:args, :o], [:nil]]]], - "ParseTree" => s(:defn, :|, - s(:args, :o), - s(:scope, s(:block, s(:nil))))) - - add_tests("defn_rescue", - "Ruby" => "def eql?(resource)\n (self.uuid == resource.uuid)\nrescue\n false\nend", - "RawParseTree" => [:defn, :eql?, - [:scope, - [:block, - [:args, :resource], - [:rescue, - [:call, - [:call, [:self], :uuid], - :==, - [:array, - [:call, [:lvar, :resource], :uuid]]], - [:resbody, nil, [:false]]]]]], - "ParseTree" => s(:defn, :eql?, - s(:args, :resource), - s(:scope, - s(:block, - s(:rescue, - s(:call, - s(:call, s(:self), :uuid, s(:arglist)), - :==, - s(:arglist, - s(:call, s(:lvar, :resource), - :uuid, s(:arglist)))), - s(:resbody, s(:array), s(:false)))))), - "Ruby2Ruby" => "def eql?(resource)\n (self.uuid == resource.uuid) rescue false\nend") - - add_tests("defn_rescue_mri_verbose_flag", - "Ruby" => "def eql?(resource)\n (self.uuid == resource.uuid)\nrescue\n false\nend", - "RawParseTree" => [:defn, :eql?, - [:scope, - [:block, - [:args, :resource], - [:rescue, - [:call, - [:call, [:self], :uuid], - :==, - [:array, - [:call, [:lvar, :resource], :uuid]]], - [:resbody, nil, [:false]]]]]], - "ParseTree" => s(:defn, :eql?, - s(:args, :resource), - s(:scope, - s(:block, - s(:rescue, - s(:call, - s(:call, s(:self), :uuid, s(:arglist)), - :==, - s(:arglist, - s(:call, s(:lvar, :resource), - :uuid, s(:arglist)))), - s(:resbody, s(:array), s(:false)))))), - "Ruby2Ruby" => "def eql?(resource)\n (self.uuid == resource.uuid) rescue false\nend") - - add_tests("defn_something_eh", - "Ruby" => "def something?\n # do nothing\nend", - "RawParseTree" => [:defn, :something?, - [:scope, [:block, [:args], [:nil]]]], - "ParseTree" => s(:defn, :something?, - s(:args), - s(:scope, s(:block, s(:nil))))) - - add_tests("defn_splat_no_name", - "Ruby" => "def x(a, *)\n p(a)\nend", - "RawParseTree" => [:defn, :x, - [:scope, - [:block, - [:args, :a, :"*"], - [:fcall, :p, - [:array, [:lvar, :a]]]]]], - "ParseTree" => s(:defn, :x, - s(:args, :a, :"*"), - s(:scope, - s(:block, - s(:call, nil, :p, - s(:arglist, s(:lvar, :a))))))) - - add_tests("defn_zarray", - "Ruby" => "def zarray\n a = []\n return a\nend", - "RawParseTree" => [:defn, :zarray, - [:scope, - [:block, [:args], - [:lasgn, :a, [:zarray]], - [:return, [:lvar, :a]]]]], - "ParseTree" => s(:defn, :zarray, - s(:args), - s(:scope, - s(:block, - s(:lasgn, :a, s(:array)), - s(:return, s(:lvar, :a)))))) - - add_tests("defs", - "Ruby" => "def self.x(y)\n (y + 1)\nend", - "RawParseTree" => [:defs, [:self], :x, - [:scope, - [:block, - [:args, :y], - [:call, [:lvar, :y], :+, - [:array, [:lit, 1]]]]]], - "ParseTree" => s(:defs, s(:self), :x, - s(:args, :y), - s(:scope, - s(:block, - s(:call, s(:lvar, :y), :+, - s(:arglist, s(:lit, 1))))))) - - add_tests("defs_empty", - "Ruby" => "def self.empty\n # do nothing\nend", - "RawParseTree" => [:defs, [:self], :empty, - [:scope, [:args]]], - "ParseTree" => s(:defs, s(:self), :empty, - s(:args), - s(:scope, s(:block)))) - - add_tests("defs_empty_args", - "Ruby" => "def self.empty(*)\n # do nothing\nend", - "RawParseTree" => [:defs, [:self], :empty, - [:scope, [:args, :*]]], - "ParseTree" => s(:defs, s(:self), :empty, - s(:args, :*), - s(:scope, s(:block)))) - - add_tests("defs_expr_wtf", - "Ruby" => "def (a.b).empty(*)\n # do nothing\nend", - "RawParseTree" => [:defs, - [:call, [:vcall, :a], :b], - :empty, - [:scope, [:args, :*]]], - "ParseTree" => s(:defs, - s(:call, - s(:call, nil, :a, s(:arglist)), - :b, s(:arglist)), - :empty, - s(:args, :*), - s(:scope, s(:block)))) - - add_tests("dmethod", - "Ruby" => [Examples, :dmethod_added], - "RawParseTree" => [:defn, :dmethod_added, - [:dmethod, - :a_method, - [:scope, - [:block, - [:args, :x], - [:call, [:lvar, :x], :+, - [:array, [:lit, 1]]]]]]], - "ParseTree" => s(:defn, :dmethod_added, - s(:args, :x), - s(:scope, - s(:block, - s(:call, s(:lvar, :x), :+, - s(:arglist, s(:lit, 1)))))), - "Ruby2Ruby" => "def dmethod_added(x)\n (x + 1)\nend") - - add_tests("dot2", - "Ruby" => "(a..b)", - "RawParseTree" => [:dot2, [:vcall, :a], [:vcall, :b]], - "ParseTree" => s(:dot2, - s(:call, nil, :a, s(:arglist)), - s(:call, nil, :b, s(:arglist)))) - - add_tests("dot3", - "Ruby" => "(a...b)", - "RawParseTree" => [:dot3, [:vcall, :a], [:vcall, :b]], - "ParseTree" => s(:dot3, - s(:call, nil, :a, s(:arglist)), - s(:call, nil, :b, s(:arglist)))) - - add_tests("dregx", - "Ruby" => "/x#\{(1 + 1)}y/", - "RawParseTree" => [:dregx, "x", - [:evstr, - [:call, [:lit, 1], :+, [:array, [:lit, 1]]]], - [:str, "y"]], - "ParseTree" => s(:dregx, "x", - s(:evstr, - s(:call, s(:lit, 1), :+, - s(:arglist, s(:lit, 1)))), - s(:str, "y"))) - - add_tests("dregx_interp", - "Ruby" => "/#\{@rakefile}/", - "RawParseTree" => [:dregx, '', [:evstr, [:ivar, :@rakefile]]], - "ParseTree" => s(:dregx, '', s(:evstr, s(:ivar, :@rakefile)))) - - add_tests("dregx_interp_empty", - "Ruby" => "/a#\{}b/", - "RawParseTree" => [:dregx, 'a', [:evstr], [:str, "b"]], - "ParseTree" => s(:dregx, 'a', s(:evstr), s(:str, "b"))) - - add_tests("dregx_n", - "Ruby" => '/#{1}/n', - "RawParseTree" => [:dregx, '', [:evstr, [:lit, 1]], /x/n.options], - "ParseTree" => s(:dregx, '', - s(:evstr, s(:lit, 1)), /x/n.options), - "Ruby2Ruby" => "/#\{1}/") # HACK - need to support regexp flag - - add_tests("dregx_once", - "Ruby" => "/x#\{(1 + 1)}y/o", - "RawParseTree" => [:dregx_once, "x", - [:evstr, - [:call, [:lit, 1], :+, [:array, [:lit, 1]]]], - [:str, "y"]], - "ParseTree" => s(:dregx_once, "x", - s(:evstr, - s(:call, s(:lit, 1), :+, - s(:arglist, s(:lit, 1)))), - s(:str, "y"))) - - add_tests("dregx_once_n_interp", - "Ruby" => "/#\{IAC}#\{SB}/no", - "RawParseTree" => [:dregx_once, '', - [:evstr, [:const, :IAC]], - [:evstr, [:const, :SB]], /x/n.options], - "ParseTree" => s(:dregx_once, '', - s(:evstr, s(:const, :IAC)), - s(:evstr, s(:const, :SB)), /x/n.options), - "Ruby2Ruby" => "/#\{IAC}#\{SB}/o") # HACK - - add_tests("dstr", - "Ruby" => "argl = 1\n\"x#\{argl}y\"\n", - "RawParseTree" => [:block, - [:lasgn, :argl, [:lit, 1]], - [:dstr, "x", [:evstr, [:lvar, :argl]], - [:str, "y"]]], - "ParseTree" => s(:block, - s(:lasgn, :argl, s(:lit, 1)), - s(:dstr, "x", s(:evstr, s(:lvar, :argl)), - s(:str, "y")))) - - add_tests("dstr_2", - "Ruby" => "argl = 1\n\"x#\{(\"%.2f\" % 3.14159)}y\"\n", - "RawParseTree" => [:block, - [:lasgn, :argl, [:lit, 1]], - [:dstr, - "x", - [:evstr, - [:call, [:str, "%.2f"], :%, - [:array, [:lit, 3.14159]]]], - [:str, "y"]]], - "ParseTree" => s(:block, - s(:lasgn, :argl, s(:lit, 1)), - s(:dstr, - "x", - s(:evstr, - s(:call, s(:str, "%.2f"), :%, - s(:arglist, s(:lit, 3.14159)))), - s(:str, "y")))) - - add_tests("dstr_3", - "Ruby" => "max = 2\nargl = 1\n\"x#\{(\"%.#\{max}f\" % 3.14159)}y\"\n", - "RawParseTree" => [:block, - [:lasgn, :max, [:lit, 2]], - [:lasgn, :argl, [:lit, 1]], - [:dstr, "x", - [:evstr, - [:call, - [:dstr, "%.", - [:evstr, [:lvar, :max]], - [:str, "f"]], - :%, - [:array, [:lit, 3.14159]]]], - [:str, "y"]]], - "ParseTree" => s(:block, - s(:lasgn, :max, s(:lit, 2)), - s(:lasgn, :argl, s(:lit, 1)), - s(:dstr, "x", - s(:evstr, - s(:call, - s(:dstr, "%.", - s(:evstr, s(:lvar, :max)), - s(:str, "f")), - :%, - s(:arglist, s(:lit, 3.14159)))), - s(:str, "y")))) - - add_tests("dstr_concat", - "Ruby" => '"#{22}aa" "cd#{44}" "55" "#{66}"', - "RawParseTree" => [:dstr, - "", - [:evstr, [:lit, 22]], - [:str, "aa"], - [:str, "cd"], - [:evstr, [:lit, 44]], - [:str, "55"], - [:evstr, [:lit, 66]]], - "ParseTree" => s(:dstr, - "", - s(:evstr, s(:lit, 22)), - s(:str, "aa"), - s(:str, "cd"), - s(:evstr, s(:lit, 44)), - s(:str, "55"), - s(:evstr, s(:lit, 66))), - "Ruby2Ruby" => '"#{22}aacd#{44}55#{66}"') - - add_tests("dstr_gross", - "Ruby" => '"a #$global b #@ivar c #@@cvar d"', - "RawParseTree" => [:dstr, "a ", - [:evstr, [:gvar, :$global]], - [:str, " b "], - [:evstr, [:ivar, :@ivar]], - [:str, " c "], - [:evstr, [:cvar, :@@cvar]], - [:str, " d"]], - "ParseTree" => s(:dstr, "a ", - s(:evstr, s(:gvar, :$global)), - s(:str, " b "), - s(:evstr, s(:ivar, :@ivar)), - s(:str, " c "), - s(:evstr, s(:cvar, :@@cvar)), - s(:str, " d")), - "Ruby2Ruby" => '"a #{$global} b #{@ivar} c #{@@cvar} d"') - - add_tests("dstr_heredoc_expand", - "Ruby" => "< [:dstr, " blah\n", - [:evstr, [:call, [:lit, 1], :+, - [:array, [:lit, 1]]]], - [:str, "blah\n"]], - "ParseTree" => s(:dstr, " blah\n", - s(:evstr, s(:call, s(:lit, 1), :+, - s(:arglist, s(:lit, 1)))), - s(:str, "blah\n")), - "Ruby2Ruby" => "\" blah\\n#\{(1 + 1)}blah\\n\"") - - add_tests("dstr_heredoc_windoze_sucks", - "Ruby" => "<<-EOF\r\ndef test_#\{action}_valid_feed\r\n EOF\r\n", - "RawParseTree" => [:dstr, - 'def test_', - [:evstr, [:vcall, :action]], - [:str, "_valid_feed\n"]], - "ParseTree" => s(:dstr, - 'def test_', - s(:evstr, s(:call, nil, :action, s(:arglist))), - s(:str, "_valid_feed\n")), - "Ruby2Ruby" => "\"def test_#\{action}_valid_feed\\n\"") - - add_tests("dstr_heredoc_yet_again", - "Ruby" => "<<-EOF\ns1 '#\{RUBY_PLATFORM}' s2\n#\{__FILE__}\n EOF\n", - "RawParseTree" => [:dstr, "s1 '", - [:evstr, [:const, :RUBY_PLATFORM]], - [:str, "' s2\n"], - [:str, "(string)"], - [:str, "\n"]], - "ParseTree" => s(:dstr, "s1 '", - s(:evstr, s(:const, :RUBY_PLATFORM)), - s(:str, "' s2\n"), - s(:str, "(string)"), - s(:str, "\n")), - "Ruby2Ruby" => "\"s1 '#\{RUBY_PLATFORM}' s2\\n(string)\\n\"") - - add_tests("dstr_nest", - "Ruby" => "%Q[before [#\{nest}] after]", - "RawParseTree" => [:dstr, "before [", - [:evstr, [:vcall, :nest]], [:str, "] after"]], - "ParseTree" => s(:dstr, "before [", - s(:evstr, s(:call, nil, :nest, s(:arglist))), - s(:str, "] after")), - "Ruby2Ruby" => "\"before [#\{nest}] after\"") - - add_tests("dstr_str_lit_start", - "Ruby" => '"#{"blah"}#{__FILE__}:#{__LINE__}: warning: #{$!.message} (#{$!.class})"', - "RawParseTree" => [:dstr, - "blah(string):", - [:evstr, [:lit, 1]], - [:str, ": warning: "], - [:evstr, [:call, [:gvar, :$!], :message]], - [:str, " ("], - [:evstr, [:call, [:gvar, :$!], :class]], - [:str, ")"]], - "ParseTree" => s(:dstr, - "blah(string):", - s(:evstr, s(:lit, 1)), - s(:str, ": warning: "), - s(:evstr, s(:call, s(:gvar, :$!), :message, - s(:arglist))), - s(:str, " ("), - s(:evstr, s(:call, s(:gvar, :$!), :class, - s(:arglist))), - s(:str, ")")), - "Ruby2Ruby" => '"blah(string):#{1}: warning: #{$!.message} (#{$!.class})"') - - add_tests("dstr_the_revenge", - "Ruby" => '"before #{from} middle #{to} (#{__FILE__}:#{__LINE__})"', - "RawParseTree" => [:dstr, - "before ", - [:evstr, [:vcall, :from]], - [:str, " middle "], - [:evstr, [:vcall, :to]], - [:str, " ("], - [:str, "(string)"], - [:str, ":"], - [:evstr, [:lit, 1]], - [:str, ")"]], - "ParseTree" => s(:dstr, - "before ", - s(:evstr, s(:call, nil, :from, s(:arglist))), - s(:str, " middle "), - s(:evstr, s(:call, nil, :to, s(:arglist))), - s(:str, " ("), - s(:str, "(string)"), - s(:str, ":"), - s(:evstr, s(:lit, 1)), - s(:str, ")")), - "Ruby2Ruby" => '"before #{from} middle #{to} ((string):#{1})"') - - add_tests("dsym", - "Ruby" => ":\"x#\{(1 + 1)}y\"", - "RawParseTree" => [:dsym, "x", - [:evstr, [:call, [:lit, 1], :+, - [:array, [:lit, 1]]]], [:str, "y"]], - "ParseTree" => s(:dsym, "x", - s(:evstr, s(:call, s(:lit, 1), :+, - s(:arglist, s(:lit, 1)))), s(:str, "y"))) - - add_tests("dxstr", - "Ruby" => "t = 5\n`touch #\{t}`\n", - "RawParseTree" => [:block, - [:lasgn, :t, [:lit, 5]], - [:dxstr, 'touch ', [:evstr, [:lvar, :t]]]], - "ParseTree" => s(:block, - s(:lasgn, :t, s(:lit, 5)), - s(:dxstr, 'touch ', s(:evstr, s(:lvar, :t))))) - - add_tests("ensure", - "Ruby" => "begin\n (1 + 1)\nrescue SyntaxError => e1\n 2\nrescue Exception => e2\n 3\nelse\n 4\nensure\n 5\nend", - "RawParseTree" => [:ensure, - [:rescue, - [:call, [:lit, 1], :+, [:array, [:lit, 1]]], - [:resbody, - [:array, [:const, :SyntaxError]], - [:block, - [:lasgn, :e1, [:gvar, :$!]], [:lit, 2]], - [:resbody, - [:array, [:const, :Exception]], - [:block, - [:lasgn, :e2, [:gvar, :$!]], [:lit, 3]]]], - [:lit, 4]], - [:lit, 5]], - "ParseTree" => s(:ensure, - s(:rescue, - s(:call, s(:lit, 1), :+, - s(:arglist, s(:lit, 1))), - s(:resbody, - s(:array, - s(:const, :SyntaxError), - s(:lasgn, :e1, s(:gvar, :$!))), - s(:lit, 2)), - s(:resbody, - s(:array, - s(:const, :Exception), - s(:lasgn, :e2, s(:gvar, :$!))), - s(:lit, 3)), - s(:lit, 4)), - s(:lit, 5))) - - add_tests("false", - "Ruby" => "false", - "RawParseTree" => [:false], - "ParseTree" => s(:false)) - - add_tests("fbody", - "Ruby" => [Examples, :an_alias], - "RawParseTree" => [:defn, :an_alias, - [:fbody, - [:scope, - [:block, - [:args, :x], - [:call, [:lvar, :x], :+, - [:array, [:lit, 1]]]]]]], - "ParseTree" => s(:defn, :an_alias, - s(:args, :x), - s(:scope, - s(:block, - s(:call, s(:lvar, :x), :+, - s(:arglist, s(:lit, 1)))))), - "Ruby2Ruby" => "def an_alias(x)\n (x + 1)\nend") - - add_tests("fcall_arglist", - "Ruby" => "m(42)", - "RawParseTree" => [:fcall, :m, [:array, [:lit, 42]]], - "ParseTree" => s(:call, nil, :m, s(:arglist, s(:lit, 42)))) - - add_tests("fcall_arglist_hash", - "Ruby" => "m(:a => 1, :b => 2)", - "RawParseTree" => [:fcall, :m, - [:array, - [:hash, - [:lit, :a], [:lit, 1], - [:lit, :b], [:lit, 2]]]], - "ParseTree" => s(:call, nil, :m, - s(:arglist, - s(:hash, - s(:lit, :a), s(:lit, 1), - s(:lit, :b), s(:lit, 2))))) - - add_tests("fcall_arglist_norm_hash", - "Ruby" => "m(42, :a => 1, :b => 2)", - "RawParseTree" => [:fcall, :m, - [:array, - [:lit, 42], - [:hash, - [:lit, :a], [:lit, 1], - [:lit, :b], [:lit, 2]]]], - "ParseTree" => s(:call, nil, :m, - s(:arglist, - s(:lit, 42), - s(:hash, - s(:lit, :a), s(:lit, 1), - s(:lit, :b), s(:lit, 2))))) - - add_tests("fcall_arglist_norm_hash_splat", - "Ruby" => "m(42, :a => 1, :b => 2, *c)", - "RawParseTree" => [:fcall, :m, - [:argscat, - [:array, - [:lit, 42], - [:hash, - [:lit, :a], [:lit, 1], - [:lit, :b], [:lit, 2]]], - [:vcall, :c]]], - "ParseTree" => s(:call, nil, :m, - s(:arglist, - s(:lit, 42), - s(:hash, - s(:lit, :a), s(:lit, 1), - s(:lit, :b), s(:lit, 2)), - s(:splat, s(:call, nil, :c, s(:arglist)))))) - - add_tests("fcall_block", - "Ruby" => "a(:b) { :c }", - "RawParseTree" => [:iter, - [:fcall, :a, [:array, [:lit, :b]]], nil, - [:lit, :c]], - "ParseTree" => s(:iter, - s(:call, nil, :a, - s(:arglist, s(:lit, :b))), nil, - s(:lit, :c))) - - add_tests("fcall_index_space", - "Ruby" => "a [42]", - "RawParseTree" => [:fcall, :a, [:array, [:array, [:lit, 42]]]], - "ParseTree" => s(:call, nil, :a, - s(:arglist, s(:array, s(:lit, 42)))), - "Ruby2Ruby" => "a([42])") - - add_tests("fcall_keyword", - "Ruby" => "42 if block_given?", - "RawParseTree" => [:if, [:fcall, :block_given?], [:lit, 42], nil], - "ParseTree" => s(:if, - s(:call, nil, :block_given?, s(:arglist)), - s(:lit, 42), nil)) - - add_tests("flip2", - "Ruby" => "x = if ((i % 4) == 0)..((i % 3) == 0) then\n i\nelse\n nil\nend", - "RawParseTree" => [:lasgn, - :x, - [:if, - [:flip2, - [:call, - [:call, [:vcall, :i], :%, - [:array, [:lit, 4]]], - :==, - [:array, [:lit, 0]]], - [:call, - [:call, [:vcall, :i], :%, - [:array, [:lit, 3]]], - :==, - [:array, [:lit, 0]]]], - [:vcall, :i], - [:nil]]], - "ParseTree" => s(:lasgn, - :x, - s(:if, - s(:flip2, - s(:call, - s(:call, s(:call, nil, :i, s(:arglist)), - :%, - s(:arglist, s(:lit, 4))), - :==, - s(:arglist, s(:lit, 0))), - s(:call, - s(:call, s(:call, nil, :i, s(:arglist)), - :%, - s(:arglist, s(:lit, 3))), - :==, - s(:arglist, s(:lit, 0)))), - s(:call, nil, :i, s(:arglist)), - s(:nil)))) - - add_tests("flip2_method", - "Ruby" => "if 1..2.a?(b) then\n nil\nend", - "RawParseTree" => [:if, - [:flip2, - [:call, [:lit, 1], :==, - [:array, [:gvar, :$.]]], - [:call, [:lit, 2], :a?, - [:array, [:vcall, :b]]]], - [:nil], - nil], - "ParseTree" => s(:if, - s(:flip2, - s(:lit, 1), - s(:call, s(:lit, 2), :a?, - s(:arglist, - s(:call, nil, :b, s(:arglist))))), - s(:nil), - nil)) - - add_tests("flip3", - "Ruby" => "x = if ((i % 4) == 0)...((i % 3) == 0) then\n i\nelse\n nil\nend", - "RawParseTree" => [:lasgn, - :x, - [:if, - [:flip3, - [:call, - [:call, [:vcall, :i], :%, - [:array, [:lit, 4]]], - :==, - [:array, [:lit, 0]]], - [:call, - [:call, [:vcall, :i], :%, - [:array, [:lit, 3]]], - :==, - [:array, [:lit, 0]]]], - [:vcall, :i], - [:nil]]], - "ParseTree" => s(:lasgn, - :x, - s(:if, - s(:flip3, - s(:call, - s(:call, s(:call, nil, :i, s(:arglist)), - :%, - s(:arglist, s(:lit, 4))), - :==, - s(:arglist, s(:lit, 0))), - s(:call, - s(:call, s(:call, nil, :i, s(:arglist)), - :%, - s(:arglist, s(:lit, 3))), - :==, - s(:arglist, s(:lit, 0)))), - s(:call, nil, :i, s(:arglist)), - s(:nil)))) - - add_tests("for", - "Ruby" => "for o in ary do\n puts(o)\nend", - "RawParseTree" => [:for, - [:vcall, :ary], - [:lasgn, :o], - [:fcall, :puts, [:array, [:lvar, :o]]]], - "ParseTree" => s(:for, - s(:call, nil, :ary, s(:arglist)), - s(:lasgn, :o), - s(:call, nil, :puts, - s(:arglist, s(:lvar, :o))))) - - add_tests("for_no_body", - "Ruby" => "for i in (0..max) do\n # do nothing\nend", - "RawParseTree" => [:for, - [:dot2, [:lit, 0], [:vcall, :max]], - [:lasgn, :i]], - "ParseTree" => s(:for, - s(:dot2, - s(:lit, 0), - s(:call, nil, :max, s(:arglist))), - s(:lasgn, :i))) - - add_tests("gasgn", - "Ruby" => "$x = 42", - "RawParseTree" => [:gasgn, :$x, [:lit, 42]], - "ParseTree" => s(:gasgn, :$x, s(:lit, 42))) - - add_tests("global", - "Ruby" => "$stderr", - "RawParseTree" => [:gvar, :$stderr], - "ParseTree" => s(:gvar, :$stderr)) - - add_tests("gvar", - "Ruby" => "$x", - "RawParseTree" => [:gvar, :$x], - "ParseTree" => s(:gvar, :$x)) - - add_tests("gvar_underscore", - "Ruby" => "$_", - "RawParseTree" => [:gvar, :$_], - "ParseTree" => s(:gvar, :$_)) - - add_tests("gvar_underscore_blah", - "Ruby" => "$__blah", - "RawParseTree" => [:gvar, :$__blah], - "ParseTree" => s(:gvar, :$__blah)) - - add_tests("hash", - "Ruby" => "{ 1 => 2, 3 => 4 }", - "RawParseTree" => [:hash, - [:lit, 1], [:lit, 2], - [:lit, 3], [:lit, 4]], - "ParseTree" => s(:hash, - s(:lit, 1), s(:lit, 2), - s(:lit, 3), s(:lit, 4))) - - add_tests("hash_rescue", - "Ruby" => "{ 1 => (2 rescue 3) }", - "RawParseTree" => [:hash, - [:lit, 1], - [:rescue, - [:lit, 2], - [:resbody, nil, [:lit, 3]]]], - "ParseTree" => s(:hash, - s(:lit, 1), - s(:rescue, - s(:lit, 2), - s(:resbody, s(:array), s(:lit, 3))))) - - add_tests("iasgn", - "Ruby" => "@a = 4", - "RawParseTree" => [:iasgn, :@a, [:lit, 4]], - "ParseTree" => s(:iasgn, :@a, s(:lit, 4))) - - add_tests("if_block_condition", - "Ruby" => "if (x = 5\n(x + 1)) then\n nil\nend", - "RawParseTree" => [:if, - [:block, - [:lasgn, :x, [:lit, 5]], - [:call, - [:lvar, :x], - :+, - [:array, [:lit, 1]]]], - [:nil], - nil], - "ParseTree" => s(:if, - s(:block, - s(:lasgn, :x, s(:lit, 5)), - s(:call, - s(:lvar, :x), - :+, - s(:arglist, s(:lit, 1)))), - s(:nil), - nil)) - - add_tests("if_lasgn_short", - "Ruby" => "if x = obj.x then\n x.do_it\nend", - "RawParseTree" => [:if, - [:lasgn, :x, - [:call, [:vcall, :obj], :x]], - [:call, - [:lvar, :x], :do_it], - nil], - "ParseTree" => s(:if, - s(:lasgn, :x, - s(:call, - s(:call, nil, :obj, s(:arglist)), - :x, s(:arglist))), - s(:call, s(:lvar, :x), :do_it, s(:arglist)), - nil)) - - add_tests("if_nested", - "Ruby" => "return if false unless true", - "RawParseTree" => [:if, [:true], nil, - [:if, [:false], [:return], nil]], - "ParseTree" => s(:if, s(:true), nil, - s(:if, s(:false), s(:return), nil))) - - add_tests("if_post", - "Ruby" => "a if b", - "RawParseTree" => [:if, [:vcall, :b], [:vcall, :a], nil], - "ParseTree" => s(:if, s(:call, nil, :b, s(:arglist)), - s(:call, nil, :a, s(:arglist)), nil)) - - add_tests("if_post_not", - "Ruby" => "a if not b", - "RawParseTree" => [:if, [:vcall, :b], nil, [:vcall, :a]], - "ParseTree" => s(:if, s(:call, nil, :b, s(:arglist)), nil, - s(:call, nil, :a, s(:arglist))), - "Ruby2Ruby" => "a unless b") - - add_tests("if_pre", - "Ruby" => "if b then a end", - "RawParseTree" => [:if, [:vcall, :b], [:vcall, :a], nil], - "ParseTree" => s(:if, s(:call, nil, :b, s(:arglist)), - s(:call, nil, :a, s(:arglist)), nil), - "Ruby2Ruby" => "a if b") - - add_tests("if_pre_not", - "Ruby" => "if not b then a end", - "RawParseTree" => [:if, [:vcall, :b], nil, [:vcall, :a]], - "ParseTree" => s(:if, s(:call, nil, :b, s(:arglist)), nil, - s(:call, nil, :a, s(:arglist))), - "Ruby2Ruby" => "a unless b") - - add_tests("iter_call_arglist_space", - "Ruby" => "a (1) {|c|d}", - "RawParseTree" => [:iter, - [:fcall, :a, [:array, [:lit, 1]]], - [:dasgn_curr, :c], - [:vcall, :d]], - "ParseTree" => s(:iter, - s(:call, nil, :a, s(:arglist, s(:lit, 1))), - s(:lasgn, :c), - s(:call, nil, :d, s(:arglist))), - "Ruby2Ruby" => "a(1) { |c| d }") - - add_tests("iter_dasgn_curr_dasgn_madness", - "Ruby" => "as.each { |a|\n b += a.b(false) }", - "RawParseTree" => [:iter, - [:call, [:vcall, :as], :each], - [:dasgn_curr, :a], - [:dasgn_curr, - :b, - [:call, - [:dvar, :b], - :+, - [:array, - [:call, [:dvar, :a], :b, - [:array, [:false]]]]]]], - "ParseTree" => s(:iter, - s(:call, - s(:call, nil, :as, s(:arglist)), - :each, s(:arglist)), - s(:lasgn, :a), - s(:lasgn, :b, - s(:call, - s(:lvar, :b), - :+, - s(:arglist, - s(:call, s(:lvar, :a), :b, - s(:arglist, s(:false))))))), - "Ruby2Ruby" => "as.each { |a| b = (b + a.b(false)) }") - - add_tests("iter_downto", - "Ruby" => "3.downto(1) { |n| puts(n.to_s) }", - "RawParseTree" => [:iter, - [:call, [:lit, 3], :downto, [:array, [:lit, 1]]], - [:dasgn_curr, :n], - [:fcall, :puts, - [:array, [:call, [:dvar, :n], :to_s]]]], - "ParseTree" => s(:iter, - s(:call, s(:lit, 3), :downto, - s(:arglist, s(:lit, 1))), - s(:lasgn, :n), - s(:call, nil, :puts, - s(:arglist, - s(:call, s(:lvar, :n), - :to_s, s(:arglist)))))) - - add_tests("iter_each_lvar", - "Ruby" => "array = [1, 2, 3]\narray.each { |x| puts(x.to_s) }\n", - "RawParseTree" => [:block, - [:lasgn, :array, - [:array, [:lit, 1], [:lit, 2], [:lit, 3]]], - [:iter, - [:call, [:lvar, :array], :each], - [:dasgn_curr, :x], - [:fcall, :puts, - [:array, [:call, [:dvar, :x], :to_s]]]]], - "ParseTree" => s(:block, - s(:lasgn, :array, - s(:array, - s(:lit, 1), s(:lit, 2), s(:lit, 3))), - s(:iter, - s(:call, s(:lvar, :array), :each, - s(:arglist)), - s(:lasgn, :x), - s(:call, nil, :puts, - s(:arglist, s(:call, s(:lvar, :x), - :to_s, s(:arglist))))))) - - add_tests("iter_each_nested", - "Ruby" => "array1 = [1, 2, 3]\narray2 = [4, 5, 6, 7]\narray1.each do |x|\n array2.each do |y|\n puts(x.to_s)\n puts(y.to_s)\n end\nend\n", - "RawParseTree" => [:block, - [:lasgn, :array1, - [:array, [:lit, 1], [:lit, 2], [:lit, 3]]], - [:lasgn, :array2, - [:array, - [:lit, 4], [:lit, 5], [:lit, 6], [:lit, 7]]], - [:iter, - [:call, - [:lvar, :array1], :each], - [:dasgn_curr, :x], - [:iter, - [:call, - [:lvar, :array2], :each], - [:dasgn_curr, :y], - [:block, - [:fcall, :puts, - [:array, [:call, [:dvar, :x], :to_s]]], - [:fcall, :puts, - [:array, [:call, [:dvar, :y], :to_s]]]]]]], - "ParseTree" => s(:block, - s(:lasgn, :array1, - s(:array, - s(:lit, 1), s(:lit, 2), s(:lit, 3))), - s(:lasgn, :array2, - s(:array, - s(:lit, 4), s(:lit, 5), - s(:lit, 6), s(:lit, 7))), - s(:iter, - s(:call, - s(:lvar, :array1), :each, s(:arglist)), - s(:lasgn, :x), - s(:iter, - s(:call, - s(:lvar, :array2), :each, s(:arglist)), - s(:lasgn, :y), - s(:block, - s(:call, nil, :puts, - s(:arglist, - s(:call, s(:lvar, :x), - :to_s, s(:arglist)))), - s(:call, nil, :puts, - s(:arglist, - s(:call, s(:lvar, :y), - :to_s, s(:arglist))))))))) - - add_tests("iter_loop_empty", - "Ruby" => "loop { }", - "RawParseTree" => [:iter, [:fcall, :loop], nil], - "ParseTree" => s(:iter, s(:call, nil, :loop, s(:arglist)), nil)) - - add_tests("iter_masgn_2", - "Ruby" => "a { |b, c| p(c) }", - "RawParseTree" => [:iter, - [:fcall, :a], - [:masgn, - [:array, [:dasgn_curr, :b], [:dasgn_curr, :c]], - nil, nil], - [:fcall, :p, [:array, [:dvar, :c]]]], - "ParseTree" => s(:iter, - s(:call, nil, :a, s(:arglist)), - s(:masgn, - s(:array, s(:lasgn, :b), s(:lasgn, :c))), - s(:call, nil, :p, s(:arglist, s(:lvar, :c))))) - - add_tests("iter_masgn_args_splat", - "Ruby" => "a { |b, c, *d| p(c) }", - "RawParseTree" => [:iter, - [:fcall, :a], - [:masgn, - [:array, [:dasgn_curr, :b], [:dasgn_curr, :c]], - [:dasgn_curr, :d], nil], - [:fcall, :p, [:array, [:dvar, :c]]]], - "ParseTree" => s(:iter, - s(:call, nil, :a, s(:arglist)), - s(:masgn, - s(:array, - s(:lasgn, :b), - s(:lasgn, :c), - s(:splat, s(:lasgn, :d)))), - s(:call, nil, :p, s(:arglist, s(:lvar, :c))))) - - add_tests("iter_masgn_args_splat_no_name", - "Ruby" => "a { |b, c, *| p(c) }", - "RawParseTree" => [:iter, - [:fcall, :a], - [:masgn, - [:array, [:dasgn_curr, :b], [:dasgn_curr, :c]], - [:splat], nil], - [:fcall, :p, [:array, [:dvar, :c]]]], - "ParseTree" => s(:iter, - s(:call, nil, :a, s(:arglist)), - s(:masgn, - s(:array, - s(:lasgn, :b), - s(:lasgn, :c), - s(:splat))), - s(:call, nil, :p, s(:arglist, s(:lvar, :c))))) - - add_tests("iter_masgn_splat", - "Ruby" => "a { |*c| p(c) }", - "RawParseTree" => [:iter, - [:fcall, :a], - [:masgn, nil, [:dasgn_curr, :c], nil], - [:fcall, :p, [:array, [:dvar, :c]]]], - "ParseTree" => s(:iter, - s(:call, nil, :a, s(:arglist)), - s(:masgn, s(:array, s(:splat, s(:lasgn, :c)))), - s(:call, nil, :p, s(:arglist, s(:lvar, :c))))) - - add_tests("iter_masgn_splat_no_name", - "Ruby" => "a { |*| p(c) }", - "RawParseTree" => [:iter, - [:fcall, :a], - [:masgn, nil, [:splat], nil], - [:fcall, :p, [:array, [:vcall, :c]]]], - "ParseTree" => s(:iter, - s(:call, nil, :a, s(:arglist)), - s(:masgn, s(:array, s(:splat))), - s(:call, nil, :p, - s(:arglist, s(:call, nil, :c, s(:arglist)))))) - - add_tests("iter_shadowed_var", - "Ruby" => "a do |x|\n b do |x|\n puts x\n end\nend", - "RawParseTree" => [:iter, - [:fcall, :a], - [:dasgn_curr, :x], - [:iter, - [:fcall, :b], - [:dasgn, :x], - [:fcall, :puts, [:array, [:dvar, :x]]]]], - "ParseTree" => s(:iter, - s(:call, nil, :a, s(:arglist)), - s(:lasgn, :x), - s(:iter, - s(:call, nil, :b, s(:arglist)), - s(:lasgn, :x), - s(:call, nil, :puts, - s(:arglist, s(:lvar, :x))))), - "Ruby2Ruby" => "a { |x| b { |x| puts(x) } }") - - add_tests("iter_upto", - "Ruby" => "1.upto(3) { |n| puts(n.to_s) }", - "RawParseTree" => [:iter, - [:call, [:lit, 1], :upto, [:array, [:lit, 3]]], - [:dasgn_curr, :n], - [:fcall, :puts, - [:array, [:call, [:dvar, :n], :to_s]]]], - "ParseTree" => s(:iter, - s(:call, s(:lit, 1), :upto, - s(:arglist, s(:lit, 3))), - s(:lasgn, :n), - s(:call, nil, :puts, - s(:arglist, - s(:call, s(:lvar, :n), :to_s, - s(:arglist)))))) - - add_tests("iter_while", - "Ruby" => "argl = 10\nwhile (argl >= 1) do\n puts(\"hello\")\n argl = (argl - 1)\nend\n", - "RawParseTree" => [:block, - [:lasgn, :argl, [:lit, 10]], - [:while, - [:call, [:lvar, :argl], :">=", - [:array, [:lit, 1]]], - [:block, - [:fcall, :puts, [:array, [:str, "hello"]]], - [:lasgn, - :argl, - [:call, [:lvar, :argl], - :"-", [:array, [:lit, 1]]]]], true]], - "ParseTree" => s(:block, - s(:lasgn, :argl, s(:lit, 10)), - s(:while, - s(:call, s(:lvar, :argl), :">=", - s(:arglist, s(:lit, 1))), - s(:block, - s(:call, nil, :puts, - s(:arglist, s(:str, "hello"))), - s(:lasgn, - :argl, - s(:call, s(:lvar, :argl), :"-", - s(:arglist, s(:lit, 1))))), true))) - - add_tests("ivar", - "Ruby" => [Examples, :reader], - "RawParseTree" => [:defn, :reader, [:ivar, :@reader]], - "ParseTree" => s(:defn, :reader, # FIX should be unified? - s(:args), - s(:ivar, :@reader)), - "Ruby2Ruby" => "attr_reader :reader") - - add_tests("lasgn_array", - "Ruby" => "var = [\"foo\", \"bar\"]", - "RawParseTree" => [:lasgn, :var, - [:array, - [:str, "foo"], - [:str, "bar"]]], - "ParseTree" => s(:lasgn, :var, - s(:array, - s(:str, "foo"), - s(:str, "bar")))) - - add_tests("lasgn_call", - "Ruby" => "c = (2 + 3)", - "RawParseTree" => [:lasgn, :c, [:call, [:lit, 2], :+, - [:array, [:lit, 3]]]], - "ParseTree" => s(:lasgn, :c, s(:call, s(:lit, 2), :+, - s(:arglist, s(:lit, 3))))) - - add_tests("lit_bool_false", - "Ruby" => "false", - "RawParseTree" => [:false], - "ParseTree" => s(:false)) - - add_tests("lit_bool_true", - "Ruby" => "true", - "RawParseTree" => [:true], - "ParseTree" => s(:true)) - - add_tests("lit_float", - "Ruby" => "1.1", - "RawParseTree" => [:lit, 1.1], - "ParseTree" => s(:lit, 1.1)) - - add_tests("lit_long", - "Ruby" => "1", - "RawParseTree" => [:lit, 1], - "ParseTree" => s(:lit, 1)) - - add_tests("lit_long_negative", - "Ruby" => "-1", - "RawParseTree" => [:lit, -1], - "ParseTree" => s(:lit, -1)) - - add_tests("lit_range2", - "Ruby" => "(1..10)", - "RawParseTree" => [:lit, 1..10], - "ParseTree" => s(:lit, 1..10)) - - add_tests("lit_range3", - "Ruby" => "(1...10)", - "RawParseTree" => [:lit, 1...10], - "ParseTree" => s(:lit, 1...10)) - -# TODO: discuss and decide which lit we like -# it "converts a regexp to an sexp" do -# "/blah/".to_sexp.should == s(:regex, "blah", 0) -# "/blah/i".to_sexp.should == s(:regex, "blah", 1) -# "/blah/u".to_sexp.should == s(:regex, "blah", 64) -# end - - add_tests("lit_regexp", - "Ruby" => "/x/", - "RawParseTree" => [:lit, /x/], - "ParseTree" => s(:lit, /x/)) - - add_tests("lit_regexp_i_wwtt", - "Ruby" => 'str.split(//i)', - "RawParseTree" => [:call, [:vcall, :str], :split, - [:array, [:lit, //i]]], - "ParseTree" => s(:call, s(:call, nil, :str, s(:arglist)), :split, - s(:arglist, s(:lit, //i)))) - - add_tests("lit_regexp_n", - "Ruby" => "/x/n", # HACK differs on 1.9 - this is easiest - "RawParseTree" => [:lit, /x/n], - "ParseTree" => s(:lit, /x/n), - "Ruby2Ruby" => /x/n.inspect) - - add_tests("lit_regexp_once", - "Ruby" => "/x/o", - "RawParseTree" => [:lit, /x/], - "ParseTree" => s(:lit, /x/), - "Ruby2Ruby" => "/x/") - - add_tests("lit_sym", - "Ruby" => ":x", - "RawParseTree" => [:lit, :x], - "ParseTree" => s(:lit, :x)) - - add_tests("lit_sym_splat", - "Ruby" => ":\"*args\"", - "RawParseTree" => [:lit, :"*args"], - "ParseTree" => s(:lit, :"*args")) - - add_tests("lvar_def_boundary", - "Ruby" => "b = 42\ndef a\n c do\n begin\n do_stuff\n rescue RuntimeError => b\n puts(b)\n end\n end\nend\n", - "RawParseTree" => [:block, - [:lasgn, :b, [:lit, 42]], - [:defn, :a, - [:scope, - [:block, - [:args], - [:iter, - [:fcall, :c], - nil, - [:rescue, - [:vcall, :do_stuff], - [:resbody, - [:array, [:const, :RuntimeError]], - [:block, - [:dasgn_curr, :b, [:gvar, :$!]], - [:fcall, :puts, - [:array, [:dvar, :b]]]]]]]]]]], - "ParseTree" => s(:block, - s(:lasgn, :b, s(:lit, 42)), - s(:defn, :a, - s(:args), - s(:scope, - s(:block, - s(:iter, - s(:call, nil, :c, s(:arglist)), - nil, - s(:rescue, - s(:call, nil, :do_stuff, s(:arglist)), - s(:resbody, - s(:array, - s(:const, :RuntimeError), - s(:lasgn, :b, s(:gvar, :$!))), - s(:call, nil, :puts, - s(:arglist, - s(:lvar, :b))))))))))) - - add_tests("masgn", - "Ruby" => "a, b = c, d", - "RawParseTree" => [:masgn, - [:array, [:lasgn, :a], [:lasgn, :b]], nil, - [:array, [:vcall, :c], [:vcall, :d]]], - "ParseTree" => s(:masgn, - s(:array, s(:lasgn, :a), s(:lasgn, :b)), - s(:array, s(:call, nil, :c, s(:arglist)), - s(:call, nil, :d, s(:arglist))))) - - add_tests("masgn_argscat", - "Ruby" => "a, b, *c = 1, 2, *[3, 4]", - "RawParseTree" => [:masgn, - [:array, [:lasgn, :a], [:lasgn, :b]], - [:lasgn, :c], - [:argscat, - [:array, [:lit, 1], [:lit, 2]], - [:array, [:lit, 3], [:lit, 4]]]], - "ParseTree" => s(:masgn, - s(:array, - s(:lasgn, :a), - s(:lasgn, :b), - s(:splat, s(:lasgn, :c))), - s(:array, - s(:lit, 1), s(:lit, 2), - s(:splat, - s(:array, s(:lit, 3), s(:lit, 4)))))) - - add_tests("masgn_attrasgn", - "Ruby" => "a, b.c = d, e", - "RawParseTree" => [:masgn, - [:array, [:lasgn, :a], - [:attrasgn, [:vcall, :b], :c=]], nil, - [:array, [:vcall, :d], [:vcall, :e]]], - "ParseTree" => s(:masgn, - s(:array, - s(:lasgn, :a), - s(:attrasgn, - s(:call, nil, :b, s(:arglist)), - :c=, s(:arglist))), - s(:array, - s(:call, nil, :d, s(:arglist)), - s(:call, nil, :e, s(:arglist))))) - - add_tests("masgn_attrasgn_array_rhs", - "Ruby" => "a.b, a.c, _ = q", - "RawParseTree" => [:masgn, - [:array, - [:attrasgn, [:vcall, :a], :b=], - [:attrasgn, [:vcall, :a], :c=], - [:lasgn, :_]], nil, - [:to_ary, [:vcall, :q]]], - "ParseTree" => s(:masgn, - s(:array, - s(:attrasgn, - s(:call, nil, :a, s(:arglist)), - :b=, s(:arglist)), - s(:attrasgn, - s(:call, nil, :a, s(:arglist)), - :c=, s(:arglist)), - s(:lasgn, :_)), - s(:to_ary, - s(:call, nil, :q, s(:arglist))))) - - add_tests("masgn_attrasgn_idx", - "Ruby" => "a, i, j = [], 1, 2\na[i], a[j] = a[j], a[i]\n", - "RawParseTree" => [:block, - [:masgn, - [:array, - [:lasgn, :a], [:lasgn, :i], [:lasgn, :j]], nil, - [:array, [:zarray], [:lit, 1], [:lit, 2]]], - [:masgn, - [:array, - [:attrasgn, - [:lvar, :a], :[]=, [:array, [:lvar, :i]]], - [:attrasgn, - [:lvar, :a], :[]=, [:array, [:lvar, :j]]]], - nil, - [:array, - [:call, [:lvar, :a], :[], - [:array, [:lvar, :j]]], - [:call, [:lvar, :a], :[], - [:array, [:lvar, :i]]]]]], - "ParseTree" => s(:block, - s(:masgn, - s(:array, - s(:lasgn, :a), - s(:lasgn, :i), s(:lasgn, :j)), - s(:array, s(:array), s(:lit, 1), s(:lit, 2))), - s(:masgn, - s(:array, - s(:attrasgn, s(:lvar, :a), :[]=, - s(:arglist, s(:lvar, :i))), - s(:attrasgn, s(:lvar, :a), :[]=, - s(:arglist, s(:lvar, :j)))), - s(:array, - s(:call, s(:lvar, :a), :[], - s(:arglist, s(:lvar, :j))), - s(:call, s(:lvar, :a), :[], - s(:arglist, s(:lvar, :i))))))) - - add_tests("masgn_cdecl", - "Ruby" => "A, B, C = 1, 2, 3", - "RawParseTree" => [:masgn, - [:array, [:cdecl, :A], [:cdecl, :B], - [:cdecl, :C]], nil, - [:array, [:lit, 1], [:lit, 2], [:lit, 3]]], - "ParseTree" => s(:masgn, - s(:array, s(:cdecl, :A), s(:cdecl, :B), - s(:cdecl, :C)), - s(:array, s(:lit, 1), s(:lit, 2), s(:lit, 3)))) - - - add_tests("masgn_iasgn", - "Ruby" => "a, @b = c, d", - "RawParseTree" => [:masgn, - [:array, [:lasgn, :a], [:iasgn, :"@b"]], nil, - [:array, [:vcall, :c], [:vcall, :d]]], - "ParseTree" => s(:masgn, - s(:array, s(:lasgn, :a), s(:iasgn, :"@b")), - s(:array, - s(:call, nil, :c, s(:arglist)), - s(:call, nil, :d, s(:arglist))))) - - add_tests("masgn_masgn", - "Ruby" => "a, (b, c) = [1, [2, 3]]", - "RawParseTree" => [:masgn, - [:array, - [:lasgn, :a], - [:masgn, - [:array, - [:lasgn, :b], - [:lasgn, :c]], nil, nil]], - nil, - [:to_ary, - [:array, - [:lit, 1], - [:array, - [:lit, 2], - [:lit, 3]]]]], - "ParseTree" => s(:masgn, - s(:array, - s(:lasgn, :a), - s(:masgn, - s(:array, - s(:lasgn, :b), - s(:lasgn, :c)))), - s(:to_ary, - s(:array, - s(:lit, 1), - s(:array, - s(:lit, 2), - s(:lit, 3)))))) - - add_tests("masgn_splat_lhs", - "Ruby" => "a, b, *c = d, e, f, g", - "RawParseTree" => [:masgn, - [:array, [:lasgn, :a], [:lasgn, :b]], - [:lasgn, :c], - [:array, - [:vcall, :d], [:vcall, :e], - [:vcall, :f], [:vcall, :g]]], - "ParseTree" => s(:masgn, - s(:array, - s(:lasgn, :a), - s(:lasgn, :b), - s(:splat, s(:lasgn, :c))), - s(:array, - s(:call, nil, :d, s(:arglist)), - s(:call, nil, :e, s(:arglist)), - s(:call, nil, :f, s(:arglist)), - s(:call, nil, :g, s(:arglist))))) - - add_tests("masgn_splat_rhs_1", - "Ruby" => "a, b = *c", - "RawParseTree" => [:masgn, - [:array, [:lasgn, :a], [:lasgn, :b]], - nil, - [:splat, [:vcall, :c]]], - "ParseTree" => s(:masgn, - s(:array, - s(:lasgn, :a), - s(:lasgn, :b)), - s(:splat, s(:call, nil, :c, s(:arglist))))) - - add_tests("masgn_splat_rhs_n", - "Ruby" => "a, b = c, d, *e", - "RawParseTree" => [:masgn, - [:array, [:lasgn, :a], [:lasgn, :b]], - nil, - [:argscat, - [:array, [:vcall, :c], [:vcall, :d]], - [:vcall, :e]]], - "ParseTree" => s(:masgn, - s(:array, - s(:lasgn, :a), - s(:lasgn, :b)), - s(:array, - s(:call, nil, :c, s(:arglist)), - s(:call, nil, :d, s(:arglist)), - s(:splat, s(:call, nil, :e, s(:arglist)))))) - - add_tests("masgn_splat_no_name_to_ary", - "Ruby" => "a, b, * = c", - "RawParseTree" => [:masgn, - [:array, [:lasgn, :a], [:lasgn, :b]], - [:splat], - [:to_ary, [:vcall, :c]]], - "ParseTree" => s(:masgn, - s(:array, - s(:lasgn, :a), - s(:lasgn, :b), - s(:splat)), - s(:to_ary, s(:call, nil, :c, s(:arglist))))) - - add_tests("masgn_splat_no_name_trailing", - "Ruby" => "a, b, = c", - "RawParseTree" => [:masgn, - [:array, [:lasgn, :a], [:lasgn, :b]], nil, - [:to_ary, [:vcall, :c]]], - "ParseTree" => s(:masgn, - s(:array, s(:lasgn, :a), s(:lasgn, :b)), - s(:to_ary, s(:call, nil, :c, s(:arglist)))), - "Ruby2Ruby" => "a, b = c") # TODO: check this is right - - add_tests("masgn_splat_to_ary", - "Ruby" => "a, b, *c = d", - "RawParseTree" => [:masgn, - [:array, [:lasgn, :a], [:lasgn, :b]], - [:lasgn, :c], - [:to_ary, [:vcall, :d]]], - "ParseTree" => s(:masgn, - s(:array, - s(:lasgn, :a), - s(:lasgn, :b), - s(:splat, s(:lasgn, :c))), - s(:to_ary, s(:call, nil, :d, s(:arglist))))) - - add_tests("masgn_splat_to_ary2", - "Ruby" => "a, b, *c = d.e(\"f\")", - "RawParseTree" => [:masgn, - [:array, [:lasgn, :a], [:lasgn, :b]], - [:lasgn, :c], - [:to_ary, - [:call, [:vcall, :d], :e, - [:array, [:str, 'f']]]]], - "ParseTree" => s(:masgn, - s(:array, - s(:lasgn, :a), - s(:lasgn, :b), - s(:splat, s(:lasgn, :c))), - s(:to_ary, - s(:call, - s(:call, nil, :d, s(:arglist)), - :e, - s(:arglist, s(:str, 'f')))))) - - add_tests("match", - "Ruby" => "1 if /x/", - "RawParseTree" => [:if, [:match, [:lit, /x/]], [:lit, 1], nil], - "ParseTree" => s(:if, s(:match, s(:lit, /x/)), s(:lit, 1), nil)) - - add_tests("match2", - "Ruby" => "/x/ =~ \"blah\"", - "RawParseTree" => [:match2, [:lit, /x/], [:str, "blah"]], - "ParseTree" => s(:match2, s(:lit, /x/), s(:str, "blah"))) - - add_tests("match3", - "Ruby" => "\"blah\" =~ /x/", - "RawParseTree" => [:match3, [:lit, /x/], [:str, "blah"]], - "ParseTree" => s(:match3, s(:lit, /x/), s(:str, "blah"))) - - add_tests("module", - "Ruby" => "module X\n def y\n # do nothing\n end\nend", - "RawParseTree" => [:module, :X, - [:scope, - [:defn, :y, - [:scope, [:block, [:args], [:nil]]]]]], - "ParseTree" => s(:module, :X, - s(:scope, - s(:defn, :y, - s(:args), - s(:scope, s(:block, s(:nil))))))) - - add_tests("module_scoped", - "Ruby" => "module X::Y\n c\nend", - "RawParseTree" => [:module, [:colon2, [:const, :X], :Y], - [:scope, [:vcall, :c]]], - "ParseTree" => s(:module, s(:colon2, s(:const, :X), :Y), - s(:scope, s(:call, nil, :c, s(:arglist))))) - - add_tests("module_scoped3", - "Ruby" => "module ::Y\n c\nend", - "RawParseTree" => [:module, [:colon3, :Y], [:scope, [:vcall, :c]]], - "ParseTree" => s(:module, - s(:colon3, :Y), - s(:scope, s(:call, nil, :c, s(:arglist))))) - - add_tests("next", - "Ruby" => "loop { next if false }", - "RawParseTree" => [:iter, - [:fcall, :loop], - nil, - [:if, [:false], [:next], nil]], - "ParseTree" => s(:iter, - s(:call, nil, :loop, s(:arglist)), - nil, - s(:if, s(:false), s(:next), nil))) - - add_tests("next_arg", - "Ruby" => "loop { next 42 if false }", - "RawParseTree" => [:iter, - [:fcall, :loop], - nil, - [:if, [:false], [:next, [:lit, 42]], nil]], - "ParseTree" => s(:iter, - s(:call, nil, :loop, s(:arglist)), - nil, - s(:if, s(:false), s(:next, s(:lit, 42)), nil))) - - add_tests("not", - "Ruby" => "(not true)", - "RawParseTree" => [:not, [:true]], - "ParseTree" => s(:not, s(:true))) - - add_tests("nth_ref", - "Ruby" => "$1", - "RawParseTree" => [:nth_ref, 1], - "ParseTree" => s(:nth_ref, 1)) - - add_tests("op_asgn1", - "Ruby" => "b = []\nb[1] ||= 10\nb[2] &&= 11\nb[3] += 12\n", - "RawParseTree" => [:block, - [:lasgn, :b, [:zarray]], - [:op_asgn1, [:lvar, :b], - [:array, [:lit, 1]], :"||", [:lit, 10]], - [:op_asgn1, [:lvar, :b], - [:array, [:lit, 2]], :"&&", [:lit, 11]], - [:op_asgn1, [:lvar, :b], - [:array, [:lit, 3]], :+, [:lit, 12]]], - "ParseTree" => s(:block, - s(:lasgn, :b, s(:array)), - s(:op_asgn1, s(:lvar, :b), - s(:arglist, s(:lit, 1)), :"||", s(:lit, 10)), - s(:op_asgn1, s(:lvar, :b), - s(:arglist, s(:lit, 2)), :"&&", s(:lit, 11)), - s(:op_asgn1, s(:lvar, :b), - s(:arglist, s(:lit, 3)), :+, s(:lit, 12)))) - - add_tests("op_asgn1_ivar", - "Ruby" => "@b = []\n@b[1] ||= 10\n@b[2] &&= 11\n@b[3] += 12\n", - "RawParseTree" => [:block, - [:iasgn, :@b, [:zarray]], - [:op_asgn1, [:ivar, :@b], - [:array, [:lit, 1]], :"||", [:lit, 10]], - [:op_asgn1, [:ivar, :@b], - [:array, [:lit, 2]], :"&&", [:lit, 11]], - [:op_asgn1, [:ivar, :@b], - [:array, [:lit, 3]], :+, [:lit, 12]]], - "ParseTree" => s(:block, - s(:iasgn, :@b, s(:array)), - s(:op_asgn1, s(:ivar, :@b), - s(:arglist, s(:lit, 1)), :"||", s(:lit, 10)), - s(:op_asgn1, s(:ivar, :@b), - s(:arglist, s(:lit, 2)), :"&&", s(:lit, 11)), - s(:op_asgn1, s(:ivar, :@b), - s(:arglist, s(:lit, 3)), :+, s(:lit, 12)))) - - add_tests("op_asgn2", - "Ruby" => "s = Struct.new(:var)\nc = s.new(nil)\nc.var ||= 20\nc.var &&= 21\nc.var += 22\nc.d.e.f ||= 42\n", - "RawParseTree" => [:block, - [:lasgn, :s, - [:call, [:const, :Struct], - :new, [:array, [:lit, :var]]]], - [:lasgn, :c, - [:call, [:lvar, :s], :new, [:array, [:nil]]]], - - [:op_asgn2, [:lvar, :c], :var=, :"||", - [:lit, 20]], - [:op_asgn2, [:lvar, :c], :var=, :"&&", - [:lit, 21]], - [:op_asgn2, [:lvar, :c], :var=, :+, [:lit, 22]], - - [:op_asgn2, - [:call, - [:call, [:lvar, :c], :d], :e], :f=, :"||", - [:lit, 42]]], - "ParseTree" => s(:block, - s(:lasgn, :s, - s(:call, s(:const, :Struct), - :new, s(:arglist, s(:lit, :var)))), - s(:lasgn, :c, - s(:call, s(:lvar, :s), - :new, s(:arglist, s(:nil)))), - s(:op_asgn2, s(:lvar, :c), - :var=, :"||", s(:lit, 20)), - s(:op_asgn2, s(:lvar, :c), - :var=, :"&&", s(:lit, 21)), - s(:op_asgn2, s(:lvar, :c), - :var=, :+, s(:lit, 22)), - s(:op_asgn2, - s(:call, - s(:call, s(:lvar, :c), :d, s(:arglist)), - :e, s(:arglist)), - :f=, :"||", s(:lit, 42)))) - - add_tests("op_asgn2_self", - "Ruby" => "self.Bag ||= Bag.new", - "RawParseTree" => [:op_asgn2, [:self], :"Bag=", :"||", - [:call, [:const, :Bag], :new]], - "ParseTree" => s(:op_asgn2, s(:self), :"Bag=", :"||", - s(:call, s(:const, :Bag), :new, s(:arglist)))) - - add_tests("op_asgn_and", - "Ruby" => "a = 0\na &&= 2\n", - "RawParseTree" => [:block, - [:lasgn, :a, [:lit, 0]], - [:op_asgn_and, - [:lvar, :a], [:lasgn, :a, [:lit, 2]]]], - "ParseTree" => s(:block, - s(:lasgn, :a, s(:lit, 0)), - s(:op_asgn_and, - s(:lvar, :a), s(:lasgn, :a, s(:lit, 2))))) - - add_tests("op_asgn_and_ivar2", - "Ruby" => "@fetcher &&= new(Gem.configuration[:http_proxy])", - "RawParseTree" => [:op_asgn_and, - [:ivar, :@fetcher], - [:iasgn, - :@fetcher, - [:fcall, - :new, - [:array, - [:call, - [:call, [:const, :Gem], :configuration], - :[], - [:array, [:lit, :http_proxy]]]]]]], - "ParseTree" => s(:op_asgn_and, - s(:ivar, :@fetcher), - s(:iasgn, - :@fetcher, - s(:call, nil, - :new, - s(:arglist, - s(:call, - s(:call, s(:const, :Gem), - :configuration, - s(:arglist)), - :[], - s(:arglist, s(:lit, :http_proxy)))))))) - - add_tests("op_asgn_or", - "Ruby" => "a = 0\na ||= 1\n", - "RawParseTree" => [:block, - [:lasgn, :a, [:lit, 0]], - [:op_asgn_or, - [:lvar, :a], [:lasgn, :a, [:lit, 1]]]], - "ParseTree" => s(:block, - s(:lasgn, :a, s(:lit, 0)), - s(:op_asgn_or, - s(:lvar, :a), s(:lasgn, :a, s(:lit, 1))))) - - add_tests("op_asgn_or_block", - "Ruby" => "a ||= begin\n b\n rescue\n c\n end", - "RawParseTree" => [:op_asgn_or, - [:lvar, :a], - [:lasgn, :a, - [:rescue, - [:vcall, :b], - [:resbody, nil, [:vcall, :c]]]]], - "ParseTree" => s(:op_asgn_or, - s(:lvar, :a), - s(:lasgn, :a, - s(:rescue, - s(:call, nil, :b, s(:arglist)), - s(:resbody, s(:array), - s(:call, nil, :c, s(:arglist)))))), - "Ruby2Ruby" => "a ||= b rescue c") - - add_tests("op_asgn_or_ivar", - "Ruby" => "@v ||= { }", - "RawParseTree" => [:op_asgn_or, - [:ivar, :@v], - [:iasgn, :@v, [:hash]]], - "ParseTree" => s(:op_asgn_or, - s(:ivar, :@v), - s(:iasgn, :@v, s(:hash)))) - - add_tests("op_asgn_or_ivar2", - "Ruby" => "@fetcher ||= new(Gem.configuration[:http_proxy])", - "RawParseTree" => [:op_asgn_or, - [:ivar, :@fetcher], - [:iasgn, - :@fetcher, - [:fcall, - :new, - [:array, - [:call, - [:call, [:const, :Gem], :configuration], - :[], - [:array, [:lit, :http_proxy]]]]]]], - "ParseTree" => s(:op_asgn_or, - s(:ivar, :@fetcher), - s(:iasgn, - :@fetcher, - s(:call, nil, :new, - s(:arglist, - s(:call, - s(:call, s(:const, :Gem), - :configuration, - s(:arglist)), - :[], - s(:arglist, s(:lit, :http_proxy)))))))) - - add_tests("or", - "Ruby" => "(a or b)", - "RawParseTree" => [:or, [:vcall, :a], [:vcall, :b]], - "ParseTree" => s(:or, - s(:call, nil, :a, s(:arglist)), - s(:call, nil, :b, s(:arglist)))) - - add_tests("or_big", - "Ruby" => "((a or b) or (c and d))", - "RawParseTree" => [:or, - [:or, [:vcall, :a], [:vcall, :b]], - [:and, [:vcall, :c], [:vcall, :d]]], - "ParseTree" => s(:or, - s(:or, - s(:call, nil, :a, s(:arglist)), - s(:call, nil, :b, s(:arglist))), - s(:and, - s(:call, nil, :c, s(:arglist)), - s(:call, nil, :d, s(:arglist))))) - - add_tests("or_big2", - "Ruby" => "((a || b) || (c && d))", - "RawParseTree" => [:or, - [:or, [:vcall, :a], [:vcall, :b]], - [:and, [:vcall, :c], [:vcall, :d]]], - "ParseTree" => s(:or, - s(:or, - s(:call, nil, :a, s(:arglist)), - s(:call, nil, :b, s(:arglist))), - s(:and, - s(:call, nil, :c, s(:arglist)), - s(:call, nil, :d, s(:arglist)))), - "Ruby2Ruby" => "((a or b) or (c and d))") - - add_tests("parse_floats_as_args", - "Ruby" => "def x(a=0.0,b=0.0)\n a+b\nend", - "RawParseTree" => [:defn, :x, - [:scope, - [:block, - [:args, :a, :b, - [:block, - [:lasgn, :a, [:lit, 0.0]], - [:lasgn, :b, [:lit, 0.0]]]], - [:call, [:lvar, :a], :+, - [:array, [:lvar, :b]]]]]], - "ParseTree" => s(:defn, :x, - s(:args, :a, :b, - s(:block, - s(:lasgn, :a, s(:lit, 0.0)), - s(:lasgn, :b, s(:lit, 0.0)))), - s(:scope, - s(:block, - s(:call, s(:lvar, :a), :+, - s(:arglist, s(:lvar, :b)))))), - "Ruby2Ruby" => "def x(a = 0.0, b = 0.0)\n (a + b)\nend") - - add_tests("postexe", - "Ruby" => "END { 1 }", - "RawParseTree" => [:iter, [:postexe], nil, [:lit, 1]], - "ParseTree" => s(:iter, s(:postexe), nil, s(:lit, 1))) - - add_tests("proc_args_0", - "Ruby" => "proc { || (x + 1) }", - "RawParseTree" => [:iter, - [:fcall, :proc], - 0, - [:call, [:vcall, :x], :+, [:array, [:lit, 1]]]], - "ParseTree" => s(:iter, - s(:call, nil, :proc, s(:arglist)), - 0, - s(:call, - s(:call, nil, :x, s(:arglist)), - :+, - s(:arglist, s(:lit, 1))))) - - add_tests("proc_args_1", - "Ruby" => "proc { |x| (x + 1) }", - "RawParseTree" => [:iter, - [:fcall, :proc], - [:dasgn_curr, :x], - [:call, [:dvar, :x], :+, [:array, [:lit, 1]]]], - "ParseTree" => s(:iter, - s(:call, nil, :proc, s(:arglist)), - s(:lasgn, :x), - s(:call, s(:lvar, :x), :+, - s(:arglist, s(:lit, 1))))) - - add_tests("proc_args_2", - "Ruby" => "proc { |x, y| (x + y) }", - "RawParseTree" => [:iter, - [:fcall, :proc], - [:masgn, [:array, - [:dasgn_curr, :x], - [:dasgn_curr, :y]], nil, nil], - [:call, [:dvar, :x], :+, [:array, [:dvar, :y]]]], - "ParseTree" => s(:iter, - s(:call, nil, :proc, s(:arglist)), - s(:masgn, - s(:array, - s(:lasgn, :x), - s(:lasgn, :y))), - s(:call, s(:lvar, :x), :+, - s(:arglist, s(:lvar, :y))))) - - add_tests("proc_args_no", - "Ruby" => "proc { (x + 1) }", - "RawParseTree" => [:iter, - [:fcall, :proc], - nil, - [:call, [:vcall, :x], :+, [:array, [:lit, 1]]]], - "ParseTree" => s(:iter, - s(:call, nil, :proc, s(:arglist)), - nil, - s(:call, s(:call, nil, :x, s(:arglist)), - :+, s(:arglist, s(:lit, 1))))) - - add_tests("redo", - "Ruby" => "loop { redo if false }", - "RawParseTree" => [:iter, - [:fcall, :loop], nil, - [:if, [:false], [:redo], nil]], - "ParseTree" => s(:iter, - s(:call, nil, :loop, s(:arglist)), - nil, - s(:if, s(:false), s(:redo), nil))) - - # TODO: need a resbody w/ multiple classes and a splat - - add_tests("rescue", - "Ruby" => "blah rescue nil", - "RawParseTree" => [:rescue, - [:vcall, :blah], [:resbody, nil, [:nil]]], - "ParseTree" => s(:rescue, - s(:call, nil, :blah, s(:arglist)), - s(:resbody, s(:array), s(:nil)))) - - add_tests("rescue_block_body", - "Ruby" => "begin\n a\nrescue => e\n c\n d\nend", - "RawParseTree" => [:rescue, - [:vcall, :a], - [:resbody, nil, - [:block, - [:lasgn, :e, [:gvar, :$!]], - [:vcall, :c], - [:vcall, :d]]]], - "ParseTree" => s(:rescue, - s(:call, nil, :a, s(:arglist)), - s(:resbody, - s(:array, s(:lasgn, :e, s(:gvar, :$!))), - s(:block, - s(:call, nil, :c, s(:arglist)), - s(:call, nil, :d, s(:arglist)))))) - - add_tests("rescue_block_body_3", - "Ruby" => "begin\n a\nrescue A\n b\nrescue B\n c\nrescue C\n d\nend", - "RawParseTree" => [:rescue, - [:vcall, :a], - [:resbody, [:array, [:const, :A]], - [:vcall, :b], - [:resbody, [:array, [:const, :B]], - [:vcall, :c], - [:resbody, [:array, [:const, :C]], - [:vcall, :d]]]]], - "ParseTree" => s(:rescue, - s(:call, nil, :a, s(:arglist)), - s(:resbody, s(:array, s(:const, :A)), - s(:call, nil, :b, s(:arglist))), - s(:resbody, s(:array, s(:const, :B)), - s(:call, nil, :c, s(:arglist))), - s(:resbody, s(:array, s(:const, :C)), - s(:call, nil, :d, s(:arglist))))) - - add_tests("rescue_block_body_ivar", - "Ruby" => "begin\n a\nrescue => @e\n c\n d\nend", - "RawParseTree" => [:rescue, - [:vcall, :a], - [:resbody, nil, - [:block, - [:iasgn, :@e, [:gvar, :$!]], - [:vcall, :c], - [:vcall, :d]]]], - "ParseTree" => s(:rescue, - s(:call, nil, :a, s(:arglist)), - s(:resbody, - s(:array, s(:iasgn, :@e, s(:gvar, :$!))), - s(:block, - s(:call, nil, :c, s(:arglist)), - s(:call, nil, :d, s(:arglist)))))) - - add_tests("rescue_block_nada", - "Ruby" => "begin\n blah\nrescue\n # do nothing\nend", - "RawParseTree" => [:rescue, [:vcall, :blah], [:resbody, nil]], - "ParseTree" => s(:rescue, - s(:call, nil, :blah, s(:arglist)), - s(:resbody, s(:array), nil))) - - add_tests("rescue_exceptions", - "Ruby" => "begin\n blah\nrescue RuntimeError => r\n # do nothing\nend", - "RawParseTree" => [:rescue, - [:vcall, :blah], - [:resbody, - [:array, [:const, :RuntimeError]], - [:lasgn, :r, [:gvar, :$!]]]], - "ParseTree" => s(:rescue, - s(:call, nil, :blah, s(:arglist)), - s(:resbody, - s(:array, - s(:const, :RuntimeError), - s(:lasgn, :r, s(:gvar, :$!))), - nil))) - - - add_tests("rescue_iasgn_var_empty", - "Ruby" => "begin\n 1\nrescue => @e\n # do nothing\nend", - "RawParseTree" => [:rescue, - [:lit, 1], - [:resbody, nil, [:iasgn, :@e, [:gvar, :$!]]]], - "ParseTree" => s(:rescue, - s(:lit, 1), - s(:resbody, - s(:array, s(:iasgn, :@e, s(:gvar, :$!))), - nil))) - - add_tests("rescue_lasgn", - "Ruby" => "begin\n 1\nrescue\n var = 2\nend", - "RawParseTree" => [:rescue, - [:lit, 1], - [:resbody, nil, [:lasgn, :var, [:lit, 2]]]], - "ParseTree" => s(:rescue, - s(:lit, 1), - s(:resbody, - s(:array), - s(:lasgn, :var, s(:lit, 2)))), - "Ruby2Ruby" => "1 rescue var = 2") - - add_tests("rescue_lasgn_var", - "Ruby" => "begin\n 1\nrescue => e\n var = 2\nend", - "RawParseTree" => [:rescue, - [:lit, 1], - [:resbody, nil, - [:block, - [:lasgn, :e, [:gvar, :$!]], - [:lasgn, :var, [:lit, 2]]]]], - "ParseTree" => s(:rescue, - s(:lit, 1), - s(:resbody, - s(:array, s(:lasgn, :e, s(:gvar, :$!))), - s(:lasgn, :var, s(:lit, 2))))) - - add_tests("rescue_lasgn_var_empty", - "Ruby" => "begin\n 1\nrescue => e\n # do nothing\nend", - "RawParseTree" => [:rescue, - [:lit, 1], - [:resbody, nil, [:lasgn, :e, [:gvar, :$!]]]], - "ParseTree" => s(:rescue, - s(:lit, 1), - s(:resbody, - s(:array, s(:lasgn, :e, s(:gvar, :$!))), - nil))) - - add_tests("retry", - "Ruby" => "retry", - "RawParseTree" => [:retry], - "ParseTree" => s(:retry)) - - add_tests("return_0", - "Ruby" => "return", - "RawParseTree" => [:return], - "ParseTree" => s(:return)) - - add_tests("return_1", - "Ruby" => "return 1", - "RawParseTree" => [:return, [:lit, 1]], - "ParseTree" => s(:return, s(:lit, 1))) - - add_tests("return_1_splatted", - "Ruby" => "return *1", - "RawParseTree" => [:return, [:svalue, [:splat, [:lit, 1]]]], - "ParseTree" => s(:return, s(:svalue, s(:splat, s(:lit, 1))))) - - add_tests("return_n", - "Ruby" => "return 1, 2, 3", - "RawParseTree" => [:return, [:array, - [:lit, 1], [:lit, 2], [:lit, 3]]], - "ParseTree" => s(:return, s(:array, - s(:lit, 1), s(:lit, 2), s(:lit, 3))), - "Ruby2Ruby" => "return [1, 2, 3]") - - add_tests("sclass", - "Ruby" => "class << self\n 42\nend", - "RawParseTree" => [:sclass, [:self], [:scope, [:lit, 42]]], - "ParseTree" => s(:sclass, s(:self), s(:scope, s(:lit, 42)))) - - add_tests("sclass_trailing_class", - "Ruby" => "class A\n class << self\n a\n end\n class B\n end\nend", - "RawParseTree" => [:class, :A, nil, - [:scope, - [:block, - [:sclass, [:self], [:scope, [:vcall, :a]]], - [:class, :B, nil, [:scope]]]]], - "ParseTree" => s(:class, :A, nil, - s(:scope, - s(:block, - s(:sclass, s(:self), - s(:scope, - s(:call, nil, :a, s(:arglist)))), - s(:class, :B, nil, s(:scope)))))) - - add_tests("splat", - "Ruby" => "def x(*b)\n a(*b)\nend", - "RawParseTree" => [:defn, :x, - [:scope, - [:block, - [:args, :"*b"], - [:fcall, :a, [:splat, [:lvar, :b]]]]]], - "ParseTree" => s(:defn, :x, - s(:args, :"*b"), - s(:scope, - s(:block, - s(:call, nil, :a, - s(:arglist, s(:splat, s(:lvar, :b)))))))) - - add_tests("splat_array", - "Ruby" => "[*[1]]", - "RawParseTree" => [:splat, [:array, [:lit, 1]]], - "ParseTree" => s(:array, s(:splat, s(:array, s(:lit, 1))))) - - add_tests("splat_break", - "Ruby" => "break *[1]", - "RawParseTree" => [:break, [:svalue, [:splat, [:array, [:lit, 1]]]]], - "ParseTree" => s(:break, s(:svalue, s(:splat, s(:array, s(:lit, 1)))))) - - add_tests("splat_break_array", - "Ruby" => "break [*[1]]", - "RawParseTree" => [:break, [:splat, [:array, [:lit, 1]]]], - "ParseTree" => s(:break, s(:array, s(:splat, s(:array, s(:lit, 1)))))) - - add_tests("splat_fcall", - "Ruby" => "meth(*[1])", - "RawParseTree" => [:fcall, :meth, - [:splat, [:array, [:lit, 1]]]], - "ParseTree" => s(:call, nil, :meth, - s(:arglist, s(:splat, s(:array, s(:lit, 1)))))) - - add_tests("splat_fcall_array", - "Ruby" => "meth([*[1]])", - "RawParseTree" => [:fcall, :meth, - [:array, [:splat, [:array, [:lit, 1]]]]], - "ParseTree" => s(:call, nil, :meth, - s(:arglist, - s(:array, s(:splat, s(:array, s(:lit, 1))))))) - - add_tests("splat_lasgn", - "Ruby" => "x = *[1]", - "RawParseTree" => [:lasgn, :x, [:svalue, [:splat, [:array, [:lit, 1]]]]], - "ParseTree" => s(:lasgn, :x, s(:svalue, s(:splat, s(:array, s(:lit, 1)))))) - - add_tests("splat_lasgn_array", - "Ruby" => "x = [*[1]]", - "RawParseTree" => [:lasgn, :x, [:splat, [:array, [:lit, 1]]]], - "ParseTree" => s(:lasgn, :x, s(:array, s(:splat, s(:array, s(:lit, 1)))))) - - add_tests("splat_lit_1", - "Ruby" => "[*1]", - "RawParseTree" => [:splat, [:lit, 1]], # UGH - damn MRI - "ParseTree" => s(:array, s(:splat, s(:lit, 1)))) - - add_tests("splat_lit_n", - "Ruby" => "[1, *2]", - "RawParseTree" => [:argscat, [:array, [:lit, 1]], [:lit, 2]], - "ParseTree" => s(:array, s(:lit, 1), s(:splat, s(:lit, 2)))) - - add_tests("splat_next", - "Ruby" => "next *[1]", - "RawParseTree" => [:next, [:svalue, [:splat, [:array, [:lit, 1]]]]], - "ParseTree" => s(:next, s(:svalue, s(:splat, s(:array, s(:lit, 1)))))) - - add_tests("splat_next_array", - "Ruby" => "next [*[1]]", - "RawParseTree" => [:next, [:splat, [:array, [:lit, 1]]]], - "ParseTree" => s(:next, s(:array, s(:splat, s(:array, s(:lit, 1)))))) - - add_tests("splat_return", - "Ruby" => "return *[1]", - "RawParseTree" => [:return, [:svalue, [:splat, [:array, [:lit, 1]]]]], - "ParseTree" => s(:return, s(:svalue, s(:splat, s(:array, s(:lit, 1)))))) - - add_tests("splat_return_array", - "Ruby" => "return [*[1]]", - "RawParseTree" => [:return, [:splat, [:array, [:lit, 1]]]], - "ParseTree" => s(:return, s(:array, s(:splat, s(:array, s(:lit, 1)))))) - - add_tests("splat_super", - "Ruby" => "super(*[1])", - "RawParseTree" => [:super, [:splat, [:array, [:lit, 1]]]], - "ParseTree" => s(:super, s(:splat, s(:array, s(:lit, 1))))) - - add_tests("splat_super_array", - "Ruby" => "super([*[1]])", - "RawParseTree" => [:super, [:array, [:splat, [:array, [:lit, 1]]]]], - "ParseTree" => s(:super, s(:array, s(:splat, s(:array, s(:lit, 1)))))) - - add_tests("splat_yield", - "Ruby" => "yield(*[1])", - "RawParseTree" => [:yield, [:splat, [:array, [:lit, 1]]]], - "ParseTree" => s(:yield, s(:splat, s(:array, s(:lit, 1))))) - - add_tests("splat_yield_array", - "Ruby" => "yield([*[1]])", - "RawParseTree" => [:yield, [:splat, [:array, [:lit, 1]]], true], - "ParseTree" => s(:yield, s(:array, s(:splat, s(:array, s(:lit, 1)))))) - - add_tests("str", - "Ruby" => '"x"', - "RawParseTree" => [:str, "x"], - "ParseTree" => s(:str, "x")) - - add_tests("str_concat_newline", # FIX? make prettier? possible? - "Ruby" => '"before" \\ - " after"', - "RawParseTree" => [:str, "before after"], - "ParseTree" => s(:str, "before after"), - "Ruby2Ruby" => '"before after"') - - add_tests("str_concat_space", - "Ruby" => '"before" " after"', - "RawParseTree" => [:str, "before after"], - "ParseTree" => s(:str, "before after"), - "Ruby2Ruby" => '"before after"') - - add_tests("str_heredoc", - "Ruby" => "<<'EOM'\n blah\nblah\nEOM", - "RawParseTree" => [:str, " blah\nblah\n"], - "ParseTree" => s(:str, " blah\nblah\n"), - "Ruby2Ruby" => "\" blah\\nblah\\n\"") - - add_tests("str_heredoc_call", - "Ruby" => "<<'EOM'.strip\n blah\nblah\nEOM", - "RawParseTree" => [:call, [:str, " blah\nblah\n"], :strip], - "ParseTree" => s(:call, s(:str, " blah\nblah\n"), - :strip, s(:arglist)), - "Ruby2Ruby" => "\" blah\\nblah\\n\".strip") - - add_tests("str_heredoc_double", - "Ruby" => "a += <<-H1 + b + <<-H2\n first\nH1\n second\nH2", - "RawParseTree" => [:lasgn, :a, - [:call, - [:lvar, :a], - :+, - [:array, - [:call, - [:call, [:str, " first\n"], :+, - [:array, [:vcall, :b]]], - :+, - [:array, [:str, " second\n"]]]]]], - "ParseTree" => s(:lasgn, :a, - s(:call, - s(:lvar, :a), - :+, - s(:arglist, - s(:call, - s(:call, s(:str, " first\n"), :+, - s(:arglist, - s(:call, nil, :b, s(:arglist)))), - :+, - s(:arglist, s(:str, " second\n")))))), - "Ruby2Ruby" => "a = (a + ((\" first\\n\" + b) + \" second\\n\"))") - - add_tests("str_heredoc_empty", # yes... tarded - "Ruby" => "<<'EOM'\nEOM", - "RawParseTree" => [:str, ""], - "ParseTree" => s(:str, ""), - "Ruby2Ruby" => '""') - - add_tests("str_heredoc_indent", - "Ruby" => "<<-EOM\n blah\nblah\n\n EOM", - "RawParseTree" => [:str, " blah\nblah\n\n"], - "ParseTree" => s(:str, " blah\nblah\n\n"), - "Ruby2Ruby" => "\" blah\\nblah\\n\\n\"") - - add_tests("str_interp_file", - "Ruby" => '"file = #{__FILE__}\n"', - "RawParseTree" => [:str, "file = (string)\n"], - "ParseTree" => s(:str, "file = (string)\n"), - "Ruby2Ruby" => '"file = (string)\\n"') - - add_tests("structure_extra_block_for_dvar_scoping", - "Ruby" => "a.b do |c, d|\n unless e.f(c) then\n g = false\n d.h { |x, i| g = true }\n end\nend", - "RawParseTree" => [:iter, - [:call, [:vcall, :a], :b], - [:masgn, [:array, - [:dasgn_curr, :c], - [:dasgn_curr, :d]], nil, nil], - [:if, - [:call, [:vcall, :e], :f, - [:array, [:dvar, :c]]], - nil, - [:block, - [:dasgn_curr, :g, [:false]], - [:iter, - [:call, [:dvar, :d], :h], - [:masgn, [:array, - [:dasgn_curr, :x], - [:dasgn_curr, :i]], nil, nil], - [:dasgn, :g, [:true]]]]]], - "ParseTree" => s(:iter, - s(:call, - s(:call, nil, :a, s(:arglist)), - :b, s(:arglist)), - s(:masgn, s(:array, - s(:lasgn, :c), - s(:lasgn, :d))), - s(:if, - s(:call, s(:call, nil, :e, s(:arglist)), :f, - s(:arglist, s(:lvar, :c))), - nil, - s(:block, - s(:lasgn, :g, s(:false)), - s(:iter, - s(:call, s(:lvar, :d), :h, s(:arglist)), - s(:masgn, s(:array, - s(:lasgn, :x), - s(:lasgn, :i))), - s(:lasgn, :g, s(:true))))))) - - add_tests("structure_remove_begin_1", - "Ruby" => "a << begin\n b\n rescue\n c\n end", - "RawParseTree" => [:call, [:vcall, :a], :<<, - [:array, [:rescue, [:vcall, :b], - [:resbody, nil, [:vcall, :c]]]]], - "ParseTree" => s(:call, s(:call, nil, :a, s(:arglist)), :<<, - s(:arglist, - s(:rescue, - s(:call, nil, :b, s(:arglist)), - s(:resbody, s(:array), - s(:call, nil, :c, s(:arglist)))))), - "Ruby2Ruby" => "(a << b rescue c)") - - add_tests("structure_remove_begin_2", - "Ruby" => "a = if c\n begin\n b\n rescue\n nil\n end\n end\na", - "RawParseTree" => [:block, - [:lasgn, - :a, - [:if, [:vcall, :c], - [:rescue, - [:vcall, :b], - [:resbody, nil, [:nil]]], - nil]], - [:lvar, :a]], - "ParseTree" => s(:block, - s(:lasgn, - :a, - s(:if, s(:call, nil, :c, s(:arglist)), - s(:rescue, s(:call, nil, :b, s(:arglist)), - s(:resbody, - s(:array), s(:nil))), - nil)), - s(:lvar, :a)), - "Ruby2Ruby" => "a = b rescue nil if c\na\n") # OMG that's awesome - - add_tests("structure_unused_literal_wwtt", - "Ruby" => "\"prevent the above from infecting rdoc\"\n\nmodule Graffle\nend", - "RawParseTree" => [:module, :Graffle, [:scope]], - "ParseTree" => s(:module, :Graffle, s(:scope)), - "Ruby2Ruby" => "module Graffle\nend") - - add_tests("super_0", - "Ruby" => "def x\n super()\nend", - "RawParseTree" => [:defn, :x, - [:scope, - [:block, [:args], [:super]]]], - "ParseTree" => s(:defn, :x, - s(:args), - s(:scope, s(:block, s(:super))))) - - add_tests("super_1", - "Ruby" => "def x\n super(4)\nend", - "RawParseTree" => [:defn, :x, - [:scope, - [:block, - [:args], - [:super, [:array, [:lit, 4]]]]]], - "ParseTree" => s(:defn, :x, - s(:args), - s(:scope, - s(:block, - s(:super, s(:lit, 4)))))) - - add_tests("super_1_array", - "Ruby" => "def x\n super([24, 42])\nend", - "RawParseTree" => [:defn, :x, - [:scope, - [:block, - [:args], - [:super, - [:array, - [:array, [:lit, 24], [:lit, 42]]]]]]], - "ParseTree" => s(:defn, :x, - s(:args), - s(:scope, - s(:block, - s(:super, s(:array, - s(:lit, 24), - s(:lit, 42))))))) - - add_tests("super_block_pass", - "Ruby" => "super(a, &b)", - "RawParseTree" => [:block_pass, - [:vcall, :b], [:super, [:array, [:vcall, :a]]]], - "ParseTree" => s(:super, - s(:call, nil, :a, s(:arglist)), - s(:block_pass, - s(:call, nil, :b, s(:arglist))))) - - add_tests("super_block_splat", - "Ruby" => "super(a, *b)", - "RawParseTree" => [:super, - [:argscat, - [:array, [:vcall, :a]], - [:vcall, :b]]], - "ParseTree" => s(:super, - s(:call, nil, :a, s(:arglist)), - s(:splat, s(:call, nil, :b, s(:arglist))))) - - add_tests("super_n", - "Ruby" => "def x\n super(24, 42)\nend", - "RawParseTree" => [:defn, :x, - [:scope, - [:block, - [:args], - [:super, [:array, [:lit, 24], [:lit, 42]]]]]], - "ParseTree" => s(:defn, :x, - s(:args), - s(:scope, - s(:block, - s(:super, s(:lit, 24), s(:lit, 42)))))) - - add_tests("svalue", - "Ruby" => "a = *b", - "RawParseTree" => [:lasgn, :a, [:svalue, [:splat, [:vcall, :b]]]], - "ParseTree" => s(:lasgn, :a, - s(:svalue, - s(:splat, s(:call, nil, :b, s(:arglist)))))) - - add_tests("to_ary", - "Ruby" => "a, b = c", - "RawParseTree" => [:masgn, - [:array, [:lasgn, :a], [:lasgn, :b]], nil, - [:to_ary, [:vcall, :c]]], - "ParseTree" => s(:masgn, - s(:array, s(:lasgn, :a), s(:lasgn, :b)), - s(:to_ary, s(:call, nil, :c, s(:arglist))))) - - add_tests("true", - "Ruby" => "true", - "RawParseTree" => [:true], - "ParseTree" => s(:true)) - - add_tests("undef", - "Ruby" => "undef :x", - "RawParseTree" => [:undef, [:lit, :x]], - "ParseTree" => s(:undef, s(:lit, :x))) - - add_tests("undef_2", - "Ruby" => "undef :x, :y", - "RawParseTree" => [:block, - [:undef, [:lit, :x]], - [:undef, [:lit, :y]]], - "ParseTree" => s(:block, - s(:undef, s(:lit, :x)), - s(:undef, s(:lit, :y))), - "Ruby2Ruby" => "undef :x\nundef :y\n") - - add_tests("undef_3", - "Ruby" => "undef :x, :y, :z", - "RawParseTree" => [:block, - [:undef, [:lit, :x]], - [:undef, [:lit, :y]], - [:undef, [:lit, :z]]], - "ParseTree" => s(:block, - s(:undef, s(:lit, :x)), - s(:undef, s(:lit, :y)), - s(:undef, s(:lit, :z))), - "Ruby2Ruby" => "undef :x\nundef :y\nundef :z\n") - - add_tests("undef_block_1", - "Ruby" => "f1\nundef :x\n", # TODO: don't like the extra return - "RawParseTree" => [:block, - [:vcall, :f1], - [:undef, [:lit, :x]]], - "ParseTree" => s(:block, - s(:call, nil, :f1, s(:arglist)), - s(:undef, s(:lit, :x)))) - - add_tests("undef_block_2", - "Ruby" => "f1\nundef :x, :y", - "RawParseTree" => [:block, - [:vcall, :f1], - [:block, - [:undef, [:lit, :x]], - [:undef, [:lit, :y]], - ]], - "ParseTree" => s(:block, - s(:call, nil, :f1, s(:arglist)), - s(:block, - s(:undef, s(:lit, :x)), - s(:undef, s(:lit, :y)))), - "Ruby2Ruby" => "f1\n(undef :x\nundef :y)\n") - - add_tests("undef_block_3", - "Ruby" => "f1\nundef :x, :y, :z", - "RawParseTree" => [:block, - [:vcall, :f1], - [:block, - [:undef, [:lit, :x]], - [:undef, [:lit, :y]], - [:undef, [:lit, :z]], - ]], - "ParseTree" => s(:block, - s(:call, nil, :f1, s(:arglist)), - s(:block, - s(:undef, s(:lit, :x)), - s(:undef, s(:lit, :y)), - s(:undef, s(:lit, :z)))), - "Ruby2Ruby" => "f1\n(undef :x\nundef :y\nundef :z)\n") - - add_tests("undef_block_3_post", - "Ruby" => "undef :x, :y, :z\nf2", - "RawParseTree" => [:block, - [:undef, [:lit, :x]], - [:undef, [:lit, :y]], - [:undef, [:lit, :z]], - [:vcall, :f2]], - "ParseTree" => s(:block, - s(:undef, s(:lit, :x)), - s(:undef, s(:lit, :y)), - s(:undef, s(:lit, :z)), - s(:call, nil, :f2, s(:arglist))), - "Ruby2Ruby" => "undef :x\nundef :y\nundef :z\nf2\n") - - add_tests("undef_block_wtf", - "Ruby" => "f1\nundef :x, :y, :z\nf2", - "RawParseTree" => [:block, - [:vcall, :f1], - [:block, - [:undef, [:lit, :x]], - [:undef, [:lit, :y]], - [:undef, [:lit, :z]]], - [:vcall, :f2]], - "ParseTree" => s(:block, - s(:call, nil, :f1, s(:arglist)), - s(:block, - s(:undef, s(:lit, :x)), - s(:undef, s(:lit, :y)), - s(:undef, s(:lit, :z))), - s(:call, nil, :f2, s(:arglist))), - "Ruby2Ruby" => "f1\n(undef :x\nundef :y\nundef :z)\nf2\n") - - - add_tests("unless_post", - "Ruby" => "a unless b", - "RawParseTree" => [:if, [:vcall, :b], nil, [:vcall, :a]], - "ParseTree" => s(:if, s(:call, nil, :b, s(:arglist)), nil, - s(:call, nil, :a, s(:arglist)))) - - add_tests("unless_post_not", - "Ruby" => "a unless not b", - "RawParseTree" => [:if, [:vcall, :b], [:vcall, :a], nil], - "ParseTree" => s(:if, s(:call, nil, :b, s(:arglist)), - s(:call, nil, :a, s(:arglist)), nil), - "Ruby2Ruby" => "a if b") - - add_tests("unless_pre", - "Ruby" => "unless b then a end", - "RawParseTree" => [:if, [:vcall, :b], nil, [:vcall, :a]], - "ParseTree" => s(:if, s(:call, nil, :b, s(:arglist)), nil, - s(:call, nil, :a, s(:arglist))), - "Ruby2Ruby" => "a unless b") - - add_tests("unless_pre_not", - "Ruby" => "unless not b then a end", - "RawParseTree" => [:if, [:vcall, :b], [:vcall, :a], nil], - "ParseTree" => s(:if, s(:call, nil, :b, s(:arglist)), - s(:call, nil, :a, s(:arglist)), nil), - "Ruby2Ruby" => "a if b") - - add_tests("until_post", - "Ruby" => "begin\n (1 + 1)\nend until false", - "RawParseTree" => [:until, [:false], - [:call, [:lit, 1], :+, - [:array, [:lit, 1]]], false], - "ParseTree" => s(:until, s(:false), - s(:call, s(:lit, 1), :+, - s(:arglist, s(:lit, 1))), false)) - - add_tests("until_post_not", - "Ruby" => "begin\n (1 + 1)\nend until not true", - "RawParseTree" => [:while, [:true], - [:call, [:lit, 1], :+, - [:array, [:lit, 1]]], false], - "ParseTree" => s(:while, s(:true), - s(:call, s(:lit, 1), :+, - s(:arglist, s(:lit, 1))), false), - "Ruby2Ruby" => "begin\n (1 + 1)\nend while true") - - add_tests("until_pre", - "Ruby" => "until false do\n (1 + 1)\nend", - "RawParseTree" => [:until, [:false], - [:call, [:lit, 1], :+, - [:array, [:lit, 1]]], true], - "ParseTree" => s(:until, s(:false), - s(:call, s(:lit, 1), :+, - s(:arglist, s(:lit, 1))), true)) - - add_tests("until_pre_mod", - "Ruby" => "(1 + 1) until false", - "RawParseTree" => [:until, [:false], - [:call, [:lit, 1], :+, - [:array, [:lit, 1]]], true], - "ParseTree" => s(:until, s(:false), - s(:call, s(:lit, 1), :+, - s(:arglist, s(:lit, 1))), true), - "Ruby2Ruby" => "until false do\n (1 + 1)\nend") - - add_tests("until_pre_not", - "Ruby" => "until not true do\n (1 + 1)\nend", - "RawParseTree" => [:while, [:true], - [:call, [:lit, 1], :+, - [:array, [:lit, 1]]], true], - "ParseTree" => s(:while, s(:true), - s(:call, s(:lit, 1), :+, - s(:arglist, s(:lit, 1))), true), - "Ruby2Ruby" => "while true do\n (1 + 1)\nend") - - add_tests("until_pre_not_mod", - "Ruby" => "(1 + 1) until not true", - "RawParseTree" => [:while, [:true], - [:call, [:lit, 1], :+, - [:array, [:lit, 1]]], true], - "ParseTree" => s(:while, s(:true), - s(:call, s(:lit, 1), :+, - s(:arglist, s(:lit, 1))), true), - "Ruby2Ruby" => "while true do\n (1 + 1)\nend") - - add_tests("valias", - "Ruby" => "alias $y $x", - "RawParseTree" => [:valias, :$y, :$x], - "ParseTree" => s(:valias, :$y, :$x)) - - add_tests("vcall", - "Ruby" => "method", - "RawParseTree" => [:vcall, :method], - "ParseTree" => s(:call, nil, :method, s(:arglist))) - - add_tests("while_post", - "Ruby" => "begin\n (1 + 1)\nend while false", - "RawParseTree" => [:while, [:false], - [:call, [:lit, 1], :+, - [:array, [:lit, 1]]], false], - "ParseTree" => s(:while, s(:false), - s(:call, s(:lit, 1), :+, - s(:arglist, s(:lit, 1))), false)) - - add_tests("while_post2", - "Ruby" => "begin\n (1 + 2)\n (3 + 4)\nend while false", - "RawParseTree" => [:while, [:false], - [:block, - [:call, [:lit, 1], :+, [:array, [:lit, 2]]], - [:call, [:lit, 3], :+, [:array, [:lit, 4]]]], - false], - "ParseTree" => s(:while, s(:false), - s(:block, - s(:call, s(:lit, 1), :+, - s(:arglist, s(:lit, 2))), - s(:call, s(:lit, 3), :+, - s(:arglist, s(:lit, 4)))), - false)) - - add_tests("while_post_not", - "Ruby" => "begin\n (1 + 1)\nend while not true", - "RawParseTree" => [:until, [:true], - [:call, [:lit, 1], :+, - [:array, [:lit, 1]]], false], - "ParseTree" => s(:until, s(:true), - s(:call, s(:lit, 1), :+, - s(:arglist, s(:lit, 1))), false), - "Ruby2Ruby" => "begin\n (1 + 1)\nend until true") - - add_tests("while_pre", - "Ruby" => "while false do\n (1 + 1)\nend", - "RawParseTree" => [:while, [:false], - [:call, [:lit, 1], :+, - [:array, [:lit, 1]]], true], - "ParseTree" => s(:while, s(:false), - s(:call, s(:lit, 1), :+, - s(:arglist, s(:lit, 1))), true)) - - add_tests("while_pre_mod", - "Ruby" => "(1 + 1) while false", - "RawParseTree" => [:while, [:false], - [:call, [:lit, 1], :+, - [:array, [:lit, 1]]], true], - "ParseTree" => s(:while, s(:false), - s(:call, s(:lit, 1), :+, - s(:arglist, s(:lit, 1))), true), - "Ruby2Ruby" => "while false do\n (1 + 1)\nend") # FIX can be one liner - - add_tests("while_pre_nil", - "Ruby" => "while false do\nend", - "RawParseTree" => [:while, [:false], nil, true], - "ParseTree" => s(:while, s(:false), nil, true)) - - add_tests("while_pre_not", - "Ruby" => "while not true do\n (1 + 1)\nend", - "RawParseTree" => [:until, [:true], - [:call, [:lit, 1], :+, - [:array, [:lit, 1]]], true], - "ParseTree" => s(:until, s(:true), - s(:call, s(:lit, 1), :+, - s(:arglist, s(:lit, 1))), true), - "Ruby2Ruby" => "until true do\n (1 + 1)\nend") - - add_tests("while_pre_not_mod", - "Ruby" => "(1 + 1) while not true", - "RawParseTree" => [:until, [:true], - [:call, [:lit, 1], :+, - [:array, [:lit, 1]]], true], - "ParseTree" => s(:until, s(:true), - s(:call, s(:lit, 1), :+, - s(:arglist, s(:lit, 1))), true), - "Ruby2Ruby" => "until true do\n (1 + 1)\nend") # FIX - - add_tests("xstr", - "Ruby" => "`touch 5`", - "RawParseTree" => [:xstr, 'touch 5'], - "ParseTree" => s(:xstr, 'touch 5')) - - add_tests("yield_0", - "Ruby" => "yield", - "RawParseTree" => [:yield], - "ParseTree" => s(:yield)) - - add_tests("yield_1", - "Ruby" => "yield(42)", - "RawParseTree" => [:yield, [:lit, 42]], - "ParseTree" => s(:yield, s(:lit, 42))) - - add_tests("yield_array_0", - "Ruby" => "yield([])", - "RawParseTree" => [:yield, [:zarray], true], - "ParseTree" => s(:yield, s(:array))) - - add_tests("yield_array_1", - "Ruby" => "yield([42])", - "RawParseTree" => [:yield, [:array, [:lit, 42]], true], - "ParseTree" => s(:yield, s(:array, s(:lit, 42)))) - - add_tests("yield_array_n", - "Ruby" => "yield([42, 24])", - "RawParseTree" => [:yield, [:array, [:lit, 42], [:lit, 24]], true], - "ParseTree" => s(:yield, s(:array, s(:lit, 42), s(:lit, 24)))) - - add_tests("yield_n", - "Ruby" => "yield(42, 24)", - "RawParseTree" => [:yield, [:array, [:lit, 42], [:lit, 24]]], - "ParseTree" => s(:yield, s(:lit, 42), s(:lit, 24))) - - add_tests("zarray", - "Ruby" => "a = []", - "RawParseTree" => [:lasgn, :a, [:zarray]], - "ParseTree" => s(:lasgn, :a, s(:array))) - - add_tests("zsuper", - "Ruby" => "def x\n super\nend", - "RawParseTree" => [:defn, :x, - [:scope, [:block, [:args], [:zsuper]]]], - "ParseTree" => s(:defn, :x, s(:args), - s(:scope, s(:block, s(:zsuper))))) -end diff --git a/Tests/Libraries/ParseTreeTests/something.rb b/Tests/Libraries/ParseTreeTests/something.rb deleted file mode 100644 index fadfc2a0f..000000000 --- a/Tests/Libraries/ParseTreeTests/something.rb +++ /dev/null @@ -1,53 +0,0 @@ - -class Something - - def self.classmethod - 1 + 1 - end - - # Other edge cases: - - def opt_args(arg1, arg2 = 42, *args) - arg3 = arg1 * arg2 * 7 - puts(arg3.to_s) - return "foo" - end - - def multi_args(arg1, arg2) - arg3 = arg1 * arg2 * 7 - puts(arg3.to_s) - return "foo" - end - - def unknown_args(arg1, arg2) - # does nothing - return arg1 - end - - def determine_args - 5 == unknown_args(4, "known") - end - - # TODO: sort list - def bbegin - begin - 1 - rescue SyntaxError => e1 - 2 - rescue Exception => e2 - 3 - else - 4 - ensure - 5 - end - end - - def bbegin_no_exception - begin - 5 - rescue - 6 - end - end -end diff --git a/Tests/Libraries/ParseTreeTests/test_parse_tree.rb b/Tests/Libraries/ParseTreeTests/test_parse_tree.rb deleted file mode 100644 index 6fb5d3393..000000000 --- a/Tests/Libraries/ParseTreeTests/test_parse_tree.rb +++ /dev/null @@ -1,259 +0,0 @@ -#!/usr/local/bin/ruby -w - -dir = File.expand_path "~/.ruby_inline" -if test ?d, dir then - require 'fileutils' - puts "nuking #{dir}" - # force removal, Windoze is bitching at me, something to hunt later... - FileUtils.rm_r dir, :force => true -end - -require 'minitest/autorun' -require 'parse_tree' -require 'pt_testcase' -require 'test/something' - -class SomethingWithInitialize - def initialize; end # this method is private - protected - def protected_meth; end -end - -class RawParseTree - def process(input, verbose = nil) # TODO: remove - - test_method = caller[0][/\`(.*)\'/, 1] - verbose = test_method =~ /mri_verbose_flag/ ? true : nil - - # um. kinda stupid, but cleaner - case input - when Array then - ParseTree.translate(*input) - else - self.parse_tree_for_string(input, '(string)', 1, verbose).first - end - end -end - -class TestRawParseTree < ParseTreeTestCase - def setup - super - @processor = RawParseTree.new(false) - end - - def test_parse_tree_for_string_with_newlines - @processor = RawParseTree.new(true) - actual = @processor.parse_tree_for_string "1 +\n nil", 'test.rb', 5 - expected = [[:newline, 6, "test.rb", - [:call, [:lit, 1], :+, [:array, [:nil]]]]] - - assert_equal expected, actual - end - - def test_class_initialize - expected = [[:class, :SomethingWithInitialize, [:const, :Object], - [:defn, :initialize, [:scope, [:block, [:args], [:nil]]]], - [:defn, :protected_meth, [:scope, [:block, [:args], [:nil]]]], - ]] - tree = @processor.parse_tree SomethingWithInitialize - assert_equal expected, tree - end - - def test_class_translate_string - str = "class A; def a; end; end" - - sexp = ParseTree.translate str - - expected = [:class, :A, nil, - [:scope, - [:defn, :a, [:scope, [:block, [:args], [:nil]]]]]] - - assert_equal expected, sexp - end - - def test_class_translate_string_method - str = "class A; def a; end; def b; end; end" - - sexp = ParseTree.translate str, :a - - expected = [:defn, :a, [:scope, [:block, [:args], [:nil]]]] - - assert_equal expected, sexp - end - - def test_parse_tree_for_string - actual = @processor.parse_tree_for_string '1 + nil', '(string)', 1 - expected = [[:call, [:lit, 1], :+, [:array, [:nil]]]] - - assert_equal expected, actual - end - - def test_parse_tree_for_str - actual = @processor.parse_tree_for_str '1 + nil', '(string)', 1 - expected = [[:call, [:lit, 1], :+, [:array, [:nil]]]] - - assert_equal expected, actual - end - - @@self_classmethod = [:defs, - [:self], :classmethod, - [:scope, - [:block, - [:args], - [:call, [:lit, 1], :+, [:array, [:lit, 1]]]]]] - - @@missing = [nil] - - @@opt_args = [:defn, :opt_args, - [:scope, - [:block, - [:args, :arg1, :arg2, :"*args", - [:block, [:lasgn, :arg2, [:lit, 42]]]], - [:lasgn, :arg3, - [:call, - [:call, - [:lvar, :arg1], - :*, - [:array, [:lvar, :arg2]]], - :*, - [:array, [:lit, 7]]]], - [:fcall, :puts, [:array, [:call, [:lvar, :arg3], :to_s]]], - [:return, - [:str, "foo"]]]]] - - @@multi_args = [:defn, :multi_args, - [:scope, - [:block, - [:args, :arg1, :arg2], - [:lasgn, :arg3, - [:call, - [:call, - [:lvar, :arg1], - :*, - [:array, [:lvar, :arg2]]], - :*, - [:array, [:lit, 7]]]], - [:fcall, :puts, [:array, [:call, [:lvar, :arg3], :to_s]]], - [:return, - [:str, "foo"]]]]] - - @@unknown_args = [:defn, :unknown_args, - [:scope, - [:block, - [:args, :arg1, :arg2], - [:return, [:lvar, :arg1]]]]] - - @@bbegin = [:defn, :bbegin, - [:scope, - [:block, - [:args], - [:ensure, - [:rescue, - [:lit, 1], - [:resbody, - [:array, [:const, :SyntaxError]], - [:block, [:lasgn, :e1, [:gvar, :$!]], [:lit, 2]], - [:resbody, - [:array, [:const, :Exception]], - [:block, [:lasgn, :e2, [:gvar, :$!]], [:lit, 3]]]], - [:lit, 4]], - [:lit, 5]]]]] - - @@bbegin_no_exception = [:defn, :bbegin_no_exception, - [:scope, - [:block, - [:args], - [:rescue, - [:lit, 5], - [:resbody, nil, [:lit, 6]]]]]] - - @@determine_args = [:defn, :determine_args, - [:scope, - [:block, - [:args], - [:call, - [:lit, 5], - :==, - [:array, - [:fcall, - :unknown_args, - [:array, [:lit, 4], [:str, "known"]]]]]]]] - - @@attrasgn = [:defn, - :attrasgn, - [:scope, - [:block, - [:args], - [:attrasgn, [:lit, 42], :method=, [:array, [:vcall, :y]]], - [:attrasgn, - [:self], - :type=, - [:array, [:call, [:vcall, :other], :type]]]]]] - - @@__all = [:class, :Something, [:const, :Object]] - - Something.instance_methods(false).sort.each do |meth| - if class_variables.include?("@@#{meth}") then - @@__all << eval("@@#{meth}") - eval "def test_#{meth}; assert_equal @@#{meth}, @processor.parse_tree_for_method(Something, :#{meth}, false, false); end" - else - eval "def test_#{meth}; flunk \"You haven't added @@#{meth} yet\"; end" - end - end - - Something.singleton_methods.sort.each do |meth| - next if meth =~ /yaml/ # rubygems introduced a bug - if class_variables.include?("@@self_#{meth}") then - @@__all << eval("@@self_#{meth}") - eval "def test_self_#{meth}; assert_equal @@self_#{meth}, @processor.parse_tree_for_method(Something, :#{meth}, true); end" - else - eval "def test_self_#{meth}; flunk \"You haven't added @@self_#{meth} yet\"; end" - end - end - - def test_missing - assert_equal(@@missing, - @processor.parse_tree_for_method(Something, :missing), - "Must return #{@@missing.inspect} for missing methods") - end - - def test_whole_class - assert_equal([@@__all], - @processor.parse_tree(Something), - "Must return a lot of shit") - end -end - -class TestParseTree < ParseTreeTestCase - def setup - super - @processor = ParseTree.new(false) - end - - def test_process_string - actual = @processor.process '1 + nil' - expected = s(:call, s(:lit, 1), :+, s(:arglist, s(:nil))) - - assert_equal expected, actual - - actual = @processor.process 'puts 42' - expected = s(:call, nil, :puts, s(:arglist, s(:lit, 42))) - - assert_equal expected, actual - end - - def test_process_string_newlines - @processor = ParseTree.new(true) - actual = @processor.process "1 +\n nil", false, 'test.rb', 5 - expected = s(:newline, 6, "test.rb", - s(:call, s(:lit, 1), :+, s(:arglist, s(:nil)))) - - assert_equal expected, actual - end - - # TODO: test_process_proc ? - # TODO: test_process_method ? - # TODO: test_process_class ? - # TODO: test_process_module ? - -end diff --git a/Tests/Libraries/ParseTreeTests/test_parse_tree_extensions.rb b/Tests/Libraries/ParseTreeTests/test_parse_tree_extensions.rb deleted file mode 100644 index b12a546de..000000000 --- a/Tests/Libraries/ParseTreeTests/test_parse_tree_extensions.rb +++ /dev/null @@ -1,107 +0,0 @@ -require 'minitest/autorun' -require 'parse_tree' -require 'parse_tree_extensions' -require 'tmpdir' - -$: << "../../ruby2ruby/dev/lib" # unoffical dependency - user responsibility -require 'ruby2ruby' - -class R2RTestCase < MiniTest::Unit::TestCase - def test_proc_to_ruby - util_setup_inline - block = proc { puts "something" } - assert_equal 'proc { puts("something") }', block.to_ruby - end - - # TODO: bus error -# def test_proc_to_ruby_args_0 -# util_setup_inline -# block = proc { || puts 42 } -# assert_equal 'proc { || puts(42) }', block.to_ruby -# end - - def test_proc_to_ruby_args_1 - util_setup_inline - block = proc { |x| puts x } - assert_equal 'proc { |x| puts(x) }', block.to_ruby - end - - def test_proc_to_ruby_args_n - util_setup_inline - block = proc { |x| puts x } - assert_equal 'proc { |x| puts(x) }', block.to_ruby - end - - def test_proc_to_sexp - util_setup_inline - p = proc { 1 + 1 } - s = s(:iter, - s(:call, nil, :proc, s(:arglist)), - nil, - s(:call, s(:lit, 1), :+, s(:arglist, s(:lit, 1)))) - assert_equal s, p.to_sexp - end - - # TODO: bus error -# def test_proc_to_sexp_args_0 -# util_setup_inline -# p = proc { || 1 + 1 } -# s = s(:iter, -# s(:call, nil, :proc, s(:arglist)), -# nil, -# s(:call, s(:lit, 1), :+, s(:arglist, s(:lit, 1)))) -# assert_equal s, p.to_sexp -# end - - def test_proc_to_sexp_args_1 - util_setup_inline - p = proc {|x| puts x } - s = s(:iter, - s(:call, nil, :proc, s(:arglist)), - s(:lasgn, :x), - s(:call, nil, :puts, s(:arglist, s(:lvar, :x)))) - - assert_equal s, p.to_sexp - end - - def test_proc_to_sexp_args_n - util_setup_inline - p = proc {|x, y| puts x + y } - s = s(:iter, - s(:call, nil, :proc, s(:arglist)), - s(:masgn, s(:array, s(:lasgn, :x), s(:lasgn, :y))), - s(:call, nil, :puts, - s(:arglist, s(:call, s(:lvar, :x), :+, s(:arglist, s(:lvar, :y)))))) - - assert_equal s, p.to_sexp - end - - def test_parse_tree_for_proc # TODO: move? - p = proc {|a, b, c|} - s = s(:iter, - s(:call, nil, :proc, s(:arglist)), - s(:masgn, s(:array, s(:lasgn, :a), s(:lasgn, :b), s(:lasgn, :c)))) - - pt = ParseTree.new(false) - u = Unifier.new - sexp = pt.parse_tree_for_proc p - - sexp = u.process(sexp) - - assert_equal s, sexp - end - - def test_unbound_method_to_ruby - util_setup_inline - r = "proc { ||\n util_setup_inline\n p = proc { (1 + 1) }\n s = s(:iter, s(:call, nil, :proc, s(:arglist)), nil, s(:call, s(:lit, 1), :+, s(:arglist, s(:lit, 1))))\n assert_equal(s, p.to_sexp)\n}" - m = self.class.instance_method(:test_proc_to_sexp) - - assert_equal r, m.to_ruby - end - - def util_setup_inline - @rootdir = File.join(Dir.tmpdir, "test_ruby_to_ruby.#{$$}") - Dir.mkdir @rootdir, 0700 unless test ?d, @rootdir - ENV['INLINEDIR'] = @rootdir - end -end diff --git a/Tests/Libraries/ParseTreeTests/test_unified_ruby.rb b/Tests/Libraries/ParseTreeTests/test_unified_ruby.rb deleted file mode 100644 index b85191368..000000000 --- a/Tests/Libraries/ParseTreeTests/test_unified_ruby.rb +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/local/bin/ruby -w - -$TESTING = true - -require 'minitest/autorun' if $0 == __FILE__ unless defined? $ZENTEST and $ZENTEST -require 'test/unit/testcase' -require 'sexp' -require 'sexp_processor' -require 'unified_ruby' - -class TestUnifier < MiniTest::Unit::TestCase - def test_pre_fcall - u = PreUnifier.new - - input = [:fcall, :block_given?] - expect = s(:fcall, :block_given?, s(:arglist)) - - assert_equal expect, u.process(input) - - input = [:fcall, :m, [:array, [:lit, 42]]] - expect = s(:fcall, :m, s(:arglist, s(:lit, 42))) - - assert_equal expect, u.process(input) - end - - def test_pre_call - u = PreUnifier.new - - input = [:call, [:self], :method] - expect = s(:call, s(:self), :method, s(:arglist)) - - assert_equal expect, u.process(input) - - input = [:fcall, :m, [:array, [:lit, 42]]] - expect = s(:fcall, :m, s(:arglist, s(:lit, 42))) - - assert_equal expect, u.process(input) - end - - def test_process_bmethod - u = Unifier.new - - raw = [:defn, :myproc3, - [:bmethod, - [:masgn, [:array, - [:dasgn_curr, :a], - [:dasgn_curr, :b], - [:dasgn_curr, :c]], - nil, nil]]] - - s = s(:defn, :myproc3, - s(:args, :a, :b, :c), - s(:scope, s(:block))) - - assert_equal s, u.process(raw) - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/MIT-LICENSE b/Tests/Libraries/Rails-3.0.0/actionmailer/MIT-LICENSE deleted file mode 100644 index 77d558ab8..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/MIT-LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -Copyright (c) 2004-2010 David Heinemeier Hansson - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/abstract_unit.rb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/abstract_unit.rb deleted file mode 100644 index 3299bb667..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/abstract_unit.rb +++ /dev/null @@ -1,80 +0,0 @@ -# Pathname has a warning, so require it first while silencing -# warnings to shut it up. -# -# Also, in 1.9, Bundler creates warnings due to overriding -# Rubygems methods -begin - old, $VERBOSE = $VERBOSE, nil - require 'pathname' - require File.expand_path('../../../load_paths', __FILE__) -ensure - $VERBOSE = old -end - -require 'active_support/core_ext/kernel/reporting' - -require 'active_support/core_ext/string/encoding' -if "ruby".encoding_aware? - # These are the normal settings that will be set up by Railties - # TODO: Have these tests support other combinations of these values - silence_warnings do - Encoding.default_internal = "UTF-8" - Encoding.default_external = "UTF-8" - end -end - -silence_warnings do - # These external dependencies have warnings :/ - require 'text/format' - require 'mail' -end - -lib = File.expand_path("#{File.dirname(__FILE__)}/../lib") -$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib) - -require 'test/unit' -require 'action_mailer' -require 'action_mailer/test_case' - -# Show backtraces for deprecated behavior for quicker cleanup. -ActiveSupport::Deprecation.debug = true - -# Bogus template processors -ActionView::Template.register_template_handler :haml, lambda { |template| "Look its HAML!".inspect } -ActionView::Template.register_template_handler :bak, lambda { |template| "Lame backup".inspect } - -FIXTURE_LOAD_PATH = File.expand_path('fixtures', File.dirname(__FILE__)) -ActionMailer::Base.view_paths = FIXTURE_LOAD_PATH - -class MockSMTP - def self.deliveries - @@deliveries - end - - def initialize - @@deliveries = [] - end - - def sendmail(mail, from, to) - @@deliveries << [mail, from, to] - end - - def start(*args) - yield self - end -end - -class Net::SMTP - def self.new(*args) - MockSMTP.new - end -end - -def set_delivery_method(method) - @old_delivery_method = ActionMailer::Base.delivery_method - ActionMailer::Base.delivery_method = method -end - -def restore_delivery_method - ActionMailer::Base.delivery_method = @old_delivery_method -end diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/base_test.rb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/base_test.rb deleted file mode 100644 index 081fe5c30..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/base_test.rb +++ /dev/null @@ -1,564 +0,0 @@ -# encoding: utf-8 -require 'abstract_unit' -require 'active_support/time' - -require 'mailers/base_mailer' -require 'mailers/proc_mailer' -require 'mailers/asset_mailer' - -class BaseTest < ActiveSupport::TestCase - # TODO Add some tests for implicity layout render and url helpers - # so we can get rid of old base tests altogether with old base. - - def teardown - ActionMailer::Base.asset_host = nil - ActionMailer::Base.assets_dir = nil - end - - test "method call to mail does not raise error" do - assert_nothing_raised { BaseMailer.welcome } - end - - # Basic mail usage without block - test "mail() should set the headers of the mail message" do - email = BaseMailer.welcome - assert_equal(['system@test.lindsaar.net'], email.to) - assert_equal(['jose@test.plataformatec.com'], email.from) - assert_equal('The first email on new API!', email.subject) - end - - test "mail() with from overwrites the class level default" do - email = BaseMailer.welcome(:from => 'someone@example.com', - :to => 'another@example.org') - assert_equal(['someone@example.com'], email.from) - assert_equal(['another@example.org'], email.to) - end - - test "mail() with bcc, cc, content_type, charset, mime_version, reply_to and date" do - @time = Time.now.beginning_of_day.to_datetime - email = BaseMailer.welcome(:bcc => 'bcc@test.lindsaar.net', - :cc => 'cc@test.lindsaar.net', - :content_type => 'multipart/mixed', - :charset => 'iso-8559-1', - :mime_version => '2.0', - :reply_to => 'reply-to@test.lindsaar.net', - :date => @time) - assert_equal(['bcc@test.lindsaar.net'], email.bcc) - assert_equal(['cc@test.lindsaar.net'], email.cc) - assert_equal('multipart/mixed; charset=iso-8559-1', email.content_type) - assert_equal('iso-8559-1', email.charset) - assert_equal('2.0', email.mime_version) - assert_equal(['reply-to@test.lindsaar.net'], email.reply_to) - assert_equal(@time, email.date) - end - - test "mail() renders the template using the method being processed" do - email = BaseMailer.welcome - assert_equal("Welcome", email.body.encoded) - end - - test "can pass in :body to the mail method hash" do - email = BaseMailer.welcome(:body => "Hello there") - assert_equal("text/plain", email.mime_type) - assert_equal("Hello there", email.body.encoded) - end - - test "should set template content type if mail has only one part" do - mail = BaseMailer.html_only - assert_equal('text/html', mail.mime_type) - mail = BaseMailer.plain_text_only - assert_equal('text/plain', mail.mime_type) - end - - # Custom headers - test "custom headers" do - email = BaseMailer.welcome - assert_equal("Not SPAM", email['X-SPAM'].decoded) - end - - test "deprecated non-String custom headers" do - email = assert_deprecated { BaseMailer.welcome_with_fixnum_header } - assert_equal("2", email['X-SPAM-COUNT'].decoded) - end - - test "can pass random headers in as a hash to mail" do - hash = {'X-Special-Domain-Specific-Header' => "SecretValue", - 'In-Reply-To' => '1234@mikel.me.com' } - mail = BaseMailer.welcome(hash) - assert_equal('SecretValue', mail['X-Special-Domain-Specific-Header'].decoded) - assert_equal('1234@mikel.me.com', mail['In-Reply-To'].decoded) - end - - test "can pass random headers in as a hash to headers" do - hash = {'X-Special-Domain-Specific-Header' => "SecretValue", - 'In-Reply-To' => '1234@mikel.me.com' } - mail = BaseMailer.welcome_with_headers(hash) - assert_equal('SecretValue', mail['X-Special-Domain-Specific-Header'].decoded) - assert_equal('1234@mikel.me.com', mail['In-Reply-To'].decoded) - end - - # Attachments - test "attachment with content" do - email = BaseMailer.attachment_with_content - assert_equal(1, email.attachments.length) - assert_equal('invoice.pdf', email.attachments[0].filename) - assert_equal('This is test File content', email.attachments['invoice.pdf'].decoded) - end - - test "attachment gets content type from filename" do - email = BaseMailer.attachment_with_content - assert_equal('invoice.pdf', email.attachments[0].filename) - end - - test "attachment with hash" do - email = BaseMailer.attachment_with_hash - assert_equal(1, email.attachments.length) - assert_equal('invoice.jpg', email.attachments[0].filename) - expected = "\312\213\254\232)b" - expected.force_encoding(Encoding::BINARY) if '1.9'.respond_to?(:force_encoding) - assert_equal expected, email.attachments['invoice.jpg'].decoded - end - - test "attachment with hash using default mail encoding" do - email = BaseMailer.attachment_with_hash_default_encoding - assert_equal(1, email.attachments.length) - assert_equal('invoice.jpg', email.attachments[0].filename) - expected = "\312\213\254\232)b" - expected.force_encoding(Encoding::BINARY) if '1.9'.respond_to?(:force_encoding) - assert_equal expected, email.attachments['invoice.jpg'].decoded - end - - test "sets mime type to multipart/mixed when attachment is included" do - email = BaseMailer.attachment_with_content - assert_equal(1, email.attachments.length) - assert_equal("multipart/mixed", email.mime_type) - end - - test "adds the rendered template as part" do - email = BaseMailer.attachment_with_content - assert_equal(2, email.parts.length) - assert_equal("multipart/mixed", email.mime_type) - assert_equal("text/html", email.parts[0].mime_type) - assert_equal("Attachment with content", email.parts[0].body.encoded) - assert_equal("application/pdf", email.parts[1].mime_type) - assert_equal("VGhpcyBpcyB0ZXN0IEZpbGUgY29udGVudA==\r\n", email.parts[1].body.encoded) - end - - test "adds the given :body as part" do - email = BaseMailer.attachment_with_content(:body => "I'm the eggman") - assert_equal(2, email.parts.length) - assert_equal("multipart/mixed", email.mime_type) - assert_equal("text/plain", email.parts[0].mime_type) - assert_equal("I'm the eggman", email.parts[0].body.encoded) - assert_equal("application/pdf", email.parts[1].mime_type) - assert_equal("VGhpcyBpcyB0ZXN0IEZpbGUgY29udGVudA==\r\n", email.parts[1].body.encoded) - end - - test "can embed an inline attachment" do - email = BaseMailer.inline_attachment - # Need to call #encoded to force the JIT sort on parts - email.encoded - assert_equal(2, email.parts.length) - assert_equal("multipart/related", email.mime_type) - assert_equal("multipart/alternative", email.parts[0].mime_type) - assert_equal("text/plain", email.parts[0].parts[0].mime_type) - assert_equal("text/html", email.parts[0].parts[1].mime_type) - assert_equal("logo.png", email.parts[1].filename) - end - - # Defaults values - test "uses default charset from class" do - with_default BaseMailer, :charset => "US-ASCII" do - email = BaseMailer.welcome - assert_equal("US-ASCII", email.charset) - - email = BaseMailer.welcome(:charset => "iso-8559-1") - assert_equal("iso-8559-1", email.charset) - end - end - - test "uses default content type from class" do - with_default BaseMailer, :content_type => "text/html" do - email = BaseMailer.welcome - assert_equal("text/html", email.mime_type) - - email = BaseMailer.welcome(:content_type => "text/plain") - assert_equal("text/plain", email.mime_type) - end - end - - test "uses default mime version from class" do - with_default BaseMailer, :mime_version => "2.0" do - email = BaseMailer.welcome - assert_equal("2.0", email.mime_version) - - email = BaseMailer.welcome(:mime_version => "1.0") - assert_equal("1.0", email.mime_version) - end - end - - test "uses random default headers from class" do - with_default BaseMailer, "X-Custom" => "Custom" do - email = BaseMailer.welcome - assert_equal("Custom", email["X-Custom"].decoded) - end - end - - test "subject gets default from I18n" do - BaseMailer.default :subject => nil - email = BaseMailer.welcome(:subject => nil) - assert_equal "Welcome", email.subject - - I18n.backend.store_translations('en', :base_mailer => {:welcome => {:subject => "New Subject!"}}) - email = BaseMailer.welcome(:subject => nil) - assert_equal "New Subject!", email.subject - end - - test "translations are scoped properly" do - I18n.backend.store_translations('en', :base_mailer => {:email_with_translations => {:greet_user => "Hello %{name}!"}}) - email = BaseMailer.email_with_translations - assert_equal 'Hello lifo!', email.body.encoded - end - - # Implicit multipart - test "implicit multipart" do - email = BaseMailer.implicit_multipart - assert_equal(2, email.parts.size) - assert_equal("multipart/alternative", email.mime_type) - assert_equal("text/plain", email.parts[0].mime_type) - assert_equal("TEXT Implicit Multipart", email.parts[0].body.encoded) - assert_equal("text/html", email.parts[1].mime_type) - assert_equal("HTML Implicit Multipart", email.parts[1].body.encoded) - end - - test "implicit multipart with sort order" do - order = ["text/html", "text/plain"] - with_default BaseMailer, :parts_order => order do - email = BaseMailer.implicit_multipart - assert_equal("text/html", email.parts[0].mime_type) - assert_equal("text/plain", email.parts[1].mime_type) - - email = BaseMailer.implicit_multipart(:parts_order => order.reverse) - assert_equal("text/plain", email.parts[0].mime_type) - assert_equal("text/html", email.parts[1].mime_type) - end - end - - test "implicit multipart with attachments creates nested parts" do - email = BaseMailer.implicit_multipart(:attachments => true) - assert_equal("application/pdf", email.parts[0].mime_type) - assert_equal("multipart/alternative", email.parts[1].mime_type) - assert_equal("text/plain", email.parts[1].parts[0].mime_type) - assert_equal("TEXT Implicit Multipart", email.parts[1].parts[0].body.encoded) - assert_equal("text/html", email.parts[1].parts[1].mime_type) - assert_equal("HTML Implicit Multipart", email.parts[1].parts[1].body.encoded) - end - - test "implicit multipart with attachments and sort order" do - order = ["text/html", "text/plain"] - with_default BaseMailer, :parts_order => order do - email = BaseMailer.implicit_multipart(:attachments => true) - assert_equal("application/pdf", email.parts[0].mime_type) - assert_equal("multipart/alternative", email.parts[1].mime_type) - assert_equal("text/plain", email.parts[1].parts[1].mime_type) - assert_equal("text/html", email.parts[1].parts[0].mime_type) - end - end - - test "implicit multipart with default locale" do - email = BaseMailer.implicit_with_locale - assert_equal(2, email.parts.size) - assert_equal("multipart/alternative", email.mime_type) - assert_equal("text/plain", email.parts[0].mime_type) - assert_equal("Implicit with locale TEXT", email.parts[0].body.encoded) - assert_equal("text/html", email.parts[1].mime_type) - assert_equal("Implicit with locale EN HTML", email.parts[1].body.encoded) - end - - test "implicit multipart with other locale" do - swap I18n, :locale => :pl do - email = BaseMailer.implicit_with_locale - assert_equal(2, email.parts.size) - assert_equal("multipart/alternative", email.mime_type) - assert_equal("text/plain", email.parts[0].mime_type) - assert_equal("Implicit with locale PL TEXT", email.parts[0].body.encoded) - assert_equal("text/html", email.parts[1].mime_type) - assert_equal("Implicit with locale HTML", email.parts[1].body.encoded) - end - end - - test "implicit multipart with several view paths uses the first one with template" do - old = BaseMailer.view_paths - begin - BaseMailer.view_paths = [File.join(FIXTURE_LOAD_PATH, "another.path")] + old.dup - email = BaseMailer.welcome - assert_equal("Welcome from another path", email.body.encoded) - ensure - BaseMailer.view_paths = old - end - end - - test "implicit multipart with inexistent templates uses the next view path" do - old = BaseMailer.view_paths - begin - BaseMailer.view_paths = [File.join(FIXTURE_LOAD_PATH, "unknown")] + old.dup - email = BaseMailer.welcome - assert_equal("Welcome", email.body.encoded) - ensure - BaseMailer.view_paths = old - end - end - - # Explicit multipart - test "explicit multipart" do - email = BaseMailer.explicit_multipart - assert_equal(2, email.parts.size) - assert_equal("multipart/alternative", email.mime_type) - assert_equal("text/plain", email.parts[0].mime_type) - assert_equal("TEXT Explicit Multipart", email.parts[0].body.encoded) - assert_equal("text/html", email.parts[1].mime_type) - assert_equal("HTML Explicit Multipart", email.parts[1].body.encoded) - end - - test "explicit multipart have a boundary" do - mail = BaseMailer.explicit_multipart - assert_not_nil(mail.content_type_parameters[:boundary]) - end - - test "explicit multipart does not sort order" do - order = ["text/html", "text/plain"] - with_default BaseMailer, :parts_order => order do - email = BaseMailer.explicit_multipart - assert_equal("text/plain", email.parts[0].mime_type) - assert_equal("text/html", email.parts[1].mime_type) - - email = BaseMailer.explicit_multipart(:parts_order => order.reverse) - assert_equal("text/plain", email.parts[0].mime_type) - assert_equal("text/html", email.parts[1].mime_type) - end - end - - test "explicit multipart with attachments creates nested parts" do - email = BaseMailer.explicit_multipart(:attachments => true) - assert_equal("application/pdf", email.parts[0].mime_type) - assert_equal("multipart/alternative", email.parts[1].mime_type) - assert_equal("text/plain", email.parts[1].parts[0].mime_type) - assert_equal("TEXT Explicit Multipart", email.parts[1].parts[0].body.encoded) - assert_equal("text/html", email.parts[1].parts[1].mime_type) - assert_equal("HTML Explicit Multipart", email.parts[1].parts[1].body.encoded) - end - - test "explicit multipart with templates" do - email = BaseMailer.explicit_multipart_templates - assert_equal(2, email.parts.size) - assert_equal("multipart/alternative", email.mime_type) - assert_equal("text/html", email.parts[0].mime_type) - assert_equal("HTML Explicit Multipart Templates", email.parts[0].body.encoded) - assert_equal("text/plain", email.parts[1].mime_type) - assert_equal("TEXT Explicit Multipart Templates", email.parts[1].body.encoded) - end - - test "explicit multipart with format.any" do - email = BaseMailer.explicit_multipart_with_any - assert_equal(2, email.parts.size) - assert_equal("multipart/alternative", email.mime_type) - assert_equal("text/plain", email.parts[0].mime_type) - assert_equal("Format with any!", email.parts[0].body.encoded) - assert_equal("text/html", email.parts[1].mime_type) - assert_equal("Format with any!", email.parts[1].body.encoded) - end - - test "explicit multipart with format(Hash)" do - email = BaseMailer.explicit_multipart_with_options(true) - email.ready_to_send! - assert_equal(2, email.parts.size) - assert_equal("multipart/alternative", email.mime_type) - assert_equal("text/plain", email.parts[0].mime_type) - assert_equal("base64", email.parts[0].content_transfer_encoding) - assert_equal("text/html", email.parts[1].mime_type) - assert_equal("7bit", email.parts[1].content_transfer_encoding) - end - - test "explicit multipart with one part is rendered as body and options are merged" do - email = BaseMailer.explicit_multipart_with_options - assert_equal(0, email.parts.size) - assert_equal("text/plain", email.mime_type) - assert_equal("base64", email.content_transfer_encoding) - end - - test "explicit multipart with one template has the expected format" do - email = BaseMailer.explicit_multipart_with_one_template - assert_equal(2, email.parts.size) - assert_equal("multipart/alternative", email.mime_type) - assert_equal("text/html", email.parts[0].mime_type) - assert_equal("[:html]", email.parts[0].body.encoded) - assert_equal("text/plain", email.parts[1].mime_type) - assert_equal("[:text]", email.parts[1].body.encoded) - end - - # Class level API with method missing - test "should respond to action methods" do - assert_respond_to BaseMailer, :welcome - assert_respond_to BaseMailer, :implicit_multipart - assert !BaseMailer.respond_to?(:mail) - assert !BaseMailer.respond_to?(:headers) - end - - test "calling just the action should return the generated mail object" do - BaseMailer.deliveries.clear - email = BaseMailer.welcome - assert_equal(0, BaseMailer.deliveries.length) - assert_equal('The first email on new API!', email.subject) - end - - test "calling deliver on the action should deliver the mail object" do - BaseMailer.deliveries.clear - BaseMailer.expects(:deliver_mail).once - mail = BaseMailer.welcome.deliver - assert_instance_of Mail::Message, mail - end - - test "calling deliver on the action should increment the deliveries collection if using the test mailer" do - BaseMailer.delivery_method = :test - BaseMailer.deliveries.clear - BaseMailer.welcome.deliver - assert_equal(1, BaseMailer.deliveries.length) - end - - test "calling deliver, ActionMailer should yield back to mail to let it call :do_delivery on itself" do - mail = Mail::Message.new - mail.expects(:do_delivery).once - BaseMailer.expects(:welcome).returns(mail) - BaseMailer.welcome.deliver - end - - # Rendering - test "you can specify a different template for implicit render" do - mail = BaseMailer.implicit_different_template('implicit_multipart').deliver - assert_equal("HTML Implicit Multipart", mail.html_part.body.decoded) - assert_equal("TEXT Implicit Multipart", mail.text_part.body.decoded) - end - - test "render :file uses render :template semantics and is deprecated" do - mail = nil - assert_deprecated { mail = BaseMailer.implicit_different_template_with_file('implicit_multipart').deliver } - assert_equal("HTML Implicit Multipart", mail.html_part.body.decoded) - assert_equal("TEXT Implicit Multipart", mail.text_part.body.decoded) - end - - test "you can specify a different template for explicit render" do - mail = BaseMailer.explicit_different_template('explicit_multipart_templates').deliver - assert_equal("HTML Explicit Multipart Templates", mail.html_part.body.decoded) - assert_equal("TEXT Explicit Multipart Templates", mail.text_part.body.decoded) - end - - test "you can specify a different layout" do - mail = BaseMailer.different_layout('different_layout').deliver - assert_equal("HTML -- HTML", mail.html_part.body.decoded) - assert_equal("PLAIN -- PLAIN", mail.text_part.body.decoded) - end - - test "you can specify the template path for implicit lookup" do - mail = BaseMailer.welcome_from_another_path('another.path/base_mailer').deliver - assert_equal("Welcome from another path", mail.body.encoded) - - mail = BaseMailer.welcome_from_another_path(['unknown/invalid', 'another.path/base_mailer']).deliver - assert_equal("Welcome from another path", mail.body.encoded) - end - - test "assets tags should use ActionMailer's asset_host settings" do - ActionMailer::Base.config.asset_host = "http://global.com" - ActionMailer::Base.config.assets_dir = "global/" - - mail = AssetMailer.welcome - - assert_equal(%{Dummy}, mail.body.to_s.strip) - end - - test "assets tags should use a Mailer's asset_host settings when available" do - ActionMailer::Base.config.asset_host = "global.com" - ActionMailer::Base.config.assets_dir = "global/" - - AssetMailer.asset_host = "http://local.com" - - mail = AssetMailer.welcome - - assert_equal(%{Dummy}, mail.body.to_s.strip) - end - - # Before and After hooks - - class MyObserver - def self.delivered_email(mail) - end - end - - test "you can register an observer to the mail object that gets informed on email delivery" do - ActionMailer::Base.register_observer(MyObserver) - mail = BaseMailer.welcome - MyObserver.expects(:delivered_email).with(mail) - mail.deliver - end - - class MyInterceptor - def self.delivering_email(mail) - end - end - - test "you can register an interceptor to the mail object that gets passed the mail object before delivery" do - ActionMailer::Base.register_interceptor(MyInterceptor) - mail = BaseMailer.welcome - MyInterceptor.expects(:delivering_email).with(mail) - mail.deliver - end - - test "being able to put proc's into the defaults hash and they get evaluated on mail sending" do - mail1 = ProcMailer.welcome - yesterday = 1.day.ago - Time.stubs(:now).returns(yesterday) - mail2 = ProcMailer.welcome - assert(mail1['X-Proc-Method'].to_s.to_i > mail2['X-Proc-Method'].to_s.to_i) - end - - test "we can call other defined methods on the class as needed" do - mail = ProcMailer.welcome - assert_equal("Thanks for signing up this afternoon", mail.subject) - end - - test "action methods should be refreshed after defining new method" do - class FooMailer < ActionMailer::Base - # this triggers action_methods - self.respond_to?(:foo) - - def notify - end - end - - assert_equal ["notify"], FooMailer.action_methods - end - - protected - - # Execute the block setting the given values and restoring old values after - # the block is executed. - def swap(klass, new_values) - old_values = {} - new_values.each do |key, value| - old_values[key] = klass.send key - klass.send :"#{key}=", value - end - yield - ensure - old_values.each do |key, value| - klass.send :"#{key}=", value - end - end - - def with_default(klass, new_values) - old = klass.default_params - klass.default(new_values) - yield - ensure - klass.default_params = old - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/delivery_methods_test.rb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/delivery_methods_test.rb deleted file mode 100644 index 1d47b5c23..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/delivery_methods_test.rb +++ /dev/null @@ -1,172 +0,0 @@ -require 'abstract_unit' -require 'mail' - -class MyCustomDelivery -end - -class BogusDelivery - def initialize(*) - end - - def deliver!(mail) - raise "failed" - end -end - -class DefaultsDeliveryMethodsTest < ActiveSupport::TestCase - test "default smtp settings" do - settings = { :address => "localhost", - :port => 25, - :domain => 'localhost.localdomain', - :user_name => nil, - :password => nil, - :authentication => nil, - :enable_starttls_auto => true } - assert_equal settings, ActionMailer::Base.smtp_settings - end - - test "default file delivery settings" do - settings = {:location => "#{Dir.tmpdir}/mails"} - assert_equal settings, ActionMailer::Base.file_settings - end - - test "default sendmail settings" do - settings = {:location => '/usr/sbin/sendmail', - :arguments => '-i -t'} - assert_equal settings, ActionMailer::Base.sendmail_settings - end -end - -class CustomDeliveryMethodsTest < ActiveSupport::TestCase - def setup - @old_delivery_method = ActionMailer::Base.delivery_method - ActionMailer::Base.add_delivery_method :custom, MyCustomDelivery - end - - def teardown - ActionMailer::Base.delivery_method = @old_delivery_method - new = ActionMailer::Base.delivery_methods.dup - new.delete(:custom) - ActionMailer::Base.delivery_methods = new - end - - test "allow to add custom delivery method" do - ActionMailer::Base.delivery_method = :custom - assert_equal :custom, ActionMailer::Base.delivery_method - end - - test "allow to customize custom settings" do - ActionMailer::Base.custom_settings = { :foo => :bar } - assert_equal Hash[:foo => :bar], ActionMailer::Base.custom_settings - end - - test "respond to custom settings" do - assert_respond_to ActionMailer::Base, :custom_settings - assert_respond_to ActionMailer::Base, :custom_settings= - end - - test "does not respond to unknown settings" do - assert_raise NoMethodError do - ActionMailer::Base.another_settings - end - end -end - -class MailDeliveryTest < ActiveSupport::TestCase - class DeliveryMailer < ActionMailer::Base - DEFAULT_HEADERS = { - :to => 'mikel@test.lindsaar.net', - :from => 'jose@test.plataformatec.com' - } - - def welcome(hash={}) - mail(DEFAULT_HEADERS.merge(hash)) - end - end - - def setup - ActionMailer::Base.delivery_method = :smtp - end - - def teardown - DeliveryMailer.delivery_method = :smtp - DeliveryMailer.perform_deliveries = true - DeliveryMailer.raise_delivery_errors = true - end - - test "ActionMailer should be told when Mail gets delivered" do - DeliveryMailer.deliveries.clear - DeliveryMailer.expects(:deliver_mail).once - DeliveryMailer.welcome.deliver - end - - test "delivery method can be customized per instance" do - email = DeliveryMailer.welcome.deliver - assert_instance_of Mail::SMTP, email.delivery_method - email = DeliveryMailer.welcome(:delivery_method => :test).deliver - assert_instance_of Mail::TestMailer, email.delivery_method - end - - test "delivery method can be customized in subclasses not changing the parent" do - DeliveryMailer.delivery_method = :test - assert_equal :smtp, ActionMailer::Base.delivery_method - $BREAK = true - email = DeliveryMailer.welcome.deliver - assert_instance_of Mail::TestMailer, email.delivery_method - end - - test "non registered delivery methods raises errors" do - DeliveryMailer.delivery_method = :unknown - assert_raise RuntimeError do - DeliveryMailer.welcome.deliver - end - end - - test "does not perform deliveries if requested" do - DeliveryMailer.perform_deliveries = false - DeliveryMailer.deliveries.clear - Mail::Message.any_instance.expects(:deliver!).never - DeliveryMailer.welcome.deliver - end - - test "does not append the deliveries collection if told not to perform the delivery" do - DeliveryMailer.perform_deliveries = false - DeliveryMailer.deliveries.clear - DeliveryMailer.welcome.deliver - assert_equal(0, DeliveryMailer.deliveries.length) - end - - test "raise errors on bogus deliveries" do - DeliveryMailer.delivery_method = BogusDelivery - DeliveryMailer.deliveries.clear - assert_raise RuntimeError do - DeliveryMailer.welcome.deliver - end - end - - test "does not increment the deliveries collection on error" do - DeliveryMailer.delivery_method = BogusDelivery - DeliveryMailer.deliveries.clear - assert_raise RuntimeError do - DeliveryMailer.welcome.deliver - end - assert_equal(0, DeliveryMailer.deliveries.length) - end - - test "does not raise errors on bogus deliveries if set" do - DeliveryMailer.delivery_method = BogusDelivery - DeliveryMailer.raise_delivery_errors = false - assert_nothing_raised do - DeliveryMailer.welcome.deliver - end - end - - test "does not increment the deliveries collection on bogus deliveries" do - DeliveryMailer.delivery_method = BogusDelivery - DeliveryMailer.raise_delivery_errors = false - DeliveryMailer.deliveries.clear - DeliveryMailer.welcome.deliver - assert_equal(0, DeliveryMailer.deliveries.length) - end - -end diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/another.path/base_mailer/welcome.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/another.path/base_mailer/welcome.erb deleted file mode 100644 index ef451298e..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/another.path/base_mailer/welcome.erb +++ /dev/null @@ -1 +0,0 @@ -Welcome from another path \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/asset_host_mailer/email_with_asset.html.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/asset_host_mailer/email_with_asset.html.erb deleted file mode 100644 index b3f0438d0..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/asset_host_mailer/email_with_asset.html.erb +++ /dev/null @@ -1 +0,0 @@ -<%= image_tag "somelogo.png" %> \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/asset_mailer/welcome.html.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/asset_mailer/welcome.html.erb deleted file mode 100644 index 90d26130d..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/asset_mailer/welcome.html.erb +++ /dev/null @@ -1 +0,0 @@ -<%= image_tag "dummy.png" %> \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/attachments/foo.jpg b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/attachments/foo.jpg deleted file mode 100644 index b976fe5e0..000000000 Binary files a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/attachments/foo.jpg and /dev/null differ diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/attachments/test.jpg b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/attachments/test.jpg deleted file mode 100644 index b976fe5e0..000000000 Binary files a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/attachments/test.jpg and /dev/null differ diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/auto_layout_mailer/hello.html.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/auto_layout_mailer/hello.html.erb deleted file mode 100644 index 54950788f..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/auto_layout_mailer/hello.html.erb +++ /dev/null @@ -1 +0,0 @@ -Inside \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/auto_layout_mailer/multipart.html.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/auto_layout_mailer/multipart.html.erb deleted file mode 100644 index 6d73f199c..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/auto_layout_mailer/multipart.html.erb +++ /dev/null @@ -1 +0,0 @@ -text/html multipart \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/auto_layout_mailer/multipart.text.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/auto_layout_mailer/multipart.text.erb deleted file mode 100644 index f4b91e403..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/auto_layout_mailer/multipart.text.erb +++ /dev/null @@ -1 +0,0 @@ -text/plain multipart \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/attachment_with_content.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/attachment_with_content.erb deleted file mode 100644 index deb9dbd03..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/attachment_with_content.erb +++ /dev/null @@ -1 +0,0 @@ -Attachment with content \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/different_layout.html.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/different_layout.html.erb deleted file mode 100644 index 3225efc49..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/different_layout.html.erb +++ /dev/null @@ -1 +0,0 @@ -HTML \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/different_layout.text.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/different_layout.text.erb deleted file mode 100644 index b547f4a33..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/different_layout.text.erb +++ /dev/null @@ -1 +0,0 @@ -PLAIN \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/email_custom_layout.text.html.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/email_custom_layout.text.html.erb deleted file mode 100644 index a2187308b..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/email_custom_layout.text.html.erb +++ /dev/null @@ -1 +0,0 @@ -body_text \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/email_with_translations.html.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/email_with_translations.html.erb deleted file mode 100644 index 30466dd00..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/email_with_translations.html.erb +++ /dev/null @@ -1 +0,0 @@ -<%= t('.greet_user', :name => 'lifo') %> \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/explicit_multipart_templates.html.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/explicit_multipart_templates.html.erb deleted file mode 100644 index c0a61b624..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/explicit_multipart_templates.html.erb +++ /dev/null @@ -1 +0,0 @@ -HTML Explicit Multipart Templates \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/explicit_multipart_templates.text.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/explicit_multipart_templates.text.erb deleted file mode 100644 index 507230b1d..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/explicit_multipart_templates.text.erb +++ /dev/null @@ -1 +0,0 @@ -TEXT Explicit Multipart Templates \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/explicit_multipart_with_one_template.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/explicit_multipart_with_one_template.erb deleted file mode 100644 index 8a69657b0..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/explicit_multipart_with_one_template.erb +++ /dev/null @@ -1 +0,0 @@ -<%= self.formats.inspect %> \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/html_only.html.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/html_only.html.erb deleted file mode 100644 index 9c99a008e..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/html_only.html.erb +++ /dev/null @@ -1 +0,0 @@ -

Testing

\ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/implicit_multipart.html.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/implicit_multipart.html.erb deleted file mode 100644 index 23745cd28..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/implicit_multipart.html.erb +++ /dev/null @@ -1 +0,0 @@ -HTML Implicit Multipart \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/implicit_multipart.text.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/implicit_multipart.text.erb deleted file mode 100644 index d51437fc7..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/implicit_multipart.text.erb +++ /dev/null @@ -1 +0,0 @@ -TEXT Implicit Multipart \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/implicit_with_locale.en.html.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/implicit_with_locale.en.html.erb deleted file mode 100644 index 34e39c8fd..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/implicit_with_locale.en.html.erb +++ /dev/null @@ -1 +0,0 @@ -Implicit with locale EN HTML \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/implicit_with_locale.html.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/implicit_with_locale.html.erb deleted file mode 100644 index 5ce283f22..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/implicit_with_locale.html.erb +++ /dev/null @@ -1 +0,0 @@ -Implicit with locale HTML \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/implicit_with_locale.pl.text.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/implicit_with_locale.pl.text.erb deleted file mode 100644 index c49cbae60..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/implicit_with_locale.pl.text.erb +++ /dev/null @@ -1 +0,0 @@ -Implicit with locale PL TEXT \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/implicit_with_locale.text.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/implicit_with_locale.text.erb deleted file mode 100644 index 5a18ff62c..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/implicit_with_locale.text.erb +++ /dev/null @@ -1 +0,0 @@ -Implicit with locale TEXT \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/inline_attachment.html.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/inline_attachment.html.erb deleted file mode 100644 index 398b488b9..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/inline_attachment.html.erb +++ /dev/null @@ -1,5 +0,0 @@ -

Inline Image

- -<%= image_tag attachments['logo.png'].url %> - -

This is an image that is inline

\ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/inline_attachment.text.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/inline_attachment.text.erb deleted file mode 100644 index 14b0a2b53..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/inline_attachment.text.erb +++ /dev/null @@ -1,4 +0,0 @@ -Inline Image - -No image for you - diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/plain_text_only.text.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/plain_text_only.text.erb deleted file mode 100644 index 0a9012568..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/plain_text_only.text.erb +++ /dev/null @@ -1 +0,0 @@ -Testing \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/welcome.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/welcome.erb deleted file mode 100644 index 01f3f00c6..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/base_mailer/welcome.erb +++ /dev/null @@ -1 +0,0 @@ -Welcome \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/explicit_layout_mailer/logout.html.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/explicit_layout_mailer/logout.html.erb deleted file mode 100644 index 0533a3b2f..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/explicit_layout_mailer/logout.html.erb +++ /dev/null @@ -1 +0,0 @@ -You logged out \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/explicit_layout_mailer/signup.html.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/explicit_layout_mailer/signup.html.erb deleted file mode 100644 index 4789e888c..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/explicit_layout_mailer/signup.html.erb +++ /dev/null @@ -1 +0,0 @@ -We do not spam \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/first_mailer/share.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/first_mailer/share.erb deleted file mode 100644 index 4c543cd05..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/first_mailer/share.erb +++ /dev/null @@ -1 +0,0 @@ -first mail diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/layouts/auto_layout_mailer.html.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/layouts/auto_layout_mailer.html.erb deleted file mode 100644 index 932271450..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/layouts/auto_layout_mailer.html.erb +++ /dev/null @@ -1 +0,0 @@ -Hello from layout <%= yield %> \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/layouts/auto_layout_mailer.text.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/layouts/auto_layout_mailer.text.erb deleted file mode 100644 index 111576b67..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/layouts/auto_layout_mailer.text.erb +++ /dev/null @@ -1 +0,0 @@ -text/plain layout - <%= yield %> \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/layouts/different_layout.html.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/layouts/different_layout.html.erb deleted file mode 100644 index 99eb026ae..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/layouts/different_layout.html.erb +++ /dev/null @@ -1 +0,0 @@ -HTML -- <%= yield %> \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/layouts/different_layout.text.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/layouts/different_layout.text.erb deleted file mode 100644 index b93467b7a..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/layouts/different_layout.text.erb +++ /dev/null @@ -1 +0,0 @@ -PLAIN -- <%= yield %> \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/layouts/spam.html.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/layouts/spam.html.erb deleted file mode 100644 index 619d6b16b..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/layouts/spam.html.erb +++ /dev/null @@ -1 +0,0 @@ -Spammer layout <%= yield %> \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/nested_layout_mailer/signup.html.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/nested_layout_mailer/signup.html.erb deleted file mode 100644 index 4789e888c..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/nested_layout_mailer/signup.html.erb +++ /dev/null @@ -1 +0,0 @@ -We do not spam \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/path.with.dots/funky_path_mailer/multipart_with_template_path_with_dots.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/path.with.dots/funky_path_mailer/multipart_with_template_path_with_dots.erb deleted file mode 100644 index 2d0cd5c12..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/path.with.dots/funky_path_mailer/multipart_with_template_path_with_dots.erb +++ /dev/null @@ -1 +0,0 @@ -Have some dots. Enjoy! \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email deleted file mode 100644 index c57bc04bf..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email +++ /dev/null @@ -1,14 +0,0 @@ -From jamis_buck@byu.edu Mon May 2 16:07:05 2005 -Mime-Version: 1.0 (Apple Message framework v622) -Content-Transfer-Encoding: base64 -Message-Id: -Content-Type: text/plain; - charset=EUC-KR; - format=flowed -To: willard15georgina@jamis.backpackit.com -From: Jamis Buck -Subject: =?EUC-KR?Q?NOTE:_=C7=D1=B1=B9=B8=BB=B7=CE_=C7=CF=B4=C2_=B0=CD?= -Date: Mon, 2 May 2005 16:07:05 -0600 - -tOu6zrrQwMcguLbC+bChwfa3ziwgv+y4rrTCIMfPs6q01MC7ILnPvcC0z7TZLg0KDQrBpiDAzLin -wLogSmFtaXPA1LTPtNku diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email10 b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email10 deleted file mode 100644 index 8b61289fc..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email10 +++ /dev/null @@ -1,20 +0,0 @@ -Return-Path: -Received: from xxx.xxxx.xxx by xxx.xxxx.xxx with ESMTP id C1B953B4CB6 for ; Tue, 10 May 2005 15:27:05 -0500 -Received: from SMS-GTYxxx.xxxx.xxx by xxx.xxxx.xxx with ESMTP id ca for ; Tue, 10 May 2005 15:27:04 -0500 -Received: from xxx.xxxx.xxx by SMS-GTYxxx.xxxx.xxx with ESMTP id j4AKR3r23323 for ; Tue, 10 May 2005 15:27:03 -0500 -Date: Tue, 10 May 2005 15:27:03 -0500 -From: xxx@xxxx.xxx -Sender: xxx@xxxx.xxx -To: xxxxxxxxxxx@xxxx.xxxx.xxx -Message-Id: -X-Original-To: xxxxxxxxxxx@xxxx.xxxx.xxx -Delivered-To: xxx@xxxx.xxx -Importance: normal -Content-Type: text/plain; charset=X-UNKNOWN - -Test test. Hi. Waving. m - ----------------------------------------------------------------- -Sent via Bell Mobility's Text Messaging service. -Envoyé par le service de messagerie texte de Bell Mobilité. ----------------------------------------------------------------- diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email12 b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email12 deleted file mode 100644 index 123d7d358..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email12 +++ /dev/null @@ -1,32 +0,0 @@ -Mime-Version: 1.0 (Apple Message framework v730) -Content-Type: multipart/mixed; boundary=Apple-Mail-13-196941151 -Message-Id: <9169D984-4E0B-45EF-82D4-8F5E53AD7012@example.com> -From: foo@example.com -Subject: testing -Date: Mon, 6 Jun 2005 22:21:22 +0200 -To: blah@example.com - - ---Apple-Mail-13-196941151 -Content-Transfer-Encoding: quoted-printable -Content-Type: text/plain; - charset=ISO-8859-1; - delsp=yes; - format=flowed - -This is the first part. - ---Apple-Mail-13-196941151 -Content-Type: image/jpeg -Content-Transfer-Encoding: base64 -Content-Location: Photo25.jpg -Content-ID: -Content-Disposition: inline - -jamisSqGSIb3DQEHAqCAMIjamisxCzAJBgUrDgMCGgUAMIAGCSqGSjamisEHAQAAoIIFSjCCBUYw -ggQujamisQICBD++ukQwDQYJKojamisNAQEFBQAwMTELMAkGA1UEBhMCRjamisAKBgNVBAoTA1RE -QzEUMBIGjamisxMLVERDIE9DRVMgQ0jamisNMDQwMjI5MTE1OTAxWhcNMDYwMjamisIyOTAxWjCB -gDELMAkGA1UEjamisEsxKTAnBgNVBAoTIEjamisuIG9yZ2FuaXNhdG9yaXNrIHRpbjamisRuaW5= - ---Apple-Mail-13-196941151-- - diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email13 b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email13 deleted file mode 100644 index a7e10d37b..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email13 +++ /dev/null @@ -1,29 +0,0 @@ -Mime-Version: 1.0 (Apple Message framework v730) -Content-Type: multipart/mixed; boundary=Apple-Mail-13-196941151 -Message-Id: <9169D984-4E0B-45EF-82D4-8F5E53AD7012@example.com> -From: foo@example.com -Subject: testing -Date: Mon, 6 Jun 2005 22:21:22 +0200 -To: blah@example.com - - ---Apple-Mail-13-196941151 -Content-Transfer-Encoding: quoted-printable -Content-Type: text/plain; - charset=ISO-8859-1; - delsp=yes; - format=flowed - -This is the first part. - ---Apple-Mail-13-196941151 -Content-Type: text/x-ruby-script; name="hello.rb" -Content-Transfer-Encoding: 7bit -Content-Disposition: attachment; - filename="api.rb" - -puts "Hello, world!" -gets - ---Apple-Mail-13-196941151-- - diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email2 b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email2 deleted file mode 100644 index 7c16a4f46..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email2 +++ /dev/null @@ -1,114 +0,0 @@ -From xxxxxxxxx.xxxxxxx@gmail.com Sun May 8 19:07:09 2005 -Return-Path: -X-Original-To: xxxxx@xxxxx.xxxxxxxxx.com -Delivered-To: xxxxx@xxxxx.xxxxxxxxx.com -Received: from localhost (localhost [127.0.0.1]) - by xxxxx.xxxxxxxxx.com (Postfix) with ESMTP id 06C9DA98D - for ; Sun, 8 May 2005 19:09:13 +0000 (GMT) -Received: from xxxxx.xxxxxxxxx.com ([127.0.0.1]) - by localhost (xxxxx.xxxxxxxxx.com [127.0.0.1]) (amavisd-new, port 10024) - with LMTP id 88783-08 for ; - Sun, 8 May 2005 19:09:12 +0000 (GMT) -Received: from xxxxxxx.xxxxxxxxx.com (xxxxxxx.xxxxxxxxx.com [69.36.39.150]) - by xxxxx.xxxxxxxxx.com (Postfix) with ESMTP id 10D8BA960 - for ; Sun, 8 May 2005 19:09:12 +0000 (GMT) -Received: from zproxy.gmail.com (zproxy.gmail.com [64.233.162.199]) - by xxxxxxx.xxxxxxxxx.com (Postfix) with ESMTP id 9EBC4148EAB - for ; Sun, 8 May 2005 14:09:11 -0500 (CDT) -Received: by zproxy.gmail.com with SMTP id 13so1233405nzp - for ; Sun, 08 May 2005 12:09:11 -0700 (PDT) -DomainKey-Signature: a=rsa-sha1; q=dns; c=nofws; - s=beta; d=gmail.com; - h=received:message-id:date:from:reply-to:to:subject:in-reply-to:mime-version:content-type:references; - b=cid1mzGEFa3gtRa06oSrrEYfKca2CTKu9sLMkWxjbvCsWMtp9RGEILjUz0L5RySdH5iO661LyNUoHRFQIa57bylAbXM3g2DTEIIKmuASDG3x3rIQ4sHAKpNxP7Pul+mgTaOKBv+spcH7af++QEJ36gHFXD2O/kx9RePs3JNf/K8= -Received: by 10.36.10.16 with SMTP id 16mr1012493nzj; - Sun, 08 May 2005 12:09:11 -0700 (PDT) -Received: by 10.36.5.10 with HTTP; Sun, 8 May 2005 12:09:11 -0700 (PDT) -Message-ID: -Date: Sun, 8 May 2005 14:09:11 -0500 -From: xxxxxxxxx xxxxxxx -Reply-To: xxxxxxxxx xxxxxxx -To: xxxxx xxxx -Subject: Fwd: Signed email causes file attachments -In-Reply-To: -Mime-Version: 1.0 -Content-Type: multipart/mixed; - boundary="----=_Part_5028_7368284.1115579351471" -References: - -------=_Part_5028_7368284.1115579351471 -Content-Type: text/plain; charset=ISO-8859-1 -Content-Transfer-Encoding: quoted-printable -Content-Disposition: inline - -We should not include these files or vcards as attachments. - ----------- Forwarded message ---------- -From: xxxxx xxxxxx -Date: May 8, 2005 1:17 PM -Subject: Signed email causes file attachments -To: xxxxxxx@xxxxxxxxxx.com - - -Hi, - -Just started to use my xxxxxxxx account (to set-up a GTD system, -natch) and noticed that when I send content via email the signature/ -certificate from my email account gets added as a file (e.g. -"smime.p7s"). - -Obviously I can uncheck the signature option in the Mail compose -window but how often will I remember to do that? - -Is there any way these kind of files could be ignored, e.g. via some -sort of exclusions list? - -------=_Part_5028_7368284.1115579351471 -Content-Type: application/pkcs7-signature; name=smime.p7s -Content-Transfer-Encoding: base64 -Content-Disposition: attachment; filename="smime.p7s" - -MIAGCSqGSIb3DQEHAqCAMIACAQExCzAJBgUrDgMCGgUAMIAGCSqGSIb3DQEHAQAAoIIGFDCCAs0w -ggI2oAMCAQICAw5c+TANBgkqhkiG9w0BAQQFADBiMQswCQYDVQQGEwJaQTElMCMGA1UEChMcVGhh -d3RlIENvbnN1bHRpbmcgKFB0eSkgTHRkLjEsMCoGA1UEAxMjVGhhd3RlIFBlcnNvbmFsIEZyZWVt -YWlsIElzc3VpbmcgQ0EwHhcNMDUwMzI5MDkzOTEwWhcNMDYwMzI5MDkzOTEwWjBCMR8wHQYDVQQD -ExZUaGF3dGUgRnJlZW1haWwgTWVtYmVyMR8wHQYJKoZIhvcNAQkBFhBzbWhhdW5jaEBtYWMuY29t -MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn90dPsYS3LjfMY211OSYrDQLzwNYPlAL -7+/0XA+kdy8/rRnyEHFGwhNCDmg0B6pxC7z3xxJD/8GfCd+IYUUNUQV5m9MkxfP9pTVXZVIYLaBw -o8xS3A0a1LXealcmlEbJibmKkEaoXci3MhryLgpaa+Kk/sH02SNatDO1vS28bPsibZpcc6deFrla -hSYnL+PW54mDTGHIcCN2fbx/Y6qspzqmtKaXrv75NBtuy9cB6KzU4j2xXbTkAwz3pRSghJJaAwdp -+yIivAD3vr0kJE3p+Ez34HMh33EXEpFoWcN+MCEQZD9WnmFViMrvfvMXLGVFQfAAcC060eGFSRJ1 -ZQ9UVQIDAQABoy0wKzAbBgNVHREEFDASgRBzbWhhdW5jaEBtYWMuY29tMAwGA1UdEwEB/wQCMAAw -DQYJKoZIhvcNAQEEBQADgYEAQMrg1n2pXVWteP7BBj+Pk3UfYtbuHb42uHcLJjfjnRlH7AxnSwrd -L3HED205w3Cq8T7tzVxIjRRLO/ljq0GedSCFBky7eYo1PrXhztGHCTSBhsiWdiyLWxKlOxGAwJc/ -lMMnwqLOdrQcoF/YgbjeaUFOQbUh94w9VDNpWZYCZwcwggM/MIICqKADAgECAgENMA0GCSqGSIb3 -DQEBBQUAMIHRMQswCQYDVQQGEwJaQTEVMBMGA1UECBMMV2VzdGVybiBDYXBlMRIwEAYDVQQHEwlD -YXBlIFRvd24xGjAYBgNVBAoTEVRoYXd0ZSBDb25zdWx0aW5nMSgwJgYDVQQLEx9DZXJ0aWZpY2F0 -aW9uIFNlcnZpY2VzIERpdmlzaW9uMSQwIgYDVQQDExtUaGF3dGUgUGVyc29uYWwgRnJlZW1haWwg -Q0ExKzApBgkqhkiG9w0BCQEWHHBlcnNvbmFsLWZyZWVtYWlsQHRoYXd0ZS5jb20wHhcNMDMwNzE3 -MDAwMDAwWhcNMTMwNzE2MjM1OTU5WjBiMQswCQYDVQQGEwJaQTElMCMGA1UEChMcVGhhd3RlIENv -bnN1bHRpbmcgKFB0eSkgTHRkLjEsMCoGA1UEAxMjVGhhd3RlIFBlcnNvbmFsIEZyZWVtYWlsIElz -c3VpbmcgQ0EwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMSmPFVzVftOucqZWh5owHUEcJ3f -6f+jHuy9zfVb8hp2vX8MOmHyv1HOAdTlUAow1wJjWiyJFXCO3cnwK4Vaqj9xVsuvPAsH5/EfkTYk -KhPPK9Xzgnc9A74r/rsYPge/QIACZNenprufZdHFKlSFD0gEf6e20TxhBEAeZBlyYLf7AgMBAAGj -gZQwgZEwEgYDVR0TAQH/BAgwBgEB/wIBADBDBgNVHR8EPDA6MDigNqA0hjJodHRwOi8vY3JsLnRo -YXd0ZS5jb20vVGhhd3RlUGVyc29uYWxGcmVlbWFpbENBLmNybDALBgNVHQ8EBAMCAQYwKQYDVR0R -BCIwIKQeMBwxGjAYBgNVBAMTEVByaXZhdGVMYWJlbDItMTM4MA0GCSqGSIb3DQEBBQUAA4GBAEiM -0VCD6gsuzA2jZqxnD3+vrL7CF6FDlpSdf0whuPg2H6otnzYvwPQcUCCTcDz9reFhYsPZOhl+hLGZ -GwDFGguCdJ4lUJRix9sncVcljd2pnDmOjCBPZV+V2vf3h9bGCE6u9uo05RAaWzVNd+NWIXiC3CEZ -Nd4ksdMdRv9dX2VPMYIC5zCCAuMCAQEwaTBiMQswCQYDVQQGEwJaQTElMCMGA1UEChMcVGhhd3Rl -IENvbnN1bHRpbmcgKFB0eSkgTHRkLjEsMCoGA1UEAxMjVGhhd3RlIFBlcnNvbmFsIEZyZWVtYWls -IElzc3VpbmcgQ0ECAw5c+TAJBgUrDgMCGgUAoIIBUzAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcB -MBwGCSqGSIb3DQEJBTEPFw0wNTA1MDgxODE3NDZaMCMGCSqGSIb3DQEJBDEWBBQSkG9j6+hB0pKp -fV9tCi/iP59sNTB4BgkrBgEEAYI3EAQxazBpMGIxCzAJBgNVBAYTAlpBMSUwIwYDVQQKExxUaGF3 -dGUgQ29uc3VsdGluZyAoUHR5KSBMdGQuMSwwKgYDVQQDEyNUaGF3dGUgUGVyc29uYWwgRnJlZW1h -aWwgSXNzdWluZyBDQQIDDlz5MHoGCyqGSIb3DQEJEAILMWugaTBiMQswCQYDVQQGEwJaQTElMCMG -A1UEChMcVGhhd3RlIENvbnN1bHRpbmcgKFB0eSkgTHRkLjEsMCoGA1UEAxMjVGhhd3RlIFBlcnNv -bmFsIEZyZWVtYWlsIElzc3VpbmcgQ0ECAw5c+TANBgkqhkiG9w0BAQEFAASCAQAm1GeF7dWfMvrW -8yMPjkhE+R8D1DsiCoWSCp+5gAQm7lcK7V3KrZh5howfpI3TmCZUbbaMxOH+7aKRKpFemxoBY5Q8 -rnCkbpg/++/+MI01T69hF/rgMmrGcrv2fIYy8EaARLG0xUVFSZHSP+NQSYz0TTmh4cAESHMzY3JA -nHOoUkuPyl8RXrimY1zn0lceMXlweZRouiPGuPNl1hQKw8P+GhOC5oLlM71UtStnrlk3P9gqX5v7 -Tj7Hx057oVfY8FMevjxGwU3EK5TczHezHbWWgTyum9l2ZQbUQsDJxSniD3BM46C1VcbDLPaotAZ0 -fTYLZizQfm5hcWEbfYVzkSzLAAAAAAAA -------=_Part_5028_7368284.1115579351471-- - diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email3 b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email3 deleted file mode 100644 index 8c05980b3..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email3 +++ /dev/null @@ -1,70 +0,0 @@ -From xxxx@xxxx.com Tue May 10 11:28:07 2005 -Return-Path: -X-Original-To: xxxx@xxxx.com -Delivered-To: xxxx@xxxx.com -Received: from localhost (localhost [127.0.0.1]) - by xxx.xxxxx.com (Postfix) with ESMTP id 50FD3A96F - for ; Tue, 10 May 2005 17:26:50 +0000 (GMT) -Received: from xxx.xxxxx.com ([127.0.0.1]) - by localhost (xxx.xxxxx.com [127.0.0.1]) (amavisd-new, port 10024) - with LMTP id 70060-03 for ; - Tue, 10 May 2005 17:26:49 +0000 (GMT) -Received: from xxx.xxxxx.com (xxx.xxxxx.com [69.36.39.150]) - by xxx.xxxxx.com (Postfix) with ESMTP id 8B957A94B - for ; Tue, 10 May 2005 17:26:48 +0000 (GMT) -Received: from xxx.xxxxx.com (xxx.xxxxx.com [64.233.184.203]) - by xxx.xxxxx.com (Postfix) with ESMTP id 9972514824C - for ; Tue, 10 May 2005 12:26:40 -0500 (CDT) -Received: by xxx.xxxxx.com with SMTP id 68so1694448wri - for ; Tue, 10 May 2005 10:26:40 -0700 (PDT) -DomainKey-Signature: a=rsa-sha1; q=dns; c=nofws; - s=beta; d=xxxxx.com; - h=received:message-id:date:from:reply-to:to:subject:mime-version:content-type; - b=g8ZO5ttS6GPEMAz9WxrRk9+9IXBUfQIYsZLL6T88+ECbsXqGIgfGtzJJFn6o9CE3/HMrrIGkN5AisxVFTGXWxWci5YA/7PTVWwPOhJff5BRYQDVNgRKqMl/SMttNrrRElsGJjnD1UyQ/5kQmcBxq2PuZI5Zc47u6CILcuoBcM+A= -Received: by 10.54.96.19 with SMTP id t19mr621017wrb; - Tue, 10 May 2005 10:26:39 -0700 (PDT) -Received: by 10.54.110.5 with HTTP; Tue, 10 May 2005 10:26:39 -0700 (PDT) -Message-ID: -Date: Tue, 10 May 2005 11:26:39 -0600 -From: Test Tester -Reply-To: Test Tester -To: xxxx@xxxx.com, xxxx@xxxx.com -Subject: Another PDF -Mime-Version: 1.0 -Content-Type: multipart/mixed; - boundary="----=_Part_2192_32400445.1115745999735" -X-Virus-Scanned: amavisd-new at textdrive.com - -------=_Part_2192_32400445.1115745999735 -Content-Type: text/plain; charset=ISO-8859-1 -Content-Transfer-Encoding: quoted-printable -Content-Disposition: inline - -Just attaching another PDF, here, to see what the message looks like, -and to see if I can figure out what is going wrong here. - -------=_Part_2192_32400445.1115745999735 -Content-Type: application/pdf; name="broken.pdf" -Content-Transfer-Encoding: base64 -Content-Disposition: attachment; filename="broken.pdf" - -JVBERi0xLjQNCiXk9tzfDQoxIDAgb2JqDQo8PCAvTGVuZ3RoIDIgMCBSDQogICAvRmlsdGVyIC9G -bGF0ZURlY29kZQ0KPj4NCnN0cmVhbQ0KeJy9Wt2KJbkNvm/od6jrhZxYln9hWEh2p+8HBvICySaE -ycLuTV4/1ifJ9qnq09NpSBimu76yLUuy/qzqcPz7+em3Ixx/CDc6CsXxs3b5+fvfjr/8cPz6/BRu -rbfAx/n3739/fuJylJ5u5fjX81OuDr4deK4Bz3z/aDP+8fz0yw8g0Ofq7ktr1Mn+u28rvhy/jVeD -QSa+9YNKHP/pxjvDNfVAx/m3MFz54FhvTbaseaxiDoN2LeMVMw+yA7RbHSCDzxZuaYB2E1Yay7QU -x89vz0+tyFDKMlAHK5yqLmnjF+c4RjEiQIUeKwblXMe+AsZjN1J5yGQL5DHpDHksurM81rF6PKab -gK6zAarIDzIiUY23rJsN9iorAE816aIu6lsgAdQFsuhhkHOUFgVjp2GjMqSewITXNQ27jrMeamkg -1rPI3iLWG2CIaSBB+V1245YVRICGbbpYKHc2USFDl6M09acQVQYhlwIrkBNLISvXhGlF1wi5FHCw -wxZkoGNJlVeJCEsqKA+3YAV5AMb6KkeaqEJQmFKKQU8T1pRi2ihE1Y4CDrqoYFFXYjJJOatsyzuI -8SIlykuxKTMibWK8H1PgEvqYgs4GmQSrEjJAalgGirIhik+p4ZQN9E3ETFPAHE1b8pp1l/0Rc1gl -fQs0ABWvyoZZzU8VnPXwVVcO9BEsyjEJaO6eBoZRyKGlrKoYoOygA8BGIzgwN3RQ15ouigG5idZQ -fx2U4Db2CqiLO0WHAZoylGiCAqhniNQjFjQPSkmjwfNTgQ6M1Ih+eWo36wFmjIxDJZiGUBiWsAyR -xX3EekGOizkGI96Ol9zVZTAivikURhRsHh2E3JhWMpSTZCnnonrLhMCodgrNcgo4uyJUJc6qnVss -nrGd1Ptr0YwisCOYyIbUwVjV4xBUNLbguSO2YHujonAMJkMdSI7bIw91Akq2AUlMUWGFTMAOamjU -OvZQCxIkY2pCpMFo/IwLdVLHs6nddwTRrgoVbvLU9eB0G4EMndV0TNoxHbt3JBWwK6hhv3iHfDtF -yokB302IpEBTnWICde4uYc/1khDbSIkQopO6lcqamGBu1OSE3N5IPSsZX00CkSHRiiyx6HQIShsS -HSVNswdVsaOUSAWq9aYhDtGDaoG5a3lBGkYt/lFlBFt1UqrYnzVtUpUQnLiZeouKgf1KhRBViRRk -ExepJCzTwEmFDalIRbLEGtw0gfpESOpIAF/NnpPzcVCG86s0g2DuSyd41uhNGbEgaSrWEXORErbw -------=_Part_2192_32400445.1115745999735-- - diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email4 b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email4 deleted file mode 100644 index a56bd1bf4..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email4 +++ /dev/null @@ -1,59 +0,0 @@ -Return-Path: -Received: from xxx.xxxx.xxx by xxx.xxxx.xxx with ESMTP id 6AAEE3B4D23 for ; Sun, 8 May 2005 12:30:23 -0500 -Received: from xxx.xxxx.xxx by xxx.xxxx.xxx with ESMTP id j48HUC213279 for ; Sun, 8 May 2005 12:30:13 -0500 -Received: from conversion-xxx.xxxx.xxx.net by xxx.xxxx.xxx id <0IG600901LQ64I@xxx.xxxx.xxx> for ; Sun, 8 May 2005 12:30:12 -0500 -Received: from agw1 by xxx.xxxx.xxx with ESMTP id <0IG600JFYLYCAxxx@xxxx.xxx> for ; Sun, 8 May 2005 12:30:12 -0500 -Date: Sun, 8 May 2005 12:30:08 -0500 -From: xxx@xxxx.xxx -To: xxx@xxxx.xxx -Message-Id: <7864245.1115573412626.JavaMxxx@xxxx.xxx> -Subject: Filth -Mime-Version: 1.0 -Content-Type: multipart/mixed; boundary=mimepart_427e4cb4ca329_133ae40413c81ef -X-Mms-Priority: 1 -X-Mms-Transaction-Id: 3198421808-0 -X-Mms-Message-Type: 0 -X-Mms-Sender-Visibility: 1 -X-Mms-Read-Reply: 1 -X-Original-To: xxx@xxxx.xxx -X-Mms-Message-Class: 0 -X-Mms-Delivery-Report: 0 -X-Mms-Mms-Version: 16 -Delivered-To: xxx@xxxx.xxx -X-Nokia-Ag-Version: 2.0 - -This is a multi-part message in MIME format. - ---mimepart_427e4cb4ca329_133ae40413c81ef -Content-Type: multipart/mixed; boundary=mimepart_427e4cb4cbd97_133ae40413c8217 - - - ---mimepart_427e4cb4cbd97_133ae40413c8217 -Content-Type: text/plain; charset=utf-8 -Content-Transfer-Encoding: 7bit -Content-Disposition: inline -Content-Location: text.txt - -Some text - ---mimepart_427e4cb4cbd97_133ae40413c8217-- - ---mimepart_427e4cb4ca329_133ae40413c81ef -Content-Type: text/plain; charset=us-ascii -Content-Transfer-Encoding: 7bit - - --- -This Orange Multi Media Message was sent wirefree from an Orange -MMS phone. If you would like to reply, please text or phone the -sender directly by using the phone number listed in the sender's -address. To learn more about Orange's Multi Media Messaging -Service, find us on the Web at xxx.xxxx.xxx.uk/mms - - ---mimepart_427e4cb4ca329_133ae40413c81ef - - ---mimepart_427e4cb4ca329_133ae40413c81ef- - diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email5 b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email5 deleted file mode 100644 index fdbb243ff..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email5 +++ /dev/null @@ -1,19 +0,0 @@ -Return-Path: -Received: from xxx.xxxx.xxx by xxx.xxxx.xxx with ESMTP id C1B953B4CB6 for ; Tue, 10 May 2005 15:27:05 -0500 -Received: from SMS-GTYxxx.xxxx.xxx by xxx.xxxx.xxx with ESMTP id ca for ; Tue, 10 May 2005 15:27:04 -0500 -Received: from xxx.xxxx.xxx by SMS-GTYxxx.xxxx.xxx with ESMTP id j4AKR3r23323 for ; Tue, 10 May 2005 15:27:03 -0500 -Date: Tue, 10 May 2005 15:27:03 -0500 -From: xxx@xxxx.xxx -Sender: xxx@xxxx.xxx -To: xxxxxxxxxxx@xxxx.xxxx.xxx -Message-Id: -X-Original-To: xxxxxxxxxxx@xxxx.xxxx.xxx -Delivered-To: xxx@xxxx.xxx -Importance: normal - -Test test. Hi. Waving. m - ----------------------------------------------------------------- -Sent via Bell Mobility's Text Messaging service. -Envoyé par le service de messagerie texte de Bell Mobilité. ----------------------------------------------------------------- diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email6 b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email6 deleted file mode 100644 index 9c7b41a16..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email6 +++ /dev/null @@ -1,20 +0,0 @@ -Return-Path: -Received: from xxx.xxxx.xxx by xxx.xxxx.xxx with ESMTP id C1B953B4CB6 for ; Tue, 10 May 2005 15:27:05 -0500 -Received: from SMS-GTYxxx.xxxx.xxx by xxx.xxxx.xxx with ESMTP id ca for ; Tue, 10 May 2005 15:27:04 -0500 -Received: from xxx.xxxx.xxx by SMS-GTYxxx.xxxx.xxx with ESMTP id j4AKR3r23323 for ; Tue, 10 May 2005 15:27:03 -0500 -Date: Tue, 10 May 2005 15:27:03 -0500 -From: xxx@xxxx.xxx -Sender: xxx@xxxx.xxx -To: xxxxxxxxxxx@xxxx.xxxx.xxx -Message-Id: -X-Original-To: xxxxxxxxxxx@xxxx.xxxx.xxx -Delivered-To: xxx@xxxx.xxx -Importance: normal -Content-Type: text/plain; charset=us-ascii - -Test test. Hi. Waving. m - ----------------------------------------------------------------- -Sent via Bell Mobility's Text Messaging service. -Envoyé par le service de messagerie texte de Bell Mobilité. ----------------------------------------------------------------- diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email7 b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email7 deleted file mode 100644 index c8c8e3462..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email7 +++ /dev/null @@ -1,66 +0,0 @@ -Mime-Version: 1.0 (Apple Message framework v730) -Content-Type: multipart/mixed; boundary=Apple-Mail-13-196941151 -Message-Id: <9169D984-4E0B-45EF-82D4-8F5E53AD7012@example.com> -From: foo@example.com -Subject: testing -Date: Mon, 6 Jun 2005 22:21:22 +0200 -To: blah@example.com - - ---Apple-Mail-13-196941151 -Content-Type: multipart/mixed; - boundary=Apple-Mail-12-196940926 - - ---Apple-Mail-12-196940926 -Content-Transfer-Encoding: quoted-printable -Content-Type: text/plain; - charset=ISO-8859-1; - delsp=yes; - format=flowed - -This is the first part. - ---Apple-Mail-12-196940926 -Content-Transfer-Encoding: 7bit -Content-Type: text/x-ruby-script; - x-unix-mode=0666; - name="test.rb" -Content-Disposition: attachment; - filename=test.rb - -puts "testing, testing" - ---Apple-Mail-12-196940926 -Content-Transfer-Encoding: base64 -Content-Type: application/pdf; - x-unix-mode=0666; - name="test.pdf" -Content-Disposition: inline; - filename=test.pdf - -YmxhaCBibGFoIGJsYWg= - ---Apple-Mail-12-196940926 -Content-Transfer-Encoding: 7bit -Content-Type: text/plain; - charset=US-ASCII; - format=flowed - - - ---Apple-Mail-12-196940926-- - ---Apple-Mail-13-196941151 -Content-Transfer-Encoding: base64 -Content-Type: application/pkcs7-signature; - name=smime.p7s -Content-Disposition: attachment; - filename=smime.p7s - -jamisSqGSIb3DQEHAqCAMIjamisxCzAJBgUrDgMCGgUAMIAGCSqGSjamisEHAQAAoIIFSjCCBUYw -ggQujamisQICBD++ukQwDQYJKojamisNAQEFBQAwMTELMAkGA1UEBhMCRjamisAKBgNVBAoTA1RE -QzEUMBIGjamisxMLVERDIE9DRVMgQ0jamisNMDQwMjI5MTE1OTAxWhcNMDYwMjamisIyOTAxWjCB -gDELMAkGA1UEjamisEsxKTAnBgNVBAoTIEjamisuIG9yZ2FuaXNhdG9yaXNrIHRpbjamisRuaW5= - ---Apple-Mail-13-196941151-- diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email8 b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email8 deleted file mode 100644 index 5dbcd2a41..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email8 +++ /dev/null @@ -1,47 +0,0 @@ -From xxxxxxxxx.xxxxxxx@gmail.com Sun May 8 19:07:09 2005 -Return-Path: -Message-ID: -Date: Sun, 8 May 2005 14:09:11 -0500 -From: xxxxxxxxx xxxxxxx -Reply-To: xxxxxxxxx xxxxxxx -To: xxxxx xxxx -Subject: Fwd: Signed email causes file attachments -In-Reply-To: -Mime-Version: 1.0 -Content-Type: multipart/mixed; - boundary="----=_Part_5028_7368284.1115579351471" -References: - -------=_Part_5028_7368284.1115579351471 -Content-Type: text/plain; charset=ISO-8859-1 -Content-Transfer-Encoding: quoted-printable -Content-Disposition: inline - -We should not include these files or vcards as attachments. - ----------- Forwarded message ---------- -From: xxxxx xxxxxx -Date: May 8, 2005 1:17 PM -Subject: Signed email causes file attachments -To: xxxxxxx@xxxxxxxxxx.com - - -Hi, - -Test attachments oddly encoded with japanese charset. - - -------=_Part_5028_7368284.1115579351471 -Content-Type: application/octet-stream; name*=iso-2022-jp'ja'01%20Quien%20Te%20Dij%8aat.%20Pitbull.mp3 -Content-Transfer-Encoding: base64 -Content-Disposition: attachment - -MIAGCSqGSIb3DQEHAqCAMIACAQExCzAJBgUrDgMCGgUAMIAGCSqGSIb3DQEHAQAAoIIGFDCCAs0w -ggI2oAMCAQICAw5c+TANBgkqhkiG9w0BAQQFADBiMQswCQYDVQQGEwJaQTElMCMGA1UEChMcVGhh -d3RlIENvbnN1bHRpbmcgKFB0eSkgTHRkLjEsMCoGA1UEAxMjVGhhd3RlIFBlcnNvbmFsIEZyZWVt -YWlsIElzc3VpbmcgQ0EwHhcNMDUwMzI5MDkzOTEwWhcNMDYwMzI5MDkzOTEwWjBCMR8wHQYDVQQD -ExZUaGF3dGUgRnJlZW1haWwgTWVtYmVyMR8wHQYJKoZIhvcNAQkBFhBzbWhhdW5jaEBtYWMuY29t -MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn90dPsYS3LjfMY211OSYrDQLzwNYPlAL -7+/0XA+kdy8/rRnyEHFGwhNCDmg0B6pxC7z3xxJD/8GfCd+IYUUNUQV5m9MkxfP9pTVXZVIYLaBw -------=_Part_5028_7368284.1115579351471-- - diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email9 b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email9 deleted file mode 100644 index ca913778d..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email9 +++ /dev/null @@ -1,28 +0,0 @@ -Received: from xxx.xxx.xxx ([xxx.xxx.xxx.xxx] verified) - by xxx.com (CommuniGate Pro SMTP 4.2.8) - with SMTP id 2532598 for xxx@xxx.com; Wed, 23 Feb 2005 17:51:49 -0500 -Received-SPF: softfail - receiver=xxx.com; client-ip=xxx.xxx.xxx.xxx; envelope-from=xxx@xxx.xxx -quite Delivered-To: xxx@xxx.xxx -Received: by xxx.xxx.xxx (Wostfix, from userid xxx) - id 0F87F333; Wed, 23 Feb 2005 16:16:17 -0600 -Date: Wed, 23 Feb 2005 18:20:17 -0400 -From: "xxx xxx" -Message-ID: <4D6AA7EB.6490534@xxx.xxx> -To: xxx@xxx.com -Subject: Stop adware/spyware once and for all. -X-Scanned-By: MIMEDefang 2.11 (www dot roaringpenguin dot com slash mimedefang) - -You are infected with: -Ad Ware and Spy Ware - -Get your free scan and removal download now, -before it gets any worse. - -http://xxx.xxx.info?aid=3D13&?stat=3D4327kdzt - - - - -no more? (you will still be infected) -http://xxx.xxx.info/discon/?xxx@xxx.com diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email_quoted_with_0d0a b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email_quoted_with_0d0a deleted file mode 100644 index 8a2c25a5d..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email_quoted_with_0d0a +++ /dev/null @@ -1,14 +0,0 @@ -Mime-Version: 1.0 (Apple Message framework v730) -Message-Id: <9169D984-4E0B-45EF-82D4-8F5E53AD7012@example.com> -From: foo@example.com -Subject: testing -Date: Mon, 6 Jun 2005 22:21:22 +0200 -To: blah@example.com -Content-Transfer-Encoding: quoted-printable -Content-Type: text/plain - -A fax has arrived from remote ID ''.=0D=0A-----------------------= --------------------------------------=0D=0ATime: 3/9/2006 3:50:52= - PM=0D=0AReceived from remote ID: =0D=0AInbound user ID XXXXXXXXXX, r= -outing code XXXXXXXXX=0D=0AResult: (0/352;0/0) Successful Send=0D=0AP= -age record: 1 - 1=0D=0AElapsed time: 00:58 on channel 11=0D=0A diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email_with_invalid_characters_in_content_type b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email_with_invalid_characters_in_content_type deleted file mode 100644 index 15c0bc499..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email_with_invalid_characters_in_content_type +++ /dev/null @@ -1,104 +0,0 @@ -Return-Path: -Received: from some.isp.com by baci with ESMTP id 632BD5758 for ; Sun, 21 Oct 2007 19:38:21 +1000 -Date: Sun, 21 Oct 2007 19:38:13 +1000 -From: Mikel Lindsaar -Reply-To: Mikel Lindsaar -To: mikel.lindsaar@baci -Message-Id: <009601c813c6$19df3510$0437d30a@mikel091a> -Subject: Testing outlook -Mime-Version: 1.0 -Content-Type: multipart/alternative; boundary=----=_NextPart_000_0093_01C81419.EB75E850 -Delivered-To: mikel.lindsaar@baci -X-Mimeole: Produced By Microsoft MimeOLE V6.00.2900.3138 -X-Msmail-Priority: Normal - -This is a multi-part message in MIME format. - - -------=_NextPart_000_0093_01C81419.EB75E850 -Content-Type: text/plain; charset=iso-8859-1 -Content-Transfer-Encoding: Quoted-printable - -Hello -This is an outlook test - -So there. - -Me. - -------=_NextPart_000_0093_01C81419.EB75E850 -Content-Type: text/html; charset=iso-8859-1 -Content-Transfer-Encoding: Quoted-printable - - - - - - - - -
Hello
-
This is an outlook=20 -test
-
 
-
So there.
-
 
-
Me.
- - -------=_NextPart_000_0093_01C81419.EB75E850-- - - -Return-Path: -Received: from some.isp.com by baci with ESMTP id 632BD5758 for ; Sun, 21 Oct 2007 19:38:21 +1000 -Date: Sun, 21 Oct 2007 19:38:13 +1000 -From: Mikel Lindsaar -Reply-To: Mikel Lindsaar -To: mikel.lindsaar@baci -Message-Id: <009601c813c6$19df3510$0437d30a@mikel091a> -Subject: Testing outlook -Mime-Version: 1.0 -Content-Type: multipart/alternative; boundary=----=_NextPart_000_0093_01C81419.EB75E850 -Delivered-To: mikel.lindsaar@baci -X-Mimeole: Produced By Microsoft MimeOLE V6.00.2900.3138 -X-Msmail-Priority: Normal - -This is a multi-part message in MIME format. - - -------=_NextPart_000_0093_01C81419.EB75E850 -Content-Type: text/plain; charset=iso-8859-1 -Content-Transfer-Encoding: Quoted-printable - -Hello -This is an outlook test - -So there. - -Me. - -------=_NextPart_000_0093_01C81419.EB75E850 -Content-Type: text/html; charset=iso-8859-1 -Content-Transfer-Encoding: Quoted-printable - - - - - - - - -
Hello
-
This is an outlook=20 -test
-
 
-
So there.
-
 
-
Me.
- - -------=_NextPart_000_0093_01C81419.EB75E850-- - - diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email_with_nested_attachment b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email_with_nested_attachment deleted file mode 100644 index 9d49e6fab..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email_with_nested_attachment +++ /dev/null @@ -1,100 +0,0 @@ -From jamis@37signals.com Thu Feb 22 11:20:31 2007 -Mime-Version: 1.0 (Apple Message framework v752.3) -Message-Id: <2CCE0408-10C7-4045-9B16-A1C11C31469B@37signals.com> -Content-Type: multipart/signed; - micalg=sha1; - boundary=Apple-Mail-42-587703407; - protocol="application/pkcs7-signature" -To: Jamis Buck -Subject: Testing attachments -From: Jamis Buck -Date: Thu, 22 Feb 2007 11:20:31 -0700 - - ---Apple-Mail-42-587703407 -Content-Type: multipart/mixed; - boundary=Apple-Mail-41-587703287 - - ---Apple-Mail-41-587703287 -Content-Transfer-Encoding: 7bit -Content-Type: text/plain; - charset=US-ASCII; - format=flowed - -Here is a test of an attachment via email. - -- Jamis - - ---Apple-Mail-41-587703287 -Content-Transfer-Encoding: base64 -Content-Type: image/png; - x-unix-mode=0644; - name=byo-ror-cover.png -Content-Disposition: inline; - filename=truncated.png - -iVBORw0KGgoAAAANSUhEUgAAAKUAAADXCAYAAAB7wZEQAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz -AAALEgAACxIB0t1+/AAAABd0RVh0Q3JlYXRpb24gVGltZQAxLzI1LzIwMDeD9CJVAAAAGHRFWHRT -b2Z0d2FyZQBBZG9iZSBGaXJld29ya3NPsx9OAAAyBWlUWHRYTUw6Y29tLmFkb2JlLnhtcDw/eHBh -Y2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+Cjx4OnhtcG1l -dGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDQuMS1j -MDIwIDEuMjU1NzE2LCBUdWUgT2N0IDEwIDIwMDYgMjM6MTY6MzQiPgogICA8cmRmOlJERiB4bWxu -czpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAg -ICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczp4YXA9Imh0 -dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iPgogICAgICAgICA8eGFwOkNyZWF0b3JUb29sPkFk -b2JlIEZpcmV3b3JrcyBDUzM8L3hhcDpDcmVhdG9yVG9vbD4KICAgICAgICAgPHhhcDpDcmVhdGVE -YXRlPjIwMDctMDEtMjVUMDU6Mjg6MjFaPC94YXA6Q3JlYXRlRGF0ZT4KICAgICAgICAgPHhhcDpN -b2RpZnlEYXRlPjIwMDctMDEtMjVUMDU6Mjg6MjFaPC94YXA6TW9kaWZ5RGF0ZT4KICAgICAgPC9y -ZGY6RGVzY3JpcHRpb24+CiAgICAgIDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiCiAgICAg -ICAgICAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyI+CiAgICAg -ICAgIDxkYzpmb3JtYXQ+aW1hZ2UvcG5nPC9kYzpmb3JtYXQ+CiAgICAgIDwvcmRmOkRlc2NyaXB0 -hhojpmnJMfaYFmSkXWg5PGCmHXVj/c9At0hSK2xGdd8F3muk0VFjb4f5Ue0ksQ8qAcq0delaXhdb -DjKNnF+3B3t9kObZYmk7AZgWYqO9anpR3wpM9sQ5XslB9a+kWyTtNb0fOmudzGHfPFBQDKesyycm -DBL7Cw5bXjIEuci+SSOm/LYnXDZu6iuPEj8lYBb+OU8xx1f9m+e5rhJiYKqjo5vHfiZp+VUkW9xc -Ufd6JHNWc47PkQqb9ie3SLEZB/ZqyAssiqURY+G35iOMZUrHbasHnb80QAPv9FHtAbJIyro7bi5b -ai2TEAKen5+LJNWrglZjm3UbZvt7KryA2J5b5J1jZF8kL6GzvG1Zqx54Y1y7J7n20wMOt9frG2sW -uwGP07kNz3732vf6bfvAvLldfS+9fts2euXY37D+R29FGZdlnhzV4TTFmPJduBP2RbNNua4rTqcT -Qt7Xy1KUB0AHSdP5AZQYvHZg7WD1XvYeMO1A9HhZPqMX5KXbMBrn2efxns/ee21674efxz4Tp/fq -2HZ648dgYaC1i3Vq1IbNPq3PvDTPezY9FaRISjvnzWqdgcWN8EJgjnNq+Z7ktOm9l2Nfth28EZi4 -bG/we5JwxM+Tql47/D/X6b38I8/RyxvxPJrX6zvQbo3h9jyJx+C0ALX327QETHl5eYlaYCT5rPTb -+5/rAq26t3lKIxV/p88hq6ptngdgCzoPjJqndiLfc/6y5A14WeDFGNPct4iUsJBV2bYzLEV7m83s -6Rp63VPhHKC/g/LzaU9qexJRr56043JWinqAtfZqsSm1sjoznthl54dtCqv+uL4nIY+oYWuc3+nH -kGfn8b0HQpvOYLQAZUDanbJs3jQhITZEgdarZK+cO6ySlL13rut5nFaN23s7u3Snz6eRPTkCoc2/ -Vp1zHfZVFpZ87FiMVLV1iqyK5rlzfji2GzjfDsodlD+Weo5UD4h6PwKqzQMqID0tq2VjjFVSMpis -ZLRAs7sePZBZAHI+gIanB8I7MD+femAceeUe2Kxa5jS950kZ1p5eNEdeX1+jFmSpZ+1EdWCsDcne -NPNgUHNw3aYpnzv9PGTX0uo94EtN9qq1rOdxe3kc79T8ukeHJJ8Fnxej6qlylbLLsjQLOy6Xy2a1 -kefs/N+nM7+S7IG5/E5Yc7F003pWErLjbH0O5cGadiMptSB/DZ5U5DI9yeg5MFYyMj8lC/Y7/Xjq -OZlWcnpg9aQfXz2HRq+Wn5xOp6gN8tWq8R44e2pfyzLYemEgprst+XXk2Zj2nXlbsG05BprndTMv -C3QRaXczshhVsHnMgfYn80Y2g5JureA6wBasPeP7LkE/jvZMJAaf/g/U2RelHsisvan5FqweIAHg -Pwc7L68GxvVDAAAAAElFTkSuQmCC - ---Apple-Mail-41-587703287-- - ---Apple-Mail-42-587703407 -Content-Transfer-Encoding: base64 -Content-Type: application/pkcs7-signature; - name=smime.p7s -Content-Disposition: attachment; - filename=smime.p7s - -MIAGCSqGSIb3DQEHAqCAMIACAQExCzAJBgUrDgMCGgUAMIAGCSqGSIb3DQEHAQAAoIIGJzCCAuAw -ggJJoAMCAQICEFjnFNYXwDEZRWY5EkfzopUwDQYJKoZIhvcNAQEFBQAwYjELMAkGA1UEBhMCWkEx -JTAjBgNVBAoTHFRoYXd0ZSBDb25zdWx0aW5nIChQdHkpIEx0ZC4xLDAqBgNVBAMTI1RoYXd0ZSBQ -ZXJzb25hbCBGcmVlbWFpbCBJc3N1aW5nIENBMB4XDTA2MDkxMjE3MDExMloXDTA3MDkxMjE3MDEx -MlowRTEfMB0GA1UEAxMWVGhhd3RlIEZyZWVtYWlsIE1lbWJlcjEiMCAGCSqGSIb3DQEJARYTamFt -aXNAMzdzaWduYWxzLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAO2A9JeOFIFJ -G6z8pTcAldrZ2nMe+Xb1tNrbHgoVzN/QhHXM4qst2Ml93cmFLjMmwG7P9RJeU4oNx+jTqVoBB7NV -Ne1/o56Do0KhfMZ9iUDQdPLbkZMq4EEpFMdm6PyM3muRKwPhj66iAWe/osCb8DowUK2f66vaRx0Z -Y0MQHIIrXE02Ta4IfAhIfPqBLkZ4WgTYBHN9vMdYea1jF0GO4gqGk1wqwb3yxv2QMYMbwJ6SI+k/ -ZjkSR/OilTCBhwYLKoZIhvcNAQkQAgsxeKB2MGIxCzAJBgNVBAYTAlpBMSUwIwYDVQQKExxUaGF3 -dGUgQ29uc3VsdGluZyAoUHR5KSBMdGQuMSwwKgYDVQQDEyNUaGF3dGUgUGVyc29uYWwgRnJlZW1h -aWwgSXNzdWluZyBDQQIQWOcU1hfAMRlFZjkSR/OilTANBgkqhkiG9w0BAQEFAASCAQCfwQiC3v6/ -yleRDGv3bJ4nQYQ+c3mz3+mn3Xi6uU35n3piwxZZaWRdmLyiXPvU+QReHpSf3l2qsEZM3sdE0XF9 -eRul/+QTFJcDNXOEAxG1zC2Gpz+6c6RrX4Ou12Pwkp+pNrZWTSY/mZgdqcArupOBcZi7qBjoWcy5 -wb54dfvSSjrjmqLbkH/E8ww/6gGQuU/xXpAUZgUrTmQHrNKeIdSh5oDkOxFaFWvnmb8Z/2ixKqW/ -Ux6WqamyvBtTs/5YBEtnpZOk+uVoscYEUBhU+DVJ2OSvTdXSivMtBdXmGTsG22k+P1NGUHi/A7ev -xPaO0uk4V8xyjNlN4HPuGpkrlXwPAAAAAAAA - ---Apple-Mail-42-587703407-- diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email_with_partially_quoted_subject b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email_with_partially_quoted_subject deleted file mode 100644 index d8df28519..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/raw_email_with_partially_quoted_subject +++ /dev/null @@ -1,14 +0,0 @@ -From jamis@37signals.com Mon May 2 16:07:05 2005 -Mime-Version: 1.0 (Apple Message framework v622) -Content-Transfer-Encoding: base64 -Message-Id: -Content-Type: text/plain; - charset=EUC-KR; - format=flowed -To: jamis@37signals.com -From: Jamis Buck -Subject: Re: Test: =?UTF-8?B?Iua8ouWtlyI=?= mid =?UTF-8?B?Iua8ouWtlyI=?= tail -Date: Mon, 2 May 2005 16:07:05 -0600 - -tOu6zrrQwMcguLbC+bChwfa3ziwgv+y4rrTCIMfPs6q01MC7ILnPvcC0z7TZLg0KDQrBpiDAzLin -wLogSmFtaXPA1LTPtNku diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/second_mailer/share.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/second_mailer/share.erb deleted file mode 100644 index ba83285d3..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/second_mailer/share.erb +++ /dev/null @@ -1 +0,0 @@ -second mail diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/templates/signed_up.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/templates/signed_up.erb deleted file mode 100644 index 855338f1b..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/templates/signed_up.erb +++ /dev/null @@ -1,3 +0,0 @@ -Hello there, - -Mr. <%= @recipient %> \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/_subtemplate.text.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/_subtemplate.text.erb deleted file mode 100644 index 3b4ba35f2..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/_subtemplate.text.erb +++ /dev/null @@ -1 +0,0 @@ -let's go! \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/custom_templating_extension.html.haml b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/custom_templating_extension.html.haml deleted file mode 100644 index 8d53e36ad..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/custom_templating_extension.html.haml +++ /dev/null @@ -1,6 +0,0 @@ -%p Hello there, - -%p - Mr. - = @recipient - from haml \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/custom_templating_extension.text.haml b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/custom_templating_extension.text.haml deleted file mode 100644 index 8d53e36ad..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/custom_templating_extension.text.haml +++ /dev/null @@ -1,6 +0,0 @@ -%p Hello there, - -%p - Mr. - = @recipient - from haml \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.html.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.html.erb deleted file mode 100644 index eb35238e1..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.html.erb +++ /dev/null @@ -1,10 +0,0 @@ - - - HTML formatted message to <%= @recipient %>. - - - - - HTML formatted message to <%= @recipient %>. - - diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.html.erb~ b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.html.erb~ deleted file mode 100644 index eb35238e1..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.html.erb~ +++ /dev/null @@ -1,10 +0,0 @@ - - - HTML formatted message to <%= @recipient %>. - - - - - HTML formatted message to <%= @recipient %>. - - diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.ignored.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.ignored.erb deleted file mode 100644 index 4e67465d3..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.ignored.erb +++ /dev/null @@ -1 +0,0 @@ -Ignored when searching for implicitly multipart parts. diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.text.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.text.erb deleted file mode 100644 index 5335cf6bd..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.text.erb +++ /dev/null @@ -1,2 +0,0 @@ -Plain text to <%= @recipient %>. -Plain text to <%= @recipient %>. diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.yaml.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.yaml.erb deleted file mode 100644 index c14348c77..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.yaml.erb +++ /dev/null @@ -1 +0,0 @@ -yaml to: <%= @recipient %> \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/included_subtemplate.text.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/included_subtemplate.text.erb deleted file mode 100644 index a93c30ea1..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/included_subtemplate.text.erb +++ /dev/null @@ -1 +0,0 @@ -Hey Ho, <%= render :partial => "subtemplate" %> \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/multipart_alternative.html.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/multipart_alternative.html.erb deleted file mode 100644 index 73ea14f82..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/multipart_alternative.html.erb +++ /dev/null @@ -1 +0,0 @@ -foo <%= @foo %> \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/multipart_alternative.plain.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/multipart_alternative.plain.erb deleted file mode 100644 index 779fe4c1e..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/multipart_alternative.plain.erb +++ /dev/null @@ -1 +0,0 @@ -foo: <%= @foo %> \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/rxml_template.rxml b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/rxml_template.rxml deleted file mode 100644 index 6b87e6ae1..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/rxml_template.rxml +++ /dev/null @@ -1,2 +0,0 @@ -xml.instruct! -xml.test \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/signed_up.html.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/signed_up.html.erb deleted file mode 100644 index 855338f1b..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/test_mailer/signed_up.html.erb +++ /dev/null @@ -1,3 +0,0 @@ -Hello there, - -Mr. <%= @recipient %> \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/url_test_mailer/signed_up_with_url.erb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/url_test_mailer/signed_up_with_url.erb deleted file mode 100644 index f3a7b3c0b..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/fixtures/url_test_mailer/signed_up_with_url.erb +++ /dev/null @@ -1,5 +0,0 @@ -Hello there, - -Mr. <%= @recipient %>. Please see our greeting at <%= @welcome_url %> <%= welcome_url %> - -<%= image_tag "somelogo.png" %> \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/log_subscriber_test.rb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/log_subscriber_test.rb deleted file mode 100644 index 21a8505d2..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/log_subscriber_test.rb +++ /dev/null @@ -1,48 +0,0 @@ -require "abstract_unit" -require "active_support/log_subscriber/test_helper" -require "action_mailer/log_subscriber" - -class AMLogSubscriberTest < ActionMailer::TestCase - include ActiveSupport::LogSubscriber::TestHelper - - def setup - super - ActionMailer::LogSubscriber.attach_to :action_mailer - end - - class TestMailer < ActionMailer::Base - def basic - recipients "somewhere@example.com" - subject "basic" - from "basic@example.com" - body "Hello world" - end - - def receive(mail) - # Do nothing - end - end - - def set_logger(logger) - ActionMailer::Base.logger = logger - end - - def test_deliver_is_notified - TestMailer.basic.deliver - wait - assert_equal(1, @logger.logged(:info).size) - assert_match(/Sent mail to somewhere@example.com/, @logger.logged(:info).first) - assert_equal(1, @logger.logged(:debug).size) - assert_match(/Hello world/, @logger.logged(:debug).first) - end - - def test_receive_is_notified - fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email") - TestMailer.receive(fixture) - wait - assert_equal(1, @logger.logged(:info).size) - assert_match(/Received mail/, @logger.logged(:info).first) - assert_equal(1, @logger.logged(:debug).size) - assert_match(/Jamis/, @logger.logged(:debug).first) - end -end \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/mail_helper_test.rb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/mail_helper_test.rb deleted file mode 100644 index e93462088..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/mail_helper_test.rb +++ /dev/null @@ -1,54 +0,0 @@ -require 'abstract_unit' - -class HelperMailer < ActionMailer::Base - def use_mail_helper - @text = "But soft! What light through yonder window breaks? It is the east, " + - "and Juliet is the sun. Arise, fair sun, and kill the envious moon, " + - "which is sick and pale with grief that thou, her maid, art far more " + - "fair than she. Be not her maid, for she is envious! Her vestal " + - "livery is but sick and green, and none but fools do wear it. Cast " + - "it off!" - - mail_with_defaults do |format| - format.html { render(:inline => "<%= block_format @text %>") } - end - end - - def use_mailer - mail_with_defaults do |format| - format.html { render(:inline => "<%= mailer.message.subject %>") } - end - end - - def use_message - mail_with_defaults do |format| - format.html { render(:inline => "<%= message.subject %>") } - end - end - - protected - - def mail_with_defaults(&block) - mail(:to => "test@localhost", :from => "tester@example.com", - :subject => "using helpers", &block) - end -end - -class MailerHelperTest < ActionMailer::TestCase - def test_use_mail_helper - mail = HelperMailer.use_mail_helper - assert_match %r{ But soft!}, mail.body.encoded - assert_match %r{east, and\r\n Juliet}, mail.body.encoded - end - - def test_use_mailer - mail = HelperMailer.use_mailer - assert_match "using helpers", mail.body.encoded - end - - def test_use_message - mail = HelperMailer.use_message - assert_match "using helpers", mail.body.encoded - end -end - diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/mailers/asset_mailer.rb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/mailers/asset_mailer.rb deleted file mode 100644 index 41252259d..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/mailers/asset_mailer.rb +++ /dev/null @@ -1,7 +0,0 @@ -class AssetMailer < ActionMailer::Base - self.mailer_name = "asset_mailer" - - def welcome - mail - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/mailers/base_mailer.rb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/mailers/base_mailer.rb deleted file mode 100644 index cfc6cdd19..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/mailers/base_mailer.rb +++ /dev/null @@ -1,130 +0,0 @@ -class BaseMailer < ActionMailer::Base - self.mailer_name = "base_mailer" - - default :to => 'system@test.lindsaar.net', - :from => 'jose@test.plataformatec.com', - :reply_to => 'mikel@test.lindsaar.net' - - def welcome(hash = {}) - headers['X-SPAM'] = "Not SPAM" - mail({:subject => "The first email on new API!"}.merge!(hash)) - end - - def welcome_with_fixnum_header(hash = {}) - headers['X-SPAM-COUNT'] = 2 - mail({:template_name => "welcome", :subject => "The first email on new API!"}.merge!(hash)) - end - - def welcome_with_headers(hash = {}) - headers hash - mail - end - - def welcome_from_another_path(path) - mail(:template_name => "welcome", :template_path => path) - end - - def html_only(hash = {}) - mail(hash) - end - - def plain_text_only(hash = {}) - mail(hash) - end - - def inline_attachment - attachments.inline['logo.png'] = "\312\213\254\232" - mail - end - - def attachment_with_content(hash = {}) - attachments['invoice.pdf'] = 'This is test File content' - mail(hash) - end - - def attachment_with_hash - attachments['invoice.jpg'] = { :data => "\312\213\254\232)b", - :mime_type => "image/x-jpg", - :transfer_encoding => "base64" } - mail - end - - def attachment_with_hash_default_encoding - attachments['invoice.jpg'] = { :data => "\312\213\254\232)b", - :mime_type => "image/x-jpg" } - mail - end - - def implicit_multipart(hash = {}) - attachments['invoice.pdf'] = 'This is test File content' if hash.delete(:attachments) - mail(hash) - end - - def implicit_with_locale(hash = {}) - mail(hash) - end - - def explicit_multipart(hash = {}) - attachments['invoice.pdf'] = 'This is test File content' if hash.delete(:attachments) - mail(hash) do |format| - format.text { render :text => "TEXT Explicit Multipart" } - format.html { render :text => "HTML Explicit Multipart" } - end - end - - def explicit_multipart_templates(hash = {}) - mail(hash) do |format| - format.html - format.text - end - end - - def explicit_multipart_with_any(hash = {}) - mail(hash) do |format| - format.any(:text, :html){ render :text => "Format with any!" } - end - end - - def explicit_multipart_with_options(include_html = false) - mail do |format| - format.text(:content_transfer_encoding => "base64"){ render "welcome" } - format.html{ render "welcome" } if include_html - end - end - - def explicit_multipart_with_one_template(hash = {}) - mail(hash) do |format| - format.html - format.text - end - end - - def implicit_different_template(template_name='') - mail(:template_name => template_name) - end - - def implicit_different_template_with_file(template_name='') - mail do |format| - format.text { render :file => template_name } - format.html { render :file => template_name } - end - end - - def explicit_different_template(template_name='') - mail do |format| - format.text { render :template => "#{mailer_name}/#{template_name}" } - format.html { render :template => "#{mailer_name}/#{template_name}" } - end - end - - def different_layout(layout_name='') - mail do |format| - format.text { render :layout => layout_name } - format.html { render :layout => layout_name } - end - end - - def email_with_translations - body render("email_with_translations.html") - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/mailers/proc_mailer.rb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/mailers/proc_mailer.rb deleted file mode 100644 index aa6dab1ba..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/mailers/proc_mailer.rb +++ /dev/null @@ -1,16 +0,0 @@ -class ProcMailer < ActionMailer::Base - default :to => 'system@test.lindsaar.net', - 'X-Proc-Method' => Proc.new { Time.now.to_i.to_s }, - :subject => Proc.new { give_a_greeting } - - def welcome - mail - end - - private - - def give_a_greeting - "Thanks for signing up this afternoon" - end - -end diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/old_base/adv_attr_test.rb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/old_base/adv_attr_test.rb deleted file mode 100644 index a1bab9483..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/old_base/adv_attr_test.rb +++ /dev/null @@ -1,36 +0,0 @@ -require 'abstract_unit' -require 'action_mailer/adv_attr_accessor' - -class AdvAttrTest < ActiveSupport::TestCase - class Person - cattr_reader :protected_instance_variables - @@protected_instance_variables = [] - - extend ActionMailer::AdvAttrAccessor - adv_attr_accessor :name - end - - def setup - @person = Person.new - end - - def test_adv_attr - assert_nil @person.name - @person.name 'Bob' - assert_equal 'Bob', @person.name - end - - def test_adv_attr_writer - assert_nil @person.name - @person.name = 'Bob' - assert_equal 'Bob', @person.name - end - - def test_raise_an_error_with_multiple_args - assert_raise(ArgumentError) { @person.name('x', 'y') } - end - - def test_ivar_is_added_to_protected_instnace_variables - assert Person.protected_instance_variables.include?('@name') - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/old_base/asset_host_test.rb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/old_base/asset_host_test.rb deleted file mode 100644 index fe1a16582..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/old_base/asset_host_test.rb +++ /dev/null @@ -1,56 +0,0 @@ -require 'abstract_unit' -require 'action_controller' - -class AssetHostMailer < ActionMailer::Base - def email_with_asset - recipients 'test@localhost' - subject "testing email containing asset path while asset_host is set" - from "tester@example.com" - end -end - -class AssetHostTest < Test::Unit::TestCase - def setup - set_delivery_method :test - ActionMailer::Base.perform_deliveries = true - ActionMailer::Base.deliveries.clear - AssetHostMailer.configure do |c| - c.asset_host = "http://www.example.com" - c.assets_dir = '' - end - end - - def teardown - restore_delivery_method - end - - def test_asset_host_as_string - mail = AssetHostMailer.email_with_asset - assert_equal %Q{Somelogo}, mail.body.to_s.strip - end - - def test_asset_host_as_one_arguement_proc - AssetHostMailer.config.asset_host = Proc.new { |source| - if source.starts_with?('/images') - "http://images.example.com" - else - "http://assets.example.com" - end - } - mail = AssetHostMailer.email_with_asset - assert_equal %Q{Somelogo}, mail.body.to_s.strip - end - - def test_asset_host_as_two_arguement_proc - ActionController::Base.config.asset_host = Proc.new {|source,request| - if request && request.ssl? - "https://www.example.com" - else - "http://www.example.com" - end - } - mail = nil - assert_nothing_raised { mail = AssetHostMailer.email_with_asset } - assert_equal %Q{Somelogo}, mail.body.to_s.strip - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/old_base/mail_layout_test.rb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/old_base/mail_layout_test.rb deleted file mode 100644 index 325dbaa27..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/old_base/mail_layout_test.rb +++ /dev/null @@ -1,126 +0,0 @@ -require 'abstract_unit' - -class AutoLayoutMailer < ActionMailer::Base - - def hello - recipients 'test@localhost' - subject "You have a mail" - from "tester@example.com" - end - - def spam - recipients 'test@localhost' - subject "You have a mail" - from "tester@example.com" - - @world = "Earth" - body render(:inline => "Hello, <%= @world %>", :layout => 'spam') - end - - def nolayout - recipients 'test@localhost' - subject "You have a mail" - from "tester@example.com" - - @world = "Earth" - body render(:inline => "Hello, <%= @world %>", :layout => false) - end - - def multipart(type = nil) - recipients 'test@localhost' - subject "You have a mail" - from "tester@example.com" - - content_type(type) if type - end -end - -class ExplicitLayoutMailer < ActionMailer::Base - layout 'spam', :except => [:logout] - - def signup - recipients 'test@localhost' - subject "You have a mail" - from "tester@example.com" - end - - def logout - recipients 'test@localhost' - subject "You have a mail" - from "tester@example.com" - end -end - -class LayoutMailerTest < Test::Unit::TestCase - def setup - set_delivery_method :test - ActionMailer::Base.perform_deliveries = true - ActionMailer::Base.deliveries.clear - end - - def teardown - restore_delivery_method - end - - def test_should_pickup_default_layout - mail = AutoLayoutMailer.hello - assert_equal "Hello from layout Inside", mail.body.to_s.strip - end - - def test_should_pickup_multipart_layout - mail = AutoLayoutMailer.multipart - assert_equal "multipart/alternative", mail.mime_type - assert_equal 2, mail.parts.size - - assert_equal 'text/plain', mail.parts.first.mime_type - assert_equal "text/plain layout - text/plain multipart", mail.parts.first.body.to_s - - assert_equal 'text/html', mail.parts.last.mime_type - assert_equal "Hello from layout text/html multipart", mail.parts.last.body.to_s - end - - def test_should_pickup_multipartmixed_layout - mail = AutoLayoutMailer.multipart("multipart/mixed") - assert_equal "multipart/mixed", mail.mime_type - assert_equal 2, mail.parts.size - - assert_equal 'text/plain', mail.parts.first.mime_type - assert_equal "text/plain layout - text/plain multipart", mail.parts.first.body.to_s - - assert_equal 'text/html', mail.parts.last.mime_type - assert_equal "Hello from layout text/html multipart", mail.parts.last.body.to_s - end - - def test_should_fix_multipart_layout - mail = AutoLayoutMailer.multipart("text/plain") - assert_equal "multipart/alternative", mail.mime_type - assert_equal 2, mail.parts.size - - assert_equal 'text/plain', mail.parts.first.mime_type - assert_equal "text/plain layout - text/plain multipart", mail.parts.first.body.to_s - - assert_equal 'text/html', mail.parts.last.mime_type - assert_equal "Hello from layout text/html multipart", mail.parts.last.body.to_s - end - - - def test_should_pickup_layout_given_to_render - mail = AutoLayoutMailer.spam - assert_equal "Spammer layout Hello, Earth", mail.body.to_s.strip - end - - def test_should_respect_layout_false - mail = AutoLayoutMailer.nolayout - assert_equal "Hello, Earth", mail.body.to_s.strip - end - - def test_explicit_class_layout - mail = ExplicitLayoutMailer.signup - assert_equal "Spammer layout We do not spam", mail.body.to_s.strip - end - - def test_explicit_layout_exceptions - mail = ExplicitLayoutMailer.logout - assert_equal "You logged out", mail.body.to_s.strip - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/old_base/mail_render_test.rb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/old_base/mail_render_test.rb deleted file mode 100644 index be9048099..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/old_base/mail_render_test.rb +++ /dev/null @@ -1,167 +0,0 @@ -require 'abstract_unit' - -class RenderMailer < ActionMailer::Base - def inline_template - recipients 'test@localhost' - subject "using helpers" - from "tester@example.com" - - @world = "Earth" - body render(:inline => "Hello, <%= @world %>") - end - - def file_template - recipients 'test@localhost' - subject "using helpers" - from "tester@example.com" - - @recipient = 'test@localhost' - body render(:file => "templates/signed_up") - end - - def rxml_template - recipients 'test@localhost' - subject "rendering rxml template" - from "tester@example.com" - end - - def included_subtemplate - recipients 'test@localhost' - subject "Including another template in the one being rendered" - from "tester@example.com" - end - - def no_instance_variable - recipients 'test@localhost' - subject "No Instance Variable" - from "tester@example.com" - - silence_warnings do - body render(:inline => "Look, subject.nil? is <%= @subject.nil? %>!") - end - end - - def initialize_defaults(method_name) - super - mailer_name "test_mailer" - end - - def multipart_alternative - recipients 'test@localhost' - subject 'multipart/alternative' - from 'tester@example.com' - - build_multipart_message(:foo => "bar") - end - - private - def build_multipart_message(assigns = {}) - content_type "multipart/alternative" - - part "text/plain" do |p| - p.body = build_body_part('plain', assigns, :layout => false) - end - - part "text/html" do |p| - p.body = build_body_part('html', assigns) - end - end - - def build_body_part(content_type, assigns, options = {}) - ActiveSupport::Deprecation.silence do - render "#{template}.#{content_type}", :body => assigns - end - end -end - -class FirstMailer < ActionMailer::Base - def share - recipients 'test@localhost' - subject "using helpers" - from "tester@example.com" - end -end - -class SecondMailer < ActionMailer::Base - def share - recipients 'test@localhost' - subject "using helpers" - from "tester@example.com" - end -end - -# CHANGED: Those tests were changed because body returns an object now -# Instead of mail.body.strip, we should mail.body.to_s.strip -class RenderHelperTest < Test::Unit::TestCase - def setup - set_delivery_method :test - ActionMailer::Base.perform_deliveries = true - ActionMailer::Base.deliveries.clear - - @recipient = 'test@localhost' - end - - def teardown - restore_delivery_method - end - - def test_inline_template - mail = RenderMailer.inline_template - assert_equal "Hello, Earth", mail.body.to_s.strip - end - - def test_file_template - mail = RenderMailer.file_template - assert_equal "Hello there,\n\nMr. test@localhost", mail.body.to_s.strip - end - - def test_rxml_template - mail = RenderMailer.rxml_template.deliver - assert_equal %(\n), mail.body.to_s.strip - end - - def test_included_subtemplate - mail = RenderMailer.included_subtemplate.deliver - assert_equal "Hey Ho, let's go!", mail.body.to_s.strip - end - - def test_no_instance_variable - mail = RenderMailer.no_instance_variable.deliver - assert_equal "Look, subject.nil? is true!", mail.body.to_s.strip - end - - def test_legacy_multipart_alternative - mail = RenderMailer.multipart_alternative.deliver - assert_equal(2, mail.parts.size) - assert_equal("multipart/alternative", mail.mime_type) - assert_equal("text/plain", mail.parts[0].mime_type) - assert_equal("foo: bar", mail.parts[0].body.encoded) - assert_equal("text/html", mail.parts[1].mime_type) - assert_equal("foo bar", mail.parts[1].body.encoded) - end -end - -class FirstSecondHelperTest < Test::Unit::TestCase - def setup - set_delivery_method :test - ActionMailer::Base.perform_deliveries = true - ActionMailer::Base.deliveries.clear - - @recipient = 'test@localhost' - end - - def teardown - restore_delivery_method - end - - def test_ordering - mail = FirstMailer.share - assert_equal "first mail", mail.body.to_s.strip - mail = SecondMailer.share - assert_equal "second mail", mail.body.to_s.strip - mail = FirstMailer.share - assert_equal "first mail", mail.body.to_s.strip - mail = SecondMailer.share - assert_equal "second mail", mail.body.to_s.strip - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/old_base/mail_service_test.rb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/old_base/mail_service_test.rb deleted file mode 100644 index acc318ade..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/old_base/mail_service_test.rb +++ /dev/null @@ -1,1206 +0,0 @@ -# encoding: utf-8 -require 'abstract_unit' - -class FunkyPathMailer < ActionMailer::Base - self.view_paths = "#{File.dirname(__FILE__)}/../fixtures/path.with.dots" - - def multipart_with_template_path_with_dots(recipient) - recipients recipient - subject "This path has dots" - from "Chad Fowler " - attachment :content_type => "text/plain", - :data => "dots dots dots..." - end -end - -class TestMailer < ActionMailer::Base - def signed_up(recipient) - recipients recipient - subject "[Signed up] Welcome #{recipient}" - from "system@loudthinking.com" - - @recipient = recipient - end - - def cancelled_account(recipient) - recipients recipient - subject "[Cancelled] Goodbye #{recipient}" - from "system@loudthinking.com" - sent_on Time.local(2004, 12, 12) - body "Goodbye, Mr. #{recipient}" - end - - def from_with_name - from "System " - recipients "root@loudthinking.com" - body "Nothing to see here." - end - - def from_without_name - from "system@loudthinking.com" - recipients "root@loudthinking.com" - body "Nothing to see here." - end - - def cc_bcc(recipient) - recipients recipient - subject "testing bcc/cc" - from "system@loudthinking.com" - sent_on Time.local(2004, 12, 12) - cc "nobody@loudthinking.com" - bcc "root@loudthinking.com" - - body "Nothing to see here." - end - - def different_reply_to(recipient) - recipients recipient - subject "testing reply_to" - from "system@loudthinking.com" - sent_on Time.local(2008, 5, 23) - reply_to "atraver@gmail.com" - - body "Nothing to see here." - end - - def iso_charset(recipient) - recipients recipient - subject "testing isø charsets" - from "system@loudthinking.com" - sent_on Time.local(2004, 12, 12) - cc "nobody@loudthinking.com" - bcc "root@loudthinking.com" - charset "iso-8859-1" - - body "Nothing to see here." - end - - def unencoded_subject(recipient) - recipients recipient - subject "testing unencoded subject" - from "system@loudthinking.com" - sent_on Time.local(2004, 12, 12) - cc "nobody@loudthinking.com" - bcc "root@loudthinking.com" - - body "Nothing to see here." - end - - def extended_headers(recipient) - recipients recipient - subject "testing extended headers" - from "Grytøyr " - sent_on Time.local(2004, 12, 12) - cc "Grytøyr " - bcc "Grytøyr " - charset "iso-8859-1" - - body "Nothing to see here." - end - - def utf8_body(recipient) - recipients recipient - subject "testing utf-8 body" - from "Foo áëô îü " - sent_on Time.local(2004, 12, 12) - cc "Foo áëô îü " - bcc "Foo áëô îü " - charset "UTF-8" - - body "åœö blah" - end - - def multipart_with_mime_version(recipient) - recipients recipient - subject "multipart with mime_version" - from "test@example.com" - sent_on Time.local(2004, 12, 12) - mime_version "1.1" - content_type "multipart/alternative" - - part "text/plain" do |p| - p.body = render(:text => "blah") - end - - part "text/html" do |p| - p.body = render(:inline => "<%= content_tag(:b, 'blah') %>") - end - end - - def multipart_with_utf8_subject(recipient) - recipients recipient - subject "Foo áëô îü" - from "test@example.com" - charset "UTF-8" - - part "text/plain" do |p| - p.body = "blah" - end - - part "text/html" do |p| - p.body = "blah" - end - end - - def explicitly_multipart_example(recipient, ct=nil) - recipients recipient - subject "multipart example" - from "test@example.com" - sent_on Time.local(2004, 12, 12) - content_type ct if ct - - part "text/html" do |p| - p.charset = "iso-8859-1" - p.body = "blah" - end - - attachment :content_type => "image/jpeg", :filename => File.join(File.dirname(__FILE__), "fixtures", "attachments", "foo.jpg"), - :data => "123456789" - - body "plain text default" - end - - def implicitly_multipart_example(recipient, cs = nil, order = nil) - recipients recipient - subject "multipart example" - from "test@example.com" - sent_on Time.local(2004, 12, 12) - - @charset = cs if cs - @recipient = recipient - @implicit_parts_order = order if order - end - - def implicitly_multipart_with_utf8 - recipients "no.one@nowhere.test" - subject "Foo áëô îü" - from "some.one@somewhere.test" - template "implicitly_multipart_example" - - @recipient = "no.one@nowhere.test" - end - - def html_mail(recipient) - recipients recipient - subject "html mail" - from "test@example.com" - content_type "text/html" - - body "Emphasize this" - end - - def html_mail_with_underscores(recipient) - subject "html mail with underscores" - body %{_Google} - end - - def custom_template(recipient) - recipients recipient - subject "[Signed up] Welcome #{recipient}" - from "system@loudthinking.com" - sent_on Time.local(2004, 12, 12) - template "signed_up" - - @recipient = recipient - end - - def custom_templating_extension(recipient) - recipients recipient - subject "[Signed up] Welcome #{recipient}" - from "system@loudthinking.com" - sent_on Time.local(2004, 12, 12) - - @recipient = recipient - end - - def various_newlines(recipient) - recipients recipient - subject "various newlines" - from "test@example.com" - - body "line #1\nline #2\rline #3\r\nline #4\r\r" + - "line #5\n\nline#6\r\n\r\nline #7" - end - - def various_newlines_multipart(recipient) - recipients recipient - subject "various newlines multipart" - from "test@example.com" - content_type "multipart/alternative" - - part :content_type => "text/plain", :body => "line #1\nline #2\rline #3\r\nline #4\r\r" - part :content_type => "text/html", :body => "

line #1

\n

line #2

\r

line #3

\r\n

line #4

\r\r" - end - - def nested_multipart(recipient) - recipients recipient - subject "nested multipart" - from "test@example.com" - content_type "multipart/mixed" - - part :content_type => "multipart/alternative", :content_disposition => "inline", "foo" => "bar" do |p| - p.part :content_type => "text/plain", :body => "test text\nline #2" - p.part :content_type => "text/html", :body => "test HTML
\nline #2" - end - - attachment :content_type => "application/octet-stream", :filename => "test.txt", :data => "test abcdefghijklmnopqstuvwxyz" - end - - def nested_multipart_with_body(recipient) - recipients recipient - subject "nested multipart with body" - from "test@example.com" - content_type "multipart/mixed" - - part :content_type => "multipart/alternative", :content_disposition => "inline", :body => "Nothing to see here." do |p| - p.part :content_type => "text/html", :body => "test HTML
" - end - end - - def attachment_with_custom_header(recipient) - recipients recipient - subject "custom header in attachment" - from "test@example.com" - content_type "multipart/related" - part :content_type => "text/html", :body => 'yo' - attachment :content_type => "image/jpeg", :filename => File.join(File.dirname(__FILE__), "fixtures", "attachments", "test.jpg"), :data => "i am not a real picture", 'Content-ID' => '' - end - - def unnamed_attachment(recipient) - recipients recipient - subject "nested multipart" - from "test@example.com" - content_type "multipart/mixed" - part :content_type => "text/plain", :body => "hullo" - attachment :content_type => "application/octet-stream", :data => "test abcdefghijklmnopqstuvwxyz" - end - - def headers_with_nonalpha_chars(recipient) - recipients recipient - subject "nonalpha chars" - from "One: Two " - cc "Three: Four " - bcc "Five: Six " - body "testing" - end - - def custom_content_type_attributes - recipients "no.one@nowhere.test" - subject "custom content types" - from "some.one@somewhere.test" - content_type "text/plain; format=flowed" - body "testing" - end - - def return_path - recipients "no.one@nowhere.test" - subject "return path test" - from "some.one@somewhere.test" - headers["return-path"] = "another@somewhere.test" - body "testing" - end - - def subject_with_i18n(recipient) - recipients recipient - from "system@loudthinking.com" - body "testing" - end - - class << self - attr_accessor :received_body - end - - def receive(mail) - self.class.received_body = mail.body - end -end - -class ActionMailerTest < Test::Unit::TestCase - - def encode( text, charset="UTF-8" ) - Mail::Encodings.q_value_encode( text, charset ) - end - - def new_mail( charset="UTF-8" ) - mail = Mail.new - mail.charset = charset - mail.mime_version = "1.0" - mail - end - - # Replacing logger work around for mocha bug. Should be fixed in mocha 0.3.3 - def setup - set_delivery_method :test - ActionMailer::Base.perform_deliveries = true - ActionMailer::Base.raise_delivery_errors = true - ActionMailer::Base.deliveries.clear - - @original_logger = TestMailer.logger - @recipient = 'test@localhost' - - TestMailer.delivery_method = :test - end - - def teardown - TestMailer.logger = @original_logger - restore_delivery_method - end - - def test_nested_parts - created = nil - assert_nothing_raised { created = TestMailer.nested_multipart(@recipient)} - assert_equal 2, created.parts.size - assert_equal 2, created.parts.first.parts.size - - assert_equal "multipart/mixed", created.mime_type - assert_equal "multipart/alternative", created.parts[0].mime_type - assert_equal "bar", created.parts[0].header['foo'].to_s - assert_not_nil created.parts[0].charset - assert_equal "text/plain", created.parts[0].parts[0].mime_type - assert_equal "text/html", created.parts[0].parts[1].mime_type - assert_equal "application/octet-stream", created.parts[1].mime_type - - end - - def test_nested_parts_with_body - created = nil - TestMailer.nested_multipart_with_body(@recipient) - assert_nothing_raised { created = TestMailer.nested_multipart_with_body(@recipient)} - - assert_equal 1,created.parts.size - assert_equal 2,created.parts.first.parts.size - - assert_equal "multipart/mixed", created.mime_type - assert_equal "multipart/alternative", created.parts.first.mime_type - assert_equal "text/plain", created.parts.first.parts.first.mime_type - assert_equal "Nothing to see here.", created.parts.first.parts.first.body.to_s - assert_equal "text/html", created.parts.first.parts.second.mime_type - assert_equal "test HTML
", created.parts.first.parts.second.body.to_s - end - - def test_attachment_with_custom_header - created = nil - assert_nothing_raised { created = TestMailer.attachment_with_custom_header(@recipient) } - assert created.parts.any? { |p| p.header['content-id'].to_s == "" } - end - - def test_signed_up - TestMailer.delivery_method = :test - - Time.stubs(:now => Time.now) - - expected = new_mail - expected.to = @recipient - expected.subject = "[Signed up] Welcome #{@recipient}" - expected.body = "Hello there,\n\nMr. #{@recipient}" - expected.from = "system@loudthinking.com" - expected.date = Time.now - - created = nil - assert_nothing_raised { created = TestMailer.signed_up(@recipient) } - assert_not_nil created - - expected.message_id = '<123@456>' - created.message_id = '<123@456>' - - assert_equal expected.encoded, created.encoded - - assert_nothing_raised { TestMailer.signed_up(@recipient).deliver } - - delivered = ActionMailer::Base.deliveries.first - assert_not_nil delivered - - expected.message_id = '<123@456>' - delivered.message_id = '<123@456>' - - assert_equal expected.encoded, delivered.encoded - end - - def test_custom_template - expected = new_mail - expected.to = @recipient - expected.subject = "[Signed up] Welcome #{@recipient}" - expected.body = "Hello there,\n\nMr. #{@recipient}" - expected.from = "system@loudthinking.com" - expected.date = Time.local(2004, 12, 12) - - created = nil - assert_nothing_raised { created = TestMailer.custom_template(@recipient) } - assert_not_nil created - expected.message_id = '<123@456>' - created.message_id = '<123@456>' - assert_equal expected.encoded, created.encoded - end - - def test_custom_templating_extension - assert ActionView::Template.template_handler_extensions.include?("haml"), "haml extension was not registered" - - # N.b., custom_templating_extension.text.plain.haml is expected to be in fixtures/test_mailer directory - expected = new_mail - expected.to = @recipient - expected.subject = "[Signed up] Welcome #{@recipient}" - expected.body = "Hello there, \n\nMr. #{@recipient}" - expected.from = "system@loudthinking.com" - expected.date = Time.local(2004, 12, 12) - - # Now that the template is registered, there should be one part. The text/plain part. - created = nil - assert_nothing_raised { created = TestMailer.custom_templating_extension(@recipient) } - assert_not_nil created - assert_equal 2, created.parts.length - assert_equal 'text/plain', created.parts[0].mime_type - assert_equal 'text/html', created.parts[1].mime_type - end - - def test_cancelled_account - expected = new_mail - expected.to = @recipient - expected.subject = "[Cancelled] Goodbye #{@recipient}" - expected.body = "Goodbye, Mr. #{@recipient}" - expected.from = "system@loudthinking.com" - expected.date = Time.local(2004, 12, 12) - - created = nil - assert_nothing_raised { created = TestMailer.cancelled_account(@recipient) } - assert_not_nil created - expected.message_id = '<123@456>' - created.message_id = '<123@456>' - assert_equal expected.encoded, created.encoded - - assert_nothing_raised { TestMailer.cancelled_account(@recipient).deliver } - assert_not_nil ActionMailer::Base.deliveries.first - delivered = ActionMailer::Base.deliveries.first - expected.message_id = '<123@456>' - delivered.message_id = '<123@456>' - - assert_equal expected.encoded, delivered.encoded - end - - def test_cc_bcc - expected = new_mail - expected.to = @recipient - expected.subject = "testing bcc/cc" - expected.body = "Nothing to see here." - expected.from = "system@loudthinking.com" - expected.cc = "nobody@loudthinking.com" - expected.bcc = "root@loudthinking.com" - expected.date = Time.local 2004, 12, 12 - - created = nil - assert_nothing_raised do - created = TestMailer.cc_bcc @recipient - end - assert_not_nil created - expected.message_id = '<123@456>' - created.message_id = '<123@456>' - assert_equal expected.encoded, created.encoded - - assert_nothing_raised do - TestMailer.cc_bcc(@recipient).deliver - end - - assert_not_nil ActionMailer::Base.deliveries.first - delivered = ActionMailer::Base.deliveries.first - expected.message_id = '<123@456>' - delivered.message_id = '<123@456>' - - assert_equal expected.encoded, delivered.encoded - end - - def test_from_without_name_for_smtp - TestMailer.delivery_method = :smtp - TestMailer.from_without_name.deliver - - mail = MockSMTP.deliveries.first - assert_not_nil mail - mail, from, to = mail - - assert_equal 'system@loudthinking.com', from.to_s - end - - def test_from_with_name_for_smtp - TestMailer.delivery_method = :smtp - TestMailer.from_with_name.deliver - - mail = MockSMTP.deliveries.first - assert_not_nil mail - mail, from, to = mail - - assert_equal 'system@loudthinking.com', from - end - - def test_reply_to - TestMailer.delivery_method = :test - - expected = new_mail - - expected.to = @recipient - expected.subject = "testing reply_to" - expected.body = "Nothing to see here." - expected.from = "system@loudthinking.com" - expected.reply_to = "atraver@gmail.com" - expected.date = Time.local 2008, 5, 23 - - created = nil - assert_nothing_raised do - created = TestMailer.different_reply_to @recipient - end - assert_not_nil created - - expected.message_id = '<123@456>' - created.message_id = '<123@456>' - - assert_equal expected.encoded, created.encoded - - assert_nothing_raised do - TestMailer.different_reply_to(@recipient).deliver - end - - delivered = ActionMailer::Base.deliveries.first - assert_not_nil delivered - - expected.message_id = '<123@456>' - delivered.message_id = '<123@456>' - - assert_equal expected.encoded, delivered.encoded - end - - def test_iso_charset - TestMailer.delivery_method = :test - expected = new_mail( "iso-8859-1" ) - expected.to = @recipient - expected.subject = encode "testing isø charsets", "iso-8859-1" - expected.body = "Nothing to see here." - expected.from = "system@loudthinking.com" - expected.cc = "nobody@loudthinking.com" - expected.bcc = "root@loudthinking.com" - expected.date = Time.local 2004, 12, 12 - - created = nil - assert_nothing_raised do - created = TestMailer.iso_charset @recipient - end - assert_not_nil created - - expected.message_id = '<123@456>' - created.message_id = '<123@456>' - - assert_equal expected.encoded, created.encoded - - assert_nothing_raised do - TestMailer.iso_charset(@recipient).deliver - end - - delivered = ActionMailer::Base.deliveries.first - assert_not_nil delivered - - expected.message_id = '<123@456>' - delivered.message_id = '<123@456>' - - assert_equal expected.encoded, delivered.encoded - end - - def test_unencoded_subject - TestMailer.delivery_method = :test - expected = new_mail - expected.to = @recipient - expected.subject = "testing unencoded subject" - expected.body = "Nothing to see here." - expected.from = "system@loudthinking.com" - expected.cc = "nobody@loudthinking.com" - expected.bcc = "root@loudthinking.com" - expected.date = Time.local 2004, 12, 12 - - created = nil - assert_nothing_raised do - created = TestMailer.unencoded_subject @recipient - end - assert_not_nil created - - expected.message_id = '<123@456>' - created.message_id = '<123@456>' - - assert_equal expected.encoded, created.encoded - - assert_nothing_raised do - TestMailer.unencoded_subject(@recipient).deliver - end - - delivered = ActionMailer::Base.deliveries.first - assert_not_nil delivered - - expected.message_id = '<123@456>' - delivered.message_id = '<123@456>' - - assert_equal expected.encoded, delivered.encoded - end - - def test_deliveries_array - assert_not_nil ActionMailer::Base.deliveries - assert_equal 0, ActionMailer::Base.deliveries.size - TestMailer.signed_up(@recipient).deliver - assert_equal 1, ActionMailer::Base.deliveries.size - assert_not_nil ActionMailer::Base.deliveries.first - end - - def test_perform_deliveries_flag - ActionMailer::Base.perform_deliveries = false - TestMailer.signed_up(@recipient).deliver - assert_equal 0, ActionMailer::Base.deliveries.size - ActionMailer::Base.perform_deliveries = true - TestMailer.signed_up(@recipient).deliver - assert_equal 1, ActionMailer::Base.deliveries.size - end - - def test_doesnt_raise_errors_when_raise_delivery_errors_is_false - ActionMailer::Base.raise_delivery_errors = false - Mail::TestMailer.any_instance.expects(:deliver!).raises(Exception) - assert_nothing_raised { TestMailer.signed_up(@recipient).deliver } - end - - def test_performs_delivery_via_sendmail - IO.expects(:popen).once.with('/usr/sbin/sendmail -i -t -f "system@loudthinking.com" test@localhost', 'w+') - TestMailer.delivery_method = :sendmail - TestMailer.signed_up(@recipient).deliver - end - - def test_unquote_quoted_printable_subject - msg = <" - - expected = new_mail "iso-8859-1" - expected.to = @recipient - expected.subject = "testing extended headers" - expected.body = "Nothing to see here." - expected.from = "Grytøyr " - expected.cc = "Grytøyr " - expected.bcc = "Grytøyr " - expected.date = Time.local 2004, 12, 12 - - created = nil - assert_nothing_raised do - created = TestMailer.extended_headers @recipient - end - - assert_not_nil created - expected.message_id = '<123@456>' - created.message_id = '<123@456>' - - assert_equal expected.encoded, created.encoded - - assert_nothing_raised do - TestMailer.extended_headers(@recipient).deliver - end - - delivered = ActionMailer::Base.deliveries.first - assert_not_nil delivered - - expected.message_id = '<123@456>' - delivered.message_id = '<123@456>' - - assert_equal expected.encoded, delivered.encoded - end - - def test_utf8_body_is_not_quoted - @recipient = "Foo áëô îü " - expected = new_mail "UTF-8" - expected.to = @recipient - expected.subject = "testing UTF-8 body" - expected.body = "åœö blah" - expected.from = @recipient - expected.cc = @recipient - expected.bcc = @recipient - expected.date = Time.local 2004, 12, 12 - - created = TestMailer.utf8_body @recipient - assert_match(/åœö blah/, created.decoded) - end - - def test_multiple_utf8_recipients - @recipient = ["\"Foo áëô îü\" ", "\"Example Recipient\" "] - expected = new_mail "UTF-8" - expected.to = @recipient - expected.subject = "testing UTF-8 body" - expected.body = "åœö blah" - expected.from = @recipient.first - expected.cc = @recipient - expected.bcc = @recipient - expected.date = Time.local 2004, 12, 12 - - created = TestMailer.utf8_body @recipient - from_regexp = Regexp.escape('From: Foo =?UTF-8?B?w6HDq8O0?= =?UTF-8?B?IMOuw7w=?=') - assert_match(/#{from_regexp}/m, created.encoded) - - to_regexp = Regexp.escape("To: =?UTF-8?B?Rm9vIMOhw6vDtCDDrsO8?= ") - assert_match(/#{to_regexp}/m, created.encoded) - end - - def test_receive_decodes_base64_encoded_mail - fixture = File.read(File.dirname(__FILE__) + "/../fixtures/raw_email") - TestMailer.receive(fixture) - assert_match(/Jamis/, TestMailer.received_body.to_s) - end - - def test_receive_attachments - fixture = File.read(File.dirname(__FILE__) + "/../fixtures/raw_email2") - mail = Mail.new(fixture) - attachment = mail.attachments.last - assert_equal "smime.p7s", attachment.filename - assert_equal "application/pkcs7-signature", mail.parts.last.mime_type - end - - def test_decode_attachment_without_charset - fixture = File.read(File.dirname(__FILE__) + "/../fixtures/raw_email3") - mail = Mail.new(fixture) - attachment = mail.attachments.last - assert_equal 1026, attachment.read.length - end - - def test_attachment_using_content_location - fixture = File.read(File.dirname(__FILE__) + "/../fixtures/raw_email12") - mail = Mail.new(fixture) - assert_equal 1, mail.attachments.length - assert_equal "Photo25.jpg", mail.attachments.first.filename - end - - def test_attachment_with_text_type - fixture = File.read(File.dirname(__FILE__) + "/../fixtures/raw_email13") - mail = Mail.new(fixture) - assert mail.has_attachments? - assert_equal 1, mail.attachments.length - assert_equal "hello.rb", mail.attachments.first.filename - end - - def test_decode_part_without_content_type - fixture = File.read(File.dirname(__FILE__) + "/../fixtures/raw_email4") - mail = Mail.new(fixture) - assert_nothing_raised { mail.body } - end - - def test_decode_message_without_content_type - fixture = File.read(File.dirname(__FILE__) + "/../fixtures/raw_email5") - mail = Mail.new(fixture) - assert_nothing_raised { mail.body } - end - - def test_decode_message_with_incorrect_charset - fixture = File.read(File.dirname(__FILE__) + "/../fixtures/raw_email6") - mail = Mail.new(fixture) - assert_nothing_raised { mail.body } - end - - def test_multipart_with_mime_version - mail = TestMailer.multipart_with_mime_version(@recipient) - assert_equal "1.1", mail.mime_version - end - - def test_multipart_with_utf8_subject - mail = TestMailer.multipart_with_utf8_subject(@recipient) - regex = Regexp.escape('Subject: =?UTF-8?Q?Foo_=C3=A1=C3=AB=C3=B4_=C3=AE=C3=BC?=') - assert_match(/#{regex}/, mail.encoded) - string = "Foo áëô îü" - assert_match(string, mail.subject) - end - - def test_implicitly_multipart_with_utf8 - mail = TestMailer.implicitly_multipart_with_utf8 - regex = Regexp.escape('Subject: =?UTF-8?Q?Foo_=C3=A1=C3=AB=C3=B4_=C3=AE=C3=BC?=') - assert_match(/#{regex}/, mail.encoded) - string = "Foo áëô îü" - assert_match(string, mail.subject) - end - - def test_explicitly_multipart_messages - mail = TestMailer.explicitly_multipart_example(@recipient) - assert_equal 3, mail.parts.length - assert_equal 'multipart/mixed', mail.mime_type - assert_equal "text/plain", mail.parts[0].mime_type - - assert_equal "text/html", mail.parts[1].mime_type - assert_equal "iso-8859-1", mail.parts[1].charset - - assert_equal "image/jpeg", mail.parts[2].mime_type - - assert_equal "attachment", mail.parts[2][:content_disposition].disposition_type - assert_equal "foo.jpg", mail.parts[2][:content_disposition].filename - assert_equal "foo.jpg", mail.parts[2][:content_type].filename - assert_nil mail.parts[2].charset - end - - def test_explicitly_multipart_with_content_type - mail = TestMailer.explicitly_multipart_example(@recipient, "multipart/alternative") - assert_equal 3, mail.parts.length - assert_equal "multipart/alternative", mail.mime_type - end - - def test_explicitly_multipart_with_invalid_content_type - mail = TestMailer.explicitly_multipart_example(@recipient, "text/xml") - assert_equal 3, mail.parts.length - assert_equal 'multipart/mixed', mail.mime_type - end - - def test_implicitly_multipart_messages - assert ActionView::Template.template_handler_extensions.include?("bak"), "bak extension was not registered" - - mail = TestMailer.implicitly_multipart_example(@recipient) - assert_equal 3, mail.parts.length - assert_equal "1.0", mail.mime_version.to_s - assert_equal "multipart/alternative", mail.mime_type - assert_equal "text/plain", mail.parts[0].mime_type - assert_equal "UTF-8", mail.parts[0].charset - assert_equal "text/html", mail.parts[1].mime_type - assert_equal "UTF-8", mail.parts[1].charset - assert_equal "application/x-yaml", mail.parts[2].mime_type - assert_equal "UTF-8", mail.parts[2].charset - end - - def test_implicitly_multipart_messages_with_custom_order - assert ActionView::Template.template_handler_extensions.include?("bak"), "bak extension was not registered" - - mail = TestMailer.implicitly_multipart_example(@recipient, nil, ["application/x-yaml", "text/plain"]) - assert_equal 3, mail.parts.length - assert_equal "application/x-yaml", mail.parts[0].mime_type - assert_equal "text/plain", mail.parts[1].mime_type - assert_equal "text/html", mail.parts[2].mime_type - end - - def test_implicitly_multipart_messages_with_charset - mail = TestMailer.implicitly_multipart_example(@recipient, 'iso-8859-1') - - assert_equal "multipart/alternative", mail.header['content-type'].content_type - - assert_equal 'iso-8859-1', mail.parts[0].content_type_parameters[:charset] - assert_equal 'iso-8859-1', mail.parts[1].content_type_parameters[:charset] - assert_equal 'iso-8859-1', mail.parts[2].content_type_parameters[:charset] - end - - def test_html_mail - mail = TestMailer.html_mail(@recipient) - assert_equal "text/html", mail.mime_type - end - - def test_html_mail_with_underscores - mail = TestMailer.html_mail_with_underscores(@recipient) - assert_equal %{_Google}, mail.body.to_s - end - - def test_various_newlines - mail = TestMailer.various_newlines(@recipient) - assert_equal("line #1\nline #2\nline #3\nline #4\n\n" + - "line #5\n\nline#6\n\nline #7", mail.body.to_s) - end - - def test_various_newlines_multipart - mail = TestMailer.various_newlines_multipart(@recipient) - assert_equal "line #1\nline #2\nline #3\nline #4\n\n", mail.parts[0].body.to_s - assert_equal "

line #1

\n

line #2

\n

line #3

\n

line #4

\n\n", mail.parts[1].body.to_s - assert_equal "line #1\r\nline #2\r\nline #3\r\nline #4\r\n\r\n", mail.parts[0].body.encoded - assert_equal "

line #1

\r\n

line #2

\r\n

line #3

\r\n

line #4

\r\n\r\n", mail.parts[1].body.encoded - end - - def test_headers_removed_on_smtp_delivery - TestMailer.delivery_method = :smtp - TestMailer.cc_bcc(@recipient).deliver - assert MockSMTP.deliveries[0][2].include?("root@loudthinking.com") - assert MockSMTP.deliveries[0][2].include?("nobody@loudthinking.com") - assert MockSMTP.deliveries[0][2].include?(@recipient) - assert_match %r{^Cc: nobody@loudthinking.com}, MockSMTP.deliveries[0][0] - assert_match %r{^To: #{@recipient}}, MockSMTP.deliveries[0][0] - assert_no_match %r{^Bcc: root@loudthinking.com}, MockSMTP.deliveries[0][0] - end - - def test_file_delivery_should_create_a_file - TestMailer.delivery_method = :file - tmp_location = TestMailer.file_settings[:location] - - result = TestMailer.cc_bcc(@recipient).deliver - assert File.exists?(tmp_location) - assert File.directory?(tmp_location) - assert File.exists?(File.join(tmp_location, @recipient)) - assert File.exists?(File.join(tmp_location, 'nobody@loudthinking.com')) - assert File.exists?(File.join(tmp_location, 'root@loudthinking.com')) - end - - def test_recursive_multipart_processing - fixture = File.read(File.dirname(__FILE__) + "/../fixtures/raw_email7") - mail = Mail.new(fixture) - assert_equal(2, mail.parts.length) - assert_equal(4, mail.parts.first.parts.length) - assert_equal("This is the first part.", mail.parts.first.parts.first.body.to_s) - assert_equal("test.rb", mail.parts.first.parts.second.filename) - assert_equal("flowed", mail.parts.first.parts.fourth.content_type_parameters[:format]) - assert_equal('smime.p7s', mail.parts.second.filename) - end - - def test_decode_encoded_attachment_filename - fixture = File.read(File.dirname(__FILE__) + "/../fixtures/raw_email8") - mail = Mail.new(fixture) - attachment = mail.attachments.last - - expected = "01 Quien Te Dij\212at. Pitbull.mp3" - - if expected.respond_to?(:force_encoding) - result = attachment.filename.dup - expected.force_encoding(Encoding::ASCII_8BIT) - result.force_encoding(Encoding::ASCII_8BIT) - assert_equal expected, result - else - assert_equal expected, attachment.filename - end - end - - def test_decode_message_with_unknown_charset - fixture = File.read(File.dirname(__FILE__) + "/../fixtures/raw_email10") - mail = Mail.new(fixture) - assert_nothing_raised { mail.body } - end - - def test_empty_header_values_omitted - result = TestMailer.unnamed_attachment(@recipient).encoded - assert_match %r{Content-Type: application/octet-stream}, result - assert_match %r{Content-Disposition: attachment}, result - end - - def test_headers_with_nonalpha_chars - mail = TestMailer.headers_with_nonalpha_chars(@recipient) - assert !mail.from_addrs.empty? - assert !mail.cc_addrs.empty? - assert !mail.bcc_addrs.empty? - assert_match(/:/, mail[:from].decoded) - assert_match(/:/, mail[:cc].decoded) - assert_match(/:/, mail[:bcc].decoded) - end - - def test_with_mail_object_deliver - TestMailer.delivery_method = :test - mail = TestMailer.headers_with_nonalpha_chars(@recipient) - assert_nothing_raised { mail.deliver } - assert_equal 1, TestMailer.deliveries.length - end - - def test_multipart_with_template_path_with_dots - mail = FunkyPathMailer.multipart_with_template_path_with_dots(@recipient) - assert_equal 2, mail.parts.length - assert_equal "text/plain", mail.parts[0].mime_type - assert_equal "text/html", mail.parts[1].mime_type - assert_equal "UTF-8", mail.parts[1].charset - end - - def test_custom_content_type_attributes - mail = TestMailer.custom_content_type_attributes - assert_match %r{format=flowed}, mail.content_type - assert_match %r{charset=UTF-8}, mail.content_type - end - - def test_return_path_with_create - mail = TestMailer.return_path - assert_equal "another@somewhere.test", mail.return_path - end - - def test_return_path_with_deliver - TestMailer.delivery_method = :smtp - TestMailer.return_path.deliver - assert_match %r{^Return-Path: }, MockSMTP.deliveries[0][0] - assert_equal "another@somewhere.test", MockSMTP.deliveries[0][1].to_s - end - - def test_starttls_is_enabled_if_supported - TestMailer.smtp_settings.merge!(:enable_starttls_auto => true) - MockSMTP.any_instance.expects(:respond_to?).with(:enable_starttls_auto).returns(true) - MockSMTP.any_instance.expects(:enable_starttls_auto) - TestMailer.delivery_method = :smtp - TestMailer.signed_up(@recipient).deliver - end - - def test_starttls_is_disabled_if_not_supported - TestMailer.smtp_settings.merge!(:enable_starttls_auto => true) - MockSMTP.any_instance.expects(:respond_to?).with(:enable_starttls_auto).returns(false) - MockSMTP.any_instance.expects(:enable_starttls_auto).never - TestMailer.delivery_method = :smtp - TestMailer.signed_up(@recipient).deliver - end - - def test_starttls_is_not_enabled - TestMailer.smtp_settings.merge!(:enable_starttls_auto => false) - MockSMTP.any_instance.expects(:respond_to?).never - TestMailer.delivery_method = :smtp - TestMailer.signed_up(@recipient).deliver - ensure - TestMailer.smtp_settings.merge!(:enable_starttls_auto => true) - end -end - -class InheritableTemplateRootTest < ActiveSupport::TestCase - def test_attr - expected = File.expand_path("#{File.dirname(__FILE__)}/../fixtures/path.with.dots") - assert_equal expected, FunkyPathMailer.template_root.to_s - - sub = Class.new(FunkyPathMailer) - assert_deprecated do - sub.template_root = 'test/path' - end - - assert_equal File.expand_path('test/path'), sub.template_root.to_s - assert_equal expected, FunkyPathMailer.template_root.to_s - end -end - -class MethodNamingTest < ActiveSupport::TestCase - include ActionMailer::TestHelper - - class TestMailer < ActionMailer::Base - def send - body 'foo' - end - end - - def setup - set_delivery_method :test - ActionMailer::Base.perform_deliveries = true - ActionMailer::Base.deliveries.clear - end - - def teardown - restore_delivery_method - end - - def test_send_method - assert_nothing_raised do - assert_emails 1 do - assert_deprecated do - TestMailer.deliver_send - end - end - end - end -end -class RespondToTest < Test::Unit::TestCase - class RespondToMailer < ActionMailer::Base; end - - def setup - set_delivery_method :test - end - - def teardown - restore_delivery_method - end - - def test_should_respond_to_new - assert_respond_to RespondToMailer, :new - end - - def test_should_respond_to_create_with_template_suffix - assert_respond_to RespondToMailer, :create_any_old_template - end - - def test_should_respond_to_deliver_with_template_suffix - assert_respond_to RespondToMailer, :deliver_any_old_template - end - - def test_should_not_respond_to_new_with_template_suffix - assert !RespondToMailer.respond_to?(:new_any_old_template) - end - - def test_should_not_respond_to_create_with_template_suffix_unless_it_is_separated_by_an_underscore - assert !RespondToMailer.respond_to?(:createany_old_template) - end - - def test_should_not_respond_to_deliver_with_template_suffix_unless_it_is_separated_by_an_underscore - assert !RespondToMailer.respond_to?(:deliverany_old_template) - end - - def test_should_not_respond_to_create_with_template_suffix_if_it_begins_with_a_uppercase_letter - assert !RespondToMailer.respond_to?(:create_Any_old_template) - end - - def test_should_not_respond_to_deliver_with_template_suffix_if_it_begins_with_a_uppercase_letter - assert !RespondToMailer.respond_to?(:deliver_Any_old_template) - end - - def test_should_not_respond_to_create_with_template_suffix_if_it_begins_with_a_digit - assert !RespondToMailer.respond_to?(:create_1_template) - end - - def test_should_not_respond_to_deliver_with_template_suffix_if_it_begins_with_a_digit - assert !RespondToMailer.respond_to?(:deliver_1_template) - end - - def test_should_not_respond_to_method_where_deliver_is_not_a_suffix - assert !RespondToMailer.respond_to?(:foo_deliver_template) - end - - def test_should_still_raise_exception_with_expected_message_when_calling_an_undefined_method - error = assert_raise NoMethodError do - RespondToMailer.not_a_method - end - - assert_match(/method.*not_a_method/, error.message) - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/old_base/tmail_compat_test.rb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/old_base/tmail_compat_test.rb deleted file mode 100644 index 2953c7452..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/old_base/tmail_compat_test.rb +++ /dev/null @@ -1,35 +0,0 @@ -require 'abstract_unit' - -class TmailCompatTest < ActiveSupport::TestCase - - def test_set_content_type_raises_deprecation_warning - mail = Mail.new - assert_deprecated do - assert_nothing_raised do - mail.set_content_type "text/plain" - end - end - assert_equal mail.mime_type, "text/plain" - end - - def test_transfer_encoding_raises_deprecation_warning - mail = Mail.new - assert_deprecated do - assert_nothing_raised do - mail.transfer_encoding "base64" - end - end - assert_equal mail.content_transfer_encoding, "base64" - end - - def test_transfer_encoding_setter_raises_deprecation_warning - mail = Mail.new - assert_deprecated do - assert_nothing_raised do - mail.transfer_encoding = "base64" - end - end - assert_equal mail.content_transfer_encoding, "base64" - end - -end diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/old_base/url_test.rb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/old_base/url_test.rb deleted file mode 100644 index e5a4b8008..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/old_base/url_test.rb +++ /dev/null @@ -1,90 +0,0 @@ -require 'abstract_unit' -require 'action_controller' - -class WelcomeController < ActionController::Base -end - -AppRoutes = ActionDispatch::Routing::RouteSet.new - -class ActionMailer::Base - include AppRoutes.url_helpers -end - -class UrlTestMailer < ActionMailer::Base - default_url_options[:host] = 'www.basecamphq.com' - - configure do |c| - c.assets_dir = '' # To get the tests to pass - end - - def signed_up_with_url(recipient) - @recipients = recipient - @subject = "[Signed up] Welcome #{recipient}" - @from = "system@loudthinking.com" - @sent_on = Time.local(2004, 12, 12) - - @recipient = recipient - @welcome_url = url_for :host => "example.com", :controller => "welcome", :action => "greeting" - end -end - -class ActionMailerUrlTest < ActionMailer::TestCase - - def encode( text, charset="UTF-8" ) - quoted_printable( text, charset ) - end - - def new_mail( charset="UTF-8" ) - mail = Mail.new - mail.mime_version = "1.0" - if charset - mail.content_type ["text", "plain", { "charset" => charset }] - end - mail - end - - def setup - set_delivery_method :test - ActionMailer::Base.perform_deliveries = true - ActionMailer::Base.deliveries.clear - - @recipient = 'test@localhost' - end - - def teardown - restore_delivery_method - end - - def test_signed_up_with_url - UrlTestMailer.delivery_method = :test - - assert_deprecated do - AppRoutes.draw do |map| - map.connect ':controller/:action/:id' - map.welcome 'welcome', :controller=>"foo", :action=>"bar" - end - end - - expected = new_mail - expected.to = @recipient - expected.subject = "[Signed up] Welcome #{@recipient}" - expected.body = "Hello there,\n\nMr. #{@recipient}. Please see our greeting at http://example.com/welcome/greeting http://www.basecamphq.com/welcome\n\n\"Somelogo\"" - expected.from = "system@loudthinking.com" - expected.date = Time.local(2004, 12, 12) - - created = nil - assert_nothing_raised { created = UrlTestMailer.signed_up_with_url(@recipient) } - assert_not_nil created - - expected.message_id = '<123@456>' - created.message_id = '<123@456>' - assert_equal expected.encoded, created.encoded - - assert_nothing_raised { UrlTestMailer.signed_up_with_url(@recipient).deliver } - assert_not_nil ActionMailer::Base.deliveries.first - delivered = ActionMailer::Base.deliveries.first - - delivered.message_id = '<123@456>' - assert_equal expected.encoded, delivered.encoded - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionmailer/test/test_helper_test.rb b/Tests/Libraries/Rails-3.0.0/actionmailer/test/test_helper_test.rb deleted file mode 100644 index a8d22f97e..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionmailer/test/test_helper_test.rb +++ /dev/null @@ -1,127 +0,0 @@ -require 'abstract_unit' - -class TestHelperMailer < ActionMailer::Base - def test - recipients "test@example.com" - from "tester@example.com" - - @world = "Earth" - render(:inline => "Hello, <%= @world %>") - end -end - -class TestHelperMailerTest < ActionMailer::TestCase - def test_setup_sets_right_action_mailer_options - assert_equal :test, ActionMailer::Base.delivery_method - assert ActionMailer::Base.perform_deliveries - assert_equal [], ActionMailer::Base.deliveries - end - - def test_setup_creates_the_expected_mailer - assert_kind_of Mail::Message, @expected - assert_equal "1.0", @expected.mime_version - assert_equal "text/plain", @expected.mime_type - end - - def test_mailer_class_is_correctly_inferred - assert_equal TestHelperMailer, self.class.mailer_class - end - - def test_determine_default_mailer_raises_correct_error - assert_raise(ActionMailer::NonInferrableMailerError) do - self.class.determine_default_mailer("NotAMailerTest") - end - end - - def test_charset_is_utf_8 - assert_equal "UTF-8", charset - end - - def test_assert_emails - assert_nothing_raised do - assert_emails 1 do - TestHelperMailer.test.deliver - end - end - end - - def test_repeated_assert_emails_calls - assert_nothing_raised do - assert_emails 1 do - TestHelperMailer.test.deliver - end - end - - assert_nothing_raised do - assert_emails 2 do - TestHelperMailer.test.deliver - TestHelperMailer.test.deliver - end - end - end - - def test_assert_emails_with_no_block - assert_nothing_raised do - TestHelperMailer.test.deliver - assert_emails 1 - end - - assert_nothing_raised do - TestHelperMailer.test.deliver - TestHelperMailer.test.deliver - assert_emails 3 - end - end - - def test_assert_no_emails - assert_nothing_raised do - assert_no_emails do - TestHelperMailer.test - end - end - end - - def test_assert_emails_too_few_sent - error = assert_raise ActiveSupport::TestCase::Assertion do - assert_emails 2 do - TestHelperMailer.test.deliver - end - end - - assert_match(/2 .* but 1/, error.message) - end - - def test_assert_emails_too_many_sent - error = assert_raise ActiveSupport::TestCase::Assertion do - assert_emails 1 do - TestHelperMailer.test.deliver - TestHelperMailer.test.deliver - end - end - - assert_match(/1 .* but 2/, error.message) - end - - def test_assert_no_emails_failure - error = assert_raise ActiveSupport::TestCase::Assertion do - assert_no_emails do - TestHelperMailer.test.deliver - end - end - - assert_match(/0 .* but 1/, error.message) - end -end - -class AnotherTestHelperMailerTest < ActionMailer::TestCase - tests TestHelperMailer - - def setup - @test_var = "a value" - end - - def test_setup_shouldnt_conflict_with_mailer_setup - assert_kind_of Mail::Message, @expected - assert_equal 'a value', @test_var - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/MIT-LICENSE b/Tests/Libraries/Rails-3.0.0/actionpack/MIT-LICENSE deleted file mode 100644 index 77d558ab8..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/MIT-LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -Copyright (c) 2004-2010 David Heinemeier Hansson - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/abstract_controller_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/abstract_controller_test.rb deleted file mode 100644 index f4599c83b..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/abstract_controller_test.rb +++ /dev/null @@ -1,268 +0,0 @@ -require 'abstract_unit' - -module AbstractController - module Testing - - # Test basic dispatching. - # ==== - # * Call process - # * Test that the response_body is set correctly - class SimpleController < AbstractController::Base - end - - class Me < SimpleController - def index - self.response_body = "Hello world" - "Something else" - end - end - - class TestBasic < ActiveSupport::TestCase - test "dispatching works" do - controller = Me.new - controller.process(:index) - assert_equal "Hello world", controller.response_body - end - end - - # Test Render mixin - # ==== - class RenderingController < AbstractController::Base - include ::AbstractController::Rendering - - def _prefix() end - - def render(options = {}) - if options.is_a?(String) - options = {:_template_name => options} - end - - options[:_prefix] = _prefix - super - end - - append_view_path File.expand_path(File.join(File.dirname(__FILE__), "views")) - end - - class Me2 < RenderingController - def index - render "index.erb" - end - - def index_to_string - self.response_body = render_to_string "index.erb" - end - - def action_with_ivars - @my_ivar = "Hello" - render "action_with_ivars.erb" - end - - def naked_render - render - end - - def rendering_to_body - self.response_body = render_to_body :template => "naked_render.erb" - end - - def rendering_to_string - self.response_body = render_to_string :template => "naked_render.erb" - end - end - - class TestRenderingController < ActiveSupport::TestCase - def setup - @controller = Me2.new - end - - test "rendering templates works" do - @controller.process(:index) - assert_equal "Hello from index.erb", @controller.response_body - end - - test "render_to_string works with a String as an argument" do - @controller.process(:index_to_string) - assert_equal "Hello from index.erb", @controller.response_body - end - - test "rendering passes ivars to the view" do - @controller.process(:action_with_ivars) - assert_equal "Hello from index_with_ivars.erb", @controller.response_body - end - - test "rendering with no template name" do - @controller.process(:naked_render) - assert_equal "Hello from naked_render.erb", @controller.response_body - end - - test "rendering to a rack body" do - @controller.process(:rendering_to_body) - assert_equal "Hello from naked_render.erb", @controller.response_body - end - - test "rendering to a string" do - @controller.process(:rendering_to_string) - assert_equal "Hello from naked_render.erb", @controller.response_body - end - end - - # Test rendering with prefixes - # ==== - # * self._prefix is used when defined - class PrefixedViews < RenderingController - private - def self.prefix - name.underscore - end - - def _prefix - self.class.prefix - end - end - - class Me3 < PrefixedViews - def index - render - end - - def formatted - self.formats = [:html] - render - end - end - - class TestPrefixedViews < ActiveSupport::TestCase - def setup - @controller = Me3.new - end - - test "templates are located inside their 'prefix' folder" do - @controller.process(:index) - assert_equal "Hello from me3/index.erb", @controller.response_body - end - - test "templates included their format" do - @controller.process(:formatted) - assert_equal "Hello from me3/formatted.html.erb", @controller.response_body - end - end - - # Test rendering with layouts - # ==== - # self._layout is used when defined - class WithLayouts < PrefixedViews - include Layouts - - private - def self.layout(formats) - begin - find_template(name.underscore, {:formats => formats}, :_prefix => "layouts") - rescue ActionView::MissingTemplate - begin - find_template("application", {:formats => formats}, :_prefix => "layouts") - rescue ActionView::MissingTemplate - end - end - end - - def render_to_body(options = {}) - options[:_layout] = options[:layout] || _default_layout({}) - super - end - end - - class Me4 < WithLayouts - def index - render - end - end - - class Me5 < WithLayouts - def index - render - end - end - - class TestLayouts < ActiveSupport::TestCase - test "layouts are included" do - controller = Me4.new - result = controller.process(:index) - assert_equal "Me4 Enter : Hello from me4/index.erb : Exit", controller.response_body - end - end - - # respond_to_action?(action_name) - # ==== - # * A method can be used as an action only if this method - # returns true when passed the method name as an argument - # * Defaults to true in AbstractController - class DefaultRespondToActionController < AbstractController::Base - def index() self.response_body = "success" end - end - - class ActionMissingRespondToActionController < AbstractController::Base - # No actions - private - def action_missing(action_name) - self.response_body = "success" - end - end - - class RespondToActionController < AbstractController::Base; - def index() self.response_body = "success" end - - def fail() self.response_body = "fail" end - - private - - def method_for_action(action_name) - action_name.to_s != "fail" && action_name - end - end - - class TestRespondToAction < ActiveSupport::TestCase - - def assert_dispatch(klass, body = "success", action = :index) - controller = klass.new - controller.process(action) - assert_equal body, controller.response_body - end - - test "an arbitrary method is available as an action by default" do - assert_dispatch DefaultRespondToActionController, "success", :index - end - - test "raises ActionNotFound when method does not exist and action_missing is not defined" do - assert_raise(ActionNotFound) { DefaultRespondToActionController.new.process(:fail) } - end - - test "dispatches to action_missing when method does not exist and action_missing is defined" do - assert_dispatch ActionMissingRespondToActionController, "success", :ohai - end - - test "a method is available as an action if respond_to_action? returns true" do - assert_dispatch RespondToActionController, "success", :index - end - - test "raises ActionNotFound if method is defined but respond_to_action? returns false" do - assert_raise(ActionNotFound) { RespondToActionController.new.process(:fail) } - end - end - - class Me6 < AbstractController::Base - self.action_methods - - def index - end - end - - class TestActionMethodsReloading < ActiveSupport::TestCase - - test "action_methods should be reloaded after defining a new method" do - assert_equal ["index"], Me6.action_methods - end - end - - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/callbacks_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/callbacks_test.rb deleted file mode 100644 index 20eb75af8..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/callbacks_test.rb +++ /dev/null @@ -1,248 +0,0 @@ -require 'abstract_unit' - -module AbstractController - module Testing - - class ControllerWithCallbacks < AbstractController::Base - include AbstractController::Callbacks - end - - class Callback1 < ControllerWithCallbacks - set_callback :process_action, :before, :first - - def first - @text = "Hello world" - end - - def index - self.response_body = @text - end - end - - class TestCallbacks1 < ActiveSupport::TestCase - test "basic callbacks work" do - controller = Callback1.new - result = controller.process(:index) - assert_equal "Hello world", controller.response_body - end - end - - class Callback2 < ControllerWithCallbacks - before_filter :first - after_filter :second - around_filter :aroundz - - def first - @text = "Hello world" - end - - def second - @second = "Goodbye" - end - - def aroundz - @aroundz = "FIRST" - yield - @aroundz << "SECOND" - end - - def index - self.response_body = @text.to_s - end - end - - class Callback2Overwrite < Callback2 - before_filter :first, :except => :index - end - - class TestCallbacks2 < ActiveSupport::TestCase - def setup - @controller = Callback2.new - end - - test "before_filter works" do - result = @controller.process(:index) - assert_equal "Hello world", @controller.response_body - end - - test "after_filter works" do - @controller.process(:index) - assert_equal "Goodbye", @controller.instance_variable_get("@second") - end - - test "around_filter works" do - @controller.process(:index) - assert_equal "FIRSTSECOND", @controller.instance_variable_get("@aroundz") - end - - test "before_filter with overwritten condition" do - @controller = Callback2Overwrite.new - result = @controller.process(:index) - assert_equal "", @controller.response_body - end - end - - class Callback3 < ControllerWithCallbacks - before_filter do |c| - c.instance_variable_set("@text", "Hello world") - end - - after_filter do |c| - c.instance_variable_set("@second", "Goodbye") - end - - def index - self.response_body = @text - end - end - - class TestCallbacks3 < ActiveSupport::TestCase - def setup - @controller = Callback3.new - end - - test "before_filter works with procs" do - result = @controller.process(:index) - assert_equal "Hello world", @controller.response_body - end - - test "after_filter works with procs" do - result = @controller.process(:index) - assert_equal "Goodbye", @controller.instance_variable_get("@second") - end - end - - class CallbacksWithConditions < ControllerWithCallbacks - before_filter :list, :only => :index - before_filter :authenticate, :except => :index - - def index - self.response_body = @list.join(", ") - end - - def sekrit_data - self.response_body = (@list + [@authenticated]).join(", ") - end - - private - def list - @list = ["Hello", "World"] - end - - def authenticate - @list = [] - @authenticated = "true" - end - end - - class TestCallbacksWithConditions < ActiveSupport::TestCase - def setup - @controller = CallbacksWithConditions.new - end - - test "when :only is specified, a before filter is triggered on that action" do - @controller.process(:index) - assert_equal "Hello, World", @controller.response_body - end - - test "when :only is specified, a before filter is not triggered on other actions" do - @controller.process(:sekrit_data) - assert_equal "true", @controller.response_body - end - - test "when :except is specified, an after filter is not triggered on that action" do - result = @controller.process(:index) - assert_nil @controller.instance_variable_get("@authenticated") - end - end - - class CallbacksWithArrayConditions < ControllerWithCallbacks - before_filter :list, :only => [:index, :listy] - before_filter :authenticate, :except => [:index, :listy] - - def index - self.response_body = @list.join(", ") - end - - def sekrit_data - self.response_body = (@list + [@authenticated]).join(", ") - end - - private - def list - @list = ["Hello", "World"] - end - - def authenticate - @list = [] - @authenticated = "true" - end - end - - class TestCallbacksWithArrayConditions < ActiveSupport::TestCase - def setup - @controller = CallbacksWithArrayConditions.new - end - - test "when :only is specified with an array, a before filter is triggered on that action" do - result = @controller.process(:index) - assert_equal "Hello, World", @controller.response_body - end - - test "when :only is specified with an array, a before filter is not triggered on other actions" do - result = @controller.process(:sekrit_data) - assert_equal "true", @controller.response_body - end - - test "when :except is specified with an array, an after filter is not triggered on that action" do - result = @controller.process(:index) - assert_nil @controller.instance_variable_get("@authenticated") - end - end - - class ChangedConditions < Callback2 - before_filter :first, :only => :index - - def not_index - self.response_body = @text.to_s - end - end - - class TestCallbacksWithChangedConditions < ActiveSupport::TestCase - def setup - @controller = ChangedConditions.new - end - - test "when a callback is modified in a child with :only, it works for the :only action" do - result = @controller.process(:index) - assert_equal "Hello world", @controller.response_body - end - - test "when a callback is modified in a child with :only, it does not work for other actions" do - result = @controller.process(:not_index) - assert_equal "", @controller.response_body - end - end - - class SetsResponseBody < ControllerWithCallbacks - before_filter :set_body - - def index - self.response_body = "Fail" - end - - def set_body - self.response_body = "Success" - end - end - - class TestHalting < ActiveSupport::TestCase - test "when a callback sets the response body, the action should not be invoked" do - controller = SetsResponseBody.new - controller.process(:index) - assert_equal "Success", controller.response_body - end - end - - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/collector_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/collector_test.rb deleted file mode 100644 index a0cac3f3f..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/collector_test.rb +++ /dev/null @@ -1,57 +0,0 @@ -require 'abstract_unit' - -module AbstractController - module Testing - class MyCollector - include Collector - attr_accessor :responses - - def initialize - @responses = [] - end - - def custom(mime, *args, &block) - @responses << [mime, args, block] - end - end - - class TestCollector < ActiveSupport::TestCase - test "responds to default mime types" do - collector = MyCollector.new - assert_respond_to collector, :html - assert_respond_to collector, :text - end - - test "does not respond to unknown mime types" do - collector = MyCollector.new - assert !collector.respond_to?(:unknown) - end - - test "register mime types on method missing" do - AbstractController::Collector.send(:remove_method, :js) - collector = MyCollector.new - assert !collector.respond_to?(:js) - collector.js - assert_respond_to collector, :js - end - - test "does not register unknown mime types" do - collector = MyCollector.new - assert_raise NameError do - collector.unknown - end - end - - test "generated methods call custom with args received" do - collector = MyCollector.new - collector.html - collector.text(:foo) - collector.js(:bar) { :baz } - assert_equal [Mime::HTML, [], nil], collector.responses[0] - assert_equal [Mime::TEXT, [:foo], nil], collector.responses[1] - assert_equal [Mime::JS, [:bar]], collector.responses[2][0,2] - assert_equal :baz, collector.responses[2][2].call - end - end - end -end \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/helper_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/helper_test.rb deleted file mode 100644 index 6d3ce7984..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/helper_test.rb +++ /dev/null @@ -1,98 +0,0 @@ -require 'abstract_unit' - -ActionController::Base.helpers_path = File.expand_path('../../fixtures/helpers', __FILE__) - -module AbstractController - module Testing - - class ControllerWithHelpers < AbstractController::Base - include AbstractController::Rendering - include Helpers - - def with_module - render :inline => "Module <%= included_method %>" - end - end - - module HelperyTest - def included_method - "Included" - end - end - - class AbstractHelpers < ControllerWithHelpers - helper(HelperyTest) do - def helpery_test - "World" - end - end - - helper :abc - - def with_block - render :inline => "Hello <%= helpery_test %>" - end - - def with_symbol - render :inline => "I respond to bare_a: <%= respond_to?(:bare_a) %>" - end - end - - class ::HelperyTestController < AbstractHelpers - clear_helpers - end - - class AbstractHelpersBlock < ControllerWithHelpers - helper do - include ::AbstractController::Testing::HelperyTest - end - end - - class TestHelpers < ActiveSupport::TestCase - def setup - @controller = AbstractHelpers.new - end - - def test_helpers_with_block - @controller.process(:with_block) - assert_equal "Hello World", @controller.response_body - end - - def test_helpers_with_module - @controller.process(:with_module) - assert_equal "Module Included", @controller.response_body - end - - def test_helpers_with_symbol - @controller.process(:with_symbol) - assert_equal "I respond to bare_a: true", @controller.response_body - end - - def test_declare_missing_helper - assert_raise(MissingSourceFile) { AbstractHelpers.helper :missing } - end - - def test_helpers_with_module_through_block - @controller = AbstractHelpersBlock.new - @controller.process(:with_module) - assert_equal "Module Included", @controller.response_body - end - end - - class ClearHelpersTest < ActiveSupport::TestCase - def setup - @controller = HelperyTestController.new - end - - def test_clears_up_previous_helpers - @controller.process(:with_symbol) - assert_equal "I respond to bare_a: false", @controller.response_body - end - - def test_includes_controller_default_helper - @controller.process(:with_block) - assert_equal "Hello Default", @controller.response_body - end - end - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/layouts_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/layouts_test.rb deleted file mode 100644 index e721652cb..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/layouts_test.rb +++ /dev/null @@ -1,277 +0,0 @@ -require 'abstract_unit' - -module AbstractControllerTests - module Layouts - - # Base controller for these tests - class Base < AbstractController::Base - include AbstractController::Rendering - include AbstractController::Layouts - - self.view_paths = [ActionView::FixtureResolver.new( - "layouts/hello.erb" => "With String <%= yield %>", - "layouts/hello_override.erb" => "With Override <%= yield %>", - "layouts/overwrite.erb" => "Overwrite <%= yield %>", - "layouts/with_false_layout.erb" => "False Layout <%= yield %>", - "abstract_controller_tests/layouts/with_string_implied_child.erb" => - "With Implied <%= yield %>" - )] - end - - class Blank < Base - self.view_paths = [] - - def index - render :template => ActionView::Template::Text.new("Hello blank!") - end - end - - class WithString < Base - layout "hello" - - def index - render :template => ActionView::Template::Text.new("Hello string!") - end - - def overwrite_default - render :template => ActionView::Template::Text.new("Hello string!"), :layout => :default - end - - def overwrite_false - render :template => ActionView::Template::Text.new("Hello string!"), :layout => false - end - - def overwrite_string - render :template => ActionView::Template::Text.new("Hello string!"), :layout => "overwrite" - end - - def overwrite_skip - render :text => "Hello text!" - end - end - - class WithStringChild < WithString - end - - class WithStringOverriddenChild < WithString - layout "hello_override" - end - - class WithNilChild < WithString - layout nil - end - - class WithStringImpliedChild < WithString - end - - class WithChildOfImplied < WithStringImpliedChild - end - - class WithProc < Base - layout proc { |c| "overwrite" } - - def index - render :template => ActionView::Template::Text.new("Hello proc!") - end - end - - class WithSymbol < Base - layout :hello - - def index - render :template => ActionView::Template::Text.new("Hello symbol!") - end - private - def hello - "overwrite" - end - end - - class WithSymbolReturningString < Base - layout :no_hello - - def index - render :template => ActionView::Template::Text.new("Hello missing symbol!") - end - private - def no_hello - nil - end - end - - class WithSymbolReturningNil < Base - layout :nilz - - def index - render :template => ActionView::Template::Text.new("Hello nilz!") - end - - def nilz() end - end - - class WithSymbolReturningObj < Base - layout :objekt - - def index - render :template => ActionView::Template::Text.new("Hello nilz!") - end - - def objekt - Object.new - end - end - - class WithSymbolAndNoMethod < Base - layout :no_method - - def index - render :template => ActionView::Template::Text.new("Hello boom!") - end - end - - class WithMissingLayout < Base - layout "missing" - - def index - render :template => ActionView::Template::Text.new("Hello missing!") - end - end - - class WithFalseLayout < Base - layout false - - def index - render :template => ActionView::Template::Text.new("Hello false!") - end - end - - class WithNilLayout < Base - layout nil - - def index - render :template => ActionView::Template::Text.new("Hello nil!") - end - end - - class TestBase < ActiveSupport::TestCase - test "when no layout is specified, and no default is available, render without a layout" do - controller = Blank.new - controller.process(:index) - assert_equal "Hello blank!", controller.response_body - end - - test "when layout is specified as a string, render with that layout" do - controller = WithString.new - controller.process(:index) - assert_equal "With String Hello string!", controller.response_body - end - - test "when layout is overwriten by :default in render, render default layout" do - controller = WithString.new - controller.process(:overwrite_default) - assert_equal "With String Hello string!", controller.response_body - end - - test "when layout is overwriten by string in render, render new layout" do - controller = WithString.new - controller.process(:overwrite_string) - assert_equal "Overwrite Hello string!", controller.response_body - end - - test "when layout is overwriten by false in render, render no layout" do - controller = WithString.new - controller.process(:overwrite_false) - assert_equal "Hello string!", controller.response_body - end - - test "when text is rendered, render no layout" do - controller = WithString.new - controller.process(:overwrite_skip) - assert_equal "Hello text!", controller.response_body - end - - test "when layout is specified as a string, but the layout is missing, raise an exception" do - assert_raises(ActionView::MissingTemplate) { WithMissingLayout.new.process(:index) } - end - - test "when layout is specified as false, do not use a layout" do - controller = WithFalseLayout.new - controller.process(:index) - assert_equal "Hello false!", controller.response_body - end - - test "when layout is specified as nil, do not use a layout" do - controller = WithNilLayout.new - controller.process(:index) - assert_equal "Hello nil!", controller.response_body - end - - test "when layout is specified as a proc, call it and use the layout returned" do - controller = WithProc.new - controller.process(:index) - assert_equal "Overwrite Hello proc!", controller.response_body - end - - test "when layout is specified as a symbol, call the requested method and use the layout returned" do - controller = WithSymbol.new - controller.process(:index) - assert_equal "Overwrite Hello symbol!", controller.response_body - end - - test "when layout is specified as a symbol and the method returns nil, don't use a layout" do - controller = WithSymbolReturningNil.new - controller.process(:index) - assert_equal "Hello nilz!", controller.response_body - end - - test "when the layout is specified as a symbol and the method doesn't exist, raise an exception" do - assert_raises(NoMethodError) { WithSymbolAndNoMethod.new.process(:index) } - end - - test "when the layout is specified as a symbol and the method returns something besides a string/false/nil, raise an exception" do - assert_raises(ArgumentError) { WithSymbolReturningObj.new.process(:index) } - end - - test "when a child controller does not have a layout, use the parent controller layout" do - controller = WithStringChild.new - controller.process(:index) - assert_equal "With String Hello string!", controller.response_body - end - - test "when a child controller has specified a layout, use that layout and not the parent controller layout" do - controller = WithStringOverriddenChild.new - controller.process(:index) - assert_equal "With Override Hello string!", controller.response_body - end - - test "when a child controller has an implied layout, use that layout and not the parent controller layout" do - controller = WithStringImpliedChild.new - controller.process(:index) - assert_equal "With Implied Hello string!", controller.response_body - end - - test "when a child controller specifies layout nil, do not use the parent layout" do - controller = WithNilChild.new - controller.process(:index) - assert_equal "Hello string!", controller.response_body - end - - test "when a grandchild has no layout specified, the child has an implied layout, and the " \ - "parent has specified a layout, use the child controller layout" do - controller = WithChildOfImplied.new - controller.process(:index) - assert_equal "With Implied Hello string!", controller.response_body - end - - test "raises an exception when specifying layout true" do - assert_raises ArgumentError do - Object.class_eval do - class ::BadFailLayout < AbstractControllerTests::Layouts::Base - layout true - end - end - end - end - end - end -end \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/render_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/render_test.rb deleted file mode 100644 index 70fe746d5..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/render_test.rb +++ /dev/null @@ -1,102 +0,0 @@ -require 'abstract_unit' - -module AbstractController - module Testing - - class ControllerRenderer < AbstractController::Base - include AbstractController::Rendering - - def _prefix - "renderer" - end - - self.view_paths = [ActionView::FixtureResolver.new( - "template.erb" => "With Template", - "renderer/default.erb" => "With Default", - "renderer/string.erb" => "With String", - "renderer/symbol.erb" => "With Symbol", - "string/with_path.erb" => "With String With Path", - "some/file.erb" => "With File" - )] - - def template - render :template => "template" - end - - def file - render :file => "some/file" - end - - def inline - render :inline => "With <%= :Inline %>" - end - - def text - render :text => "With Text" - end - - def default - render - end - - def string - render "string" - end - - def string_with_path - render "string/with_path" - end - - def symbol - render :symbol - end - end - - class TestRenderer < ActiveSupport::TestCase - - def setup - @controller = ControllerRenderer.new - end - - def test_render_template - @controller.process(:template) - assert_equal "With Template", @controller.response_body - end - - def test_render_file - @controller.process(:file) - assert_equal "With File", @controller.response_body - end - - def test_render_inline - @controller.process(:inline) - assert_equal "With Inline", @controller.response_body - end - - def test_render_text - @controller.process(:text) - assert_equal "With Text", @controller.response_body - end - - def test_render_default - @controller.process(:default) - assert_equal "With Default", @controller.response_body - end - - def test_render_string - @controller.process(:string) - assert_equal "With String", @controller.response_body - end - - def test_render_symbol - @controller.process(:symbol) - assert_equal "With Symbol", @controller.response_body - end - - def test_render_string_with_path - @controller.process(:string_with_path) - assert_equal "With String With Path", @controller.response_body - end - end - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/translation_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/translation_test.rb deleted file mode 100644 index a8dd5c987..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/translation_test.rb +++ /dev/null @@ -1,26 +0,0 @@ -require 'abstract_unit' - -# class TranslatingController < ActionController::Base -# end - -class TranslationControllerTest < Test::Unit::TestCase - def setup - @controller = ActionController::Base.new - end - - def test_action_controller_base_responds_to_translate - assert_respond_to @controller, :translate - end - - def test_action_controller_base_responds_to_t - assert_respond_to @controller, :t - end - - def test_action_controller_base_responds_to_localize - assert_respond_to @controller, :localize - end - - def test_action_controller_base_responds_to_l - assert_respond_to @controller, :l - end -end \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/views/abstract_controller/testing/me3/formatted.html.erb b/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/views/abstract_controller/testing/me3/formatted.html.erb deleted file mode 100644 index 785bf6919..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/views/abstract_controller/testing/me3/formatted.html.erb +++ /dev/null @@ -1 +0,0 @@ -Hello from me3/formatted.html.erb \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/views/abstract_controller/testing/me3/index.erb b/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/views/abstract_controller/testing/me3/index.erb deleted file mode 100644 index f079ad820..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/views/abstract_controller/testing/me3/index.erb +++ /dev/null @@ -1 +0,0 @@ -Hello from me3/index.erb \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/views/abstract_controller/testing/me4/index.erb b/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/views/abstract_controller/testing/me4/index.erb deleted file mode 100644 index 89dce12bd..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/views/abstract_controller/testing/me4/index.erb +++ /dev/null @@ -1 +0,0 @@ -Hello from me4/index.erb \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/views/abstract_controller/testing/me5/index.erb b/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/views/abstract_controller/testing/me5/index.erb deleted file mode 100644 index 84d0b7417..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/views/abstract_controller/testing/me5/index.erb +++ /dev/null @@ -1 +0,0 @@ -Hello from me5/index.erb \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/views/action_with_ivars.erb b/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/views/action_with_ivars.erb deleted file mode 100644 index 8d8ae22fd..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/views/action_with_ivars.erb +++ /dev/null @@ -1 +0,0 @@ -<%= @my_ivar %> from index_with_ivars.erb \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/views/helper_test.erb b/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/views/helper_test.erb deleted file mode 100644 index 8ae45cc19..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/views/helper_test.erb +++ /dev/null @@ -1 +0,0 @@ -Hello <%= helpery_test %> : <%= included_method %> \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/views/index.erb b/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/views/index.erb deleted file mode 100644 index cc1a8b8c8..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/views/index.erb +++ /dev/null @@ -1 +0,0 @@ -Hello from index.erb \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/views/layouts/abstract_controller/testing/me4.erb b/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/views/layouts/abstract_controller/testing/me4.erb deleted file mode 100644 index 172dd5656..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/views/layouts/abstract_controller/testing/me4.erb +++ /dev/null @@ -1 +0,0 @@ -Me4 Enter : <%= yield %> : Exit \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/views/layouts/application.erb b/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/views/layouts/application.erb deleted file mode 100644 index 27317140a..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/views/layouts/application.erb +++ /dev/null @@ -1 +0,0 @@ -Application Enter : <%= yield %> : Exit \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/views/naked_render.erb b/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/views/naked_render.erb deleted file mode 100644 index 1b3d03878..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract/views/naked_render.erb +++ /dev/null @@ -1 +0,0 @@ -Hello from naked_render.erb \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract_unit.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract_unit.rb deleted file mode 100644 index 7757eedc3..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/abstract_unit.rb +++ /dev/null @@ -1,329 +0,0 @@ -require File.expand_path('../../../load_paths', __FILE__) - -lib = File.expand_path("#{File.dirname(__FILE__)}/../lib") -$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib) - -activemodel_path = File.expand_path('../../../activemodel/lib', __FILE__) -$:.unshift(activemodel_path) if File.directory?(activemodel_path) && !$:.include?(activemodel_path) - -$:.unshift(File.dirname(__FILE__) + '/lib') -$:.unshift(File.dirname(__FILE__) + '/fixtures/helpers') -$:.unshift(File.dirname(__FILE__) + '/fixtures/alternate_helpers') - -ENV['TMPDIR'] = File.join(File.dirname(__FILE__), 'tmp') - -require 'active_support/core_ext/kernel/reporting' - -require 'active_support/core_ext/string/encoding' -if "ruby".encoding_aware? - # These are the normal settings that will be set up by Railties - # TODO: Have these tests support other combinations of these values - silence_warnings do - Encoding.default_internal = "UTF-8" - Encoding.default_external = "UTF-8" - end -end - -require 'test/unit' -require 'abstract_controller' -require 'action_controller' -require 'action_view' -require 'action_view/testing/resolvers' -require 'action_dispatch' -require 'active_support/dependencies' -require 'active_model' -require 'active_record' -require 'action_controller/caching' -require 'action_controller/caching/sweeping' - -begin - require 'ruby-debug' - Debugger.settings[:autoeval] = true - Debugger.start -rescue LoadError - # Debugging disabled. `gem install ruby-debug` to enable. -end - -require 'pp' # require 'pp' early to prevent hidden_methods from not picking up the pretty-print methods until too late - -module Rails -end - -# Monkey patch the old routes initialization to be silenced. -class ActionDispatch::Routing::DeprecatedMapper - def initialize_with_silencer(*args) - ActiveSupport::Deprecation.silence { initialize_without_silencer(*args) } - end - alias_method_chain :initialize, :silencer -end - -ActiveSupport::Dependencies.hook! - -# Show backtraces for deprecated behavior for quicker cleanup. -ActiveSupport::Deprecation.debug = true - -# Register danish language for testing -I18n.backend.store_translations 'da', {} -I18n.backend.store_translations 'pt-BR', {} -ORIGINAL_LOCALES = I18n.available_locales.map {|locale| locale.to_s }.sort - -FIXTURE_LOAD_PATH = File.join(File.dirname(__FILE__), 'fixtures') -FIXTURES = Pathname.new(FIXTURE_LOAD_PATH) - -module RackTestUtils - def body_to_string(body) - if body.respond_to?(:each) - str = "" - body.each {|s| str << s } - str - else - body - end - end - extend self -end - -module RenderERBUtils - def render_erb(string) - template = ActionView::Template.new( - string.strip, - "test template", - ActionView::Template::Handlers::ERB, - {}) - - template.render(self, {}).strip - end -end - -module SetupOnce - extend ActiveSupport::Concern - - included do - cattr_accessor :setup_once_block - self.setup_once_block = nil - - setup :run_setup_once - end - - module ClassMethods - def setup_once(&block) - self.setup_once_block = block - end - end - - private - def run_setup_once - if self.setup_once_block - self.setup_once_block.call - self.setup_once_block = nil - end - end -end - -SharedTestRoutes = ActionDispatch::Routing::RouteSet.new - -module ActiveSupport - class TestCase - include SetupOnce - # Hold off drawing routes until all the possible controller classes - # have been loaded. - setup_once do - SharedTestRoutes.draw do |map| - # FIXME: match ':controller(/:action(/:id))' - map.connect ':controller/:action/:id' - end - - ActionController::IntegrationTest.app.routes.draw do |map| - # FIXME: match ':controller(/:action(/:id))' - map.connect ':controller/:action/:id' - end - end - end -end - -class RoutedRackApp - attr_reader :routes - - def initialize(routes, &blk) - @routes = routes - @stack = ActionDispatch::MiddlewareStack.new(&blk).build(@routes) - end - - def call(env) - @stack.call(env) - end -end - -class BasicController - attr_accessor :request - - def config - @config ||= ActiveSupport::InheritableOptions.new(ActionController::Base.config).tap do |config| - # VIEW TODO: View tests should not require a controller - public_dir = File.expand_path("../fixtures/public", __FILE__) - config.assets_dir = public_dir - config.javascripts_dir = "#{public_dir}/javascripts" - config.stylesheets_dir = "#{public_dir}/stylesheets" - config - end - end -end - -class ActionDispatch::IntegrationTest < ActiveSupport::TestCase - setup do - @routes = SharedTestRoutes - end -end - -class ActionController::IntegrationTest < ActiveSupport::TestCase - def self.build_app(routes = nil) - RoutedRackApp.new(routes || ActionDispatch::Routing::RouteSet.new) do |middleware| - middleware.use "ActionDispatch::ShowExceptions" - middleware.use "ActionDispatch::Callbacks" - middleware.use "ActionDispatch::ParamsParser" - middleware.use "ActionDispatch::Cookies" - middleware.use "ActionDispatch::Flash" - middleware.use "ActionDispatch::Head" - yield(middleware) if block_given? - end - end - - self.app = build_app - - # Stub Rails dispatcher so it does not get controller references and - # simply return the controller#action as Rack::Body. - class StubDispatcher < ::ActionDispatch::Routing::RouteSet::Dispatcher - protected - def controller_reference(controller_param) - controller_param - end - - def dispatch(controller, action, env) - [200, {'Content-Type' => 'text/html'}, ["#{controller}##{action}"]] - end - end - - def self.stub_controllers - old_dispatcher = ActionDispatch::Routing::RouteSet::Dispatcher - ActionDispatch::Routing::RouteSet.module_eval { remove_const :Dispatcher } - ActionDispatch::Routing::RouteSet.module_eval { const_set :Dispatcher, StubDispatcher } - yield ActionDispatch::Routing::RouteSet.new - ensure - ActionDispatch::Routing::RouteSet.module_eval { remove_const :Dispatcher } - ActionDispatch::Routing::RouteSet.module_eval { const_set :Dispatcher, old_dispatcher } - end - - def with_routing(&block) - temporary_routes = ActionDispatch::Routing::RouteSet.new - old_app, self.class.app = self.class.app, self.class.build_app(temporary_routes) - old_routes = SharedTestRoutes - silence_warnings { Object.const_set(:SharedTestRoutes, temporary_routes) } - - yield temporary_routes - ensure - self.class.app = old_app - silence_warnings { Object.const_set(:SharedTestRoutes, old_routes) } - end - - def with_autoload_path(path) - path = File.join(File.dirname(__FILE__), "fixtures", path) - if ActiveSupport::Dependencies.autoload_paths.include?(path) - yield - else - begin - ActiveSupport::Dependencies.autoload_paths << path - yield - ensure - ActiveSupport::Dependencies.autoload_paths.reject! {|p| p == path} - ActiveSupport::Dependencies.clear - end - end - end -end - -# Temporary base class -class Rack::TestCase < ActionController::IntegrationTest - def self.testing(klass = nil) - if klass - @testing = "/#{klass.name.underscore}".sub!(/_controller$/, '') - else - @testing - end - end - - def get(thing, *args) - if thing.is_a?(Symbol) - super("#{self.class.testing}/#{thing}", *args) - else - super - end - end - - def assert_body(body) - assert_equal body, Array.wrap(response.body).join - end - - def assert_status(code) - assert_equal code, response.status - end - - def assert_response(body, status = 200, headers = {}) - assert_body body - assert_status status - headers.each do |header, value| - assert_header header, value - end - end - - def assert_content_type(type) - assert_equal type, response.headers["Content-Type"] - end - - def assert_header(name, value) - assert_equal value, response.headers[name] - end -end - -class ActionController::Base - def self.test_routes(&block) - routes = ActionDispatch::Routing::RouteSet.new - routes.draw(&block) - include routes.url_helpers - end -end - -class ::ApplicationController < ActionController::Base -end - -module ActionView - class TestCase - # Must repeat the setup because AV::TestCase is a duplication - # of AC::TestCase - setup do - @routes = SharedTestRoutes - end - end -end - -module ActionController - class Base - include ActionController::Testing - end - - Base.view_paths = FIXTURE_LOAD_PATH - - class TestCase - include ActionDispatch::TestProcess - - setup do - @routes = SharedTestRoutes - end - end -end - -# This stub emulates the Railtie including the URL helpers from a Rails application -module ActionController - class Base - include SharedTestRoutes.url_helpers - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/active_record_unit.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/active_record_unit.rb deleted file mode 100644 index 19efc5a09..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/active_record_unit.rb +++ /dev/null @@ -1,99 +0,0 @@ -require 'abstract_unit' - -# Define the essentials -class ActiveRecordTestConnector - cattr_accessor :able_to_connect - cattr_accessor :connected - - # Set our defaults - self.connected = false - self.able_to_connect = true -end - -# Try to grab AR -unless defined?(ActiveRecord) && defined?(Fixtures) - begin - PATH_TO_AR = "#{File.dirname(__FILE__)}/../../activerecord/lib" - raise LoadError, "#{PATH_TO_AR} doesn't exist" unless File.directory?(PATH_TO_AR) - $LOAD_PATH.unshift PATH_TO_AR - require 'active_record' - rescue LoadError => e - $stderr.print "Failed to load Active Record. Skipping Active Record assertion tests: #{e}" - ActiveRecordTestConnector.able_to_connect = false - end -end -$stderr.flush - - -# Define the rest of the connector -class ActiveRecordTestConnector - class << self - def setup - unless self.connected || !self.able_to_connect - setup_connection - load_schema - require_fixture_models - self.connected = true - end - rescue Exception => e # errors from ActiveRecord setup - $stderr.puts "\nSkipping ActiveRecord assertion tests: #{e}" - #$stderr.puts " #{e.backtrace.join("\n ")}\n" - self.able_to_connect = false - end - - private - def setup_connection - if Object.const_defined?(:ActiveRecord) - defaults = { :database => ':memory:' } - begin - adapter = defined?(JRUBY_VERSION) ? 'jdbcsqlite3' : 'sqlite3' - options = defaults.merge :adapter => adapter, :timeout => 500 - ActiveRecord::Base.establish_connection(options) - ActiveRecord::Base.configurations = { 'sqlite3_ar_integration' => options } - ActiveRecord::Base.connection - rescue Exception # errors from establishing a connection - $stderr.puts 'SQLite 3 unavailable; trying SQLite 2.' - options = defaults.merge :adapter => 'sqlite' - ActiveRecord::Base.establish_connection(options) - ActiveRecord::Base.configurations = { 'sqlite2_ar_integration' => options } - ActiveRecord::Base.connection - end - - Object.send(:const_set, :QUOTED_TYPE, ActiveRecord::Base.connection.quote_column_name('type')) unless Object.const_defined?(:QUOTED_TYPE) - else - raise "Can't setup connection since ActiveRecord isn't loaded." - end - end - - # Load actionpack sqlite tables - def load_schema - File.read(File.dirname(__FILE__) + "/fixtures/db_definitions/sqlite.sql").split(';').each do |sql| - ActiveRecord::Base.connection.execute(sql) unless sql.blank? - end - end - - def require_fixture_models - Dir.glob(File.dirname(__FILE__) + "/fixtures/*.rb").each {|f| require f} - end - end -end - -class ActiveRecordTestCase < ActionController::TestCase - include ActiveRecord::TestFixtures - - # Set our fixture path - if ActiveRecordTestConnector.able_to_connect - self.fixture_path = [FIXTURE_LOAD_PATH] - self.use_transactional_fixtures = false - end - - def self.fixtures(*args) - super if ActiveRecordTestConnector.connected - end - - def run(*args) - super if ActiveRecordTestConnector.connected - end -end - -ActiveRecordTestConnector.setup diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/activerecord/active_record_store_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/activerecord/active_record_store_test.rb deleted file mode 100644 index 99459752b..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/activerecord/active_record_store_test.rb +++ /dev/null @@ -1,220 +0,0 @@ -require 'active_record_unit' - -class ActiveRecordStoreTest < ActionController::IntegrationTest - class TestController < ActionController::Base - def no_session_access - head :ok - end - - def set_session_value - raise "missing session!" unless session - session[:foo] = params[:foo] || "bar" - head :ok - end - - def get_session_value - render :text => "foo: #{session[:foo].inspect}" - end - - def get_session_id - render :text => "#{request.session_options[:id]}" - end - - def call_reset_session - session[:foo] - reset_session - session[:foo] = "baz" - head :ok - end - - def rescue_action(e) raise end - end - - def setup - ActiveRecord::SessionStore.session_class.create_table! - end - - def teardown - ActiveRecord::SessionStore.session_class.drop_table! - end - - %w{ session sql_bypass }.each do |class_name| - define_method("test_setting_and_getting_session_value_with_#{class_name}_store") do - with_store class_name do - with_test_route_set do - get '/set_session_value' - assert_response :success - assert cookies['_session_id'] - - get '/get_session_value' - assert_response :success - assert_equal 'foo: "bar"', response.body - - get '/set_session_value', :foo => "baz" - assert_response :success - assert cookies['_session_id'] - - get '/get_session_value' - assert_response :success - assert_equal 'foo: "baz"', response.body - - get '/call_reset_session' - assert_response :success - assert_not_equal [], headers['Set-Cookie'] - end - end - end - end - - def test_getting_nil_session_value - with_test_route_set do - get '/get_session_value' - assert_response :success - assert_equal 'foo: nil', response.body - end - end - - def test_setting_session_value_after_session_reset - with_test_route_set do - get '/set_session_value' - assert_response :success - assert cookies['_session_id'] - session_id = cookies['_session_id'] - - get '/call_reset_session' - assert_response :success - assert_not_equal [], headers['Set-Cookie'] - - get '/get_session_value' - assert_response :success - assert_equal 'foo: "baz"', response.body - - get '/get_session_id' - assert_response :success - assert_not_equal session_id, response.body - end - end - - def test_getting_session_value_after_session_reset - with_test_route_set do - get '/set_session_value' - assert_response :success - assert cookies['_session_id'] - session_cookie = cookies.send(:hash_for)['_session_id'] - - get '/call_reset_session' - assert_response :success - assert_not_equal [], headers['Set-Cookie'] - - cookies << session_cookie # replace our new session_id with our old, pre-reset session_id - - get '/get_session_value' - assert_response :success - assert_equal 'foo: nil', response.body, "data for this session should have been obliterated from the database" - end - end - - def test_getting_from_nonexistent_session - with_test_route_set do - get '/get_session_value' - assert_response :success - assert_equal 'foo: nil', response.body - assert_nil cookies['_session_id'], "should only create session on write, not read" - end - end - - def test_getting_session_id - with_test_route_set do - get '/set_session_value' - assert_response :success - assert cookies['_session_id'] - session_id = cookies['_session_id'] - - get '/get_session_id' - assert_response :success - assert_equal session_id, response.body, "should be able to read session id without accessing the session hash" - end - end - - def test_doesnt_write_session_cookie_if_session_id_is_already_exists - with_test_route_set do - get '/set_session_value' - assert_response :success - assert cookies['_session_id'] - - get '/get_session_value' - assert_response :success - assert_equal nil, headers['Set-Cookie'], "should not resend the cookie again if session_id cookie is already exists" - end - end - - def test_prevents_session_fixation - with_test_route_set do - get '/set_session_value' - assert_response :success - assert cookies['_session_id'] - - get '/get_session_value' - assert_response :success - assert_equal 'foo: "bar"', response.body - session_id = cookies['_session_id'] - assert session_id - - reset! - - get '/get_session_value', :_session_id => session_id - assert_response :success - assert_equal 'foo: nil', response.body - assert_not_equal session_id, cookies['_session_id'] - end - end - - def test_allows_session_fixation - with_test_route_set(:cookie_only => false) do - get '/set_session_value' - assert_response :success - assert cookies['_session_id'] - - get '/get_session_value' - assert_response :success - assert_equal 'foo: "bar"', response.body - session_id = cookies['_session_id'] - assert session_id - - reset! - - get '/set_session_value', :_session_id => session_id, :foo => "baz" - assert_response :success - assert_equal session_id, cookies['_session_id'] - - get '/get_session_value', :_session_id => session_id - assert_response :success - assert_equal 'foo: "baz"', response.body - assert_equal session_id, cookies['_session_id'] - end - end - - private - - def with_test_route_set(options = {}) - with_routing do |set| - set.draw do |map| - match ':action', :to => 'active_record_store_test/test' - end - - @app = self.class.build_app(set) do |middleware| - middleware.use ActiveRecord::SessionStore, options.reverse_merge(:key => '_session_id') - middleware.delete "ActionDispatch::ShowExceptions" - end - - yield - end - end - - def with_store(class_name) - session_class, ActiveRecord::SessionStore.session_class = - ActiveRecord::SessionStore.session_class, "ActiveRecord::SessionStore::#{class_name.camelize}".constantize - yield - ActiveRecord::SessionStore.session_class = session_class - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/activerecord/controller_runtime_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/activerecord/controller_runtime_test.rb deleted file mode 100644 index b217635b8..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/activerecord/controller_runtime_test.rb +++ /dev/null @@ -1,42 +0,0 @@ -require 'active_record_unit' -require 'active_record/railties/controller_runtime' -require 'fixtures/project' -require 'active_support/log_subscriber/test_helper' -require 'action_controller/log_subscriber' - -ActionController::Base.send :include, ActiveRecord::Railties::ControllerRuntime - -class ControllerRuntimeLogSubscriberTest < ActionController::TestCase - class LogSubscriberController < ActionController::Base - def show - render :inline => "<%= Project.all %>" - end - end - - include ActiveSupport::LogSubscriber::TestHelper - tests LogSubscriberController - - def setup - super - @old_logger = ActionController::Base.logger - ActionController::LogSubscriber.attach_to :action_controller - end - - def teardown - super - ActiveSupport::LogSubscriber.log_subscribers.clear - ActionController::Base.logger = @old_logger - end - - def set_logger(logger) - ActionController::Base.logger = logger - end - - def test_log_with_active_record - get :show - wait - - assert_equal 2, @logger.logged(:info).size - assert_match /\(Views: [\d\.]+ms | ActiveRecord: [\d\.]+ms\)/, @logger.logged(:info)[1] - end -end \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/activerecord/polymorphic_routes_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/activerecord/polymorphic_routes_test.rb deleted file mode 100644 index 7fc843c9c..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/activerecord/polymorphic_routes_test.rb +++ /dev/null @@ -1,450 +0,0 @@ -require 'active_record_unit' -require 'fixtures/project' - -class Task < ActiveRecord::Base - set_table_name 'projects' -end - -class Step < ActiveRecord::Base - set_table_name 'projects' -end - -class Bid < ActiveRecord::Base - set_table_name 'projects' -end - -class Tax < ActiveRecord::Base - set_table_name 'projects' -end - -class Fax < ActiveRecord::Base - set_table_name 'projects' -end - -class Series < ActiveRecord::Base - set_table_name 'projects' -end - -class PolymorphicRoutesTest < ActionController::TestCase - include SharedTestRoutes.url_helpers - self.default_url_options[:host] = 'example.com' - - def setup - @project = Project.new - @task = Task.new - @step = Step.new - @bid = Bid.new - @tax = Tax.new - @fax = Fax.new - @series = Series.new - end - - def test_with_record - with_test_routes do - @project.save - assert_equal "http://example.com/projects/#{@project.id}", polymorphic_url(@project) - end - end - - def test_with_class - with_test_routes do - assert_equal "http://example.com/projects", polymorphic_url(@project.class) - end - end - - def test_with_new_record - with_test_routes do - assert_equal "http://example.com/projects", polymorphic_url(@project) - end - end - - def test_with_destroyed_record - with_test_routes do - @project.destroy - assert_equal "http://example.com/projects", polymorphic_url(@project) - end - end - - def test_with_record_and_action - with_test_routes do - assert_equal "http://example.com/projects/new", polymorphic_url(@project, :action => 'new') - end - end - - def test_url_helper_prefixed_with_new - with_test_routes do - assert_equal "http://example.com/projects/new", new_polymorphic_url(@project) - end - end - - def test_url_helper_prefixed_with_edit - with_test_routes do - @project.save - assert_equal "http://example.com/projects/#{@project.id}/edit", edit_polymorphic_url(@project) - end - end - - def test_url_helper_prefixed_with_edit_with_url_options - with_test_routes do - @project.save - assert_equal "http://example.com/projects/#{@project.id}/edit?param1=10", edit_polymorphic_url(@project, :param1 => '10') - end - end - - def test_url_helper_with_url_options - with_test_routes do - @project.save - assert_equal "http://example.com/projects/#{@project.id}?param1=10", polymorphic_url(@project, :param1 => '10') - end - end - - def test_format_option - with_test_routes do - @project.save - assert_equal "http://example.com/projects/#{@project.id}.pdf", polymorphic_url(@project, :format => :pdf) - end - end - - def test_format_option_with_url_options - with_test_routes do - @project.save - assert_equal "http://example.com/projects/#{@project.id}.pdf?param1=10", polymorphic_url(@project, :format => :pdf, :param1 => '10') - end - end - - def test_id_and_format_option - with_test_routes do - @project.save - assert_equal "http://example.com/projects/#{@project.id}.pdf", polymorphic_url(:id => @project, :format => :pdf) - end - end - - def test_with_nested - with_test_routes do - @project.save - @task.save - assert_equal "http://example.com/projects/#{@project.id}/tasks/#{@task.id}", polymorphic_url([@project, @task]) - end - end - - def test_with_nested_unsaved - with_test_routes do - @project.save - assert_equal "http://example.com/projects/#{@project.id}/tasks", polymorphic_url([@project, @task]) - end - end - - def test_with_nested_destroyed - with_test_routes do - @project.save - @task.destroy - assert_equal "http://example.com/projects/#{@project.id}/tasks", polymorphic_url([@project, @task]) - end - end - - def test_with_nested_class - with_test_routes do - @project.save - assert_equal "http://example.com/projects/#{@project.id}/tasks", polymorphic_url([@project, @task.class]) - end - end - - def test_class_with_array_and_namespace - with_admin_test_routes do - assert_equal "http://example.com/admin/projects", polymorphic_url([:admin, @project.class]) - end - end - - def test_new_with_array_and_namespace - with_admin_test_routes do - assert_equal "http://example.com/admin/projects/new", polymorphic_url([:admin, @project], :action => 'new') - end - end - - def test_unsaved_with_array_and_namespace - with_admin_test_routes do - assert_equal "http://example.com/admin/projects", polymorphic_url([:admin, @project]) - end - end - - def test_nested_unsaved_with_array_and_namespace - with_admin_test_routes do - @project.save - assert_equal "http://example.com/admin/projects/#{@project.id}/tasks", polymorphic_url([:admin, @project, @task]) - end - end - - def test_nested_with_array_and_namespace - with_admin_test_routes do - @project.save - @task.save - assert_equal "http://example.com/admin/projects/#{@project.id}/tasks/#{@task.id}", polymorphic_url([:admin, @project, @task]) - end - end - - def test_ordering_of_nesting_and_namespace - with_admin_and_site_test_routes do - @project.save - @task.save - @step.save - assert_equal "http://example.com/admin/projects/#{@project.id}/site/tasks/#{@task.id}/steps/#{@step.id}", polymorphic_url([:admin, @project, :site, @task, @step]) - end - end - - def test_nesting_with_array_ending_in_singleton_resource - with_test_routes do - @project.save - assert_equal "http://example.com/projects/#{@project.id}/bid", polymorphic_url([@project, :bid]) - end - end - - def test_nesting_with_array_containing_singleton_resource - with_test_routes do - @project.save - @task.save - assert_equal "http://example.com/projects/#{@project.id}/bid/tasks/#{@task.id}", polymorphic_url([@project, :bid, @task]) - end - end - - def test_nesting_with_array_containing_singleton_resource_and_format - with_test_routes do - @project.save - @task.save - assert_equal "http://example.com/projects/#{@project.id}/bid/tasks/#{@task.id}.pdf", polymorphic_url([@project, :bid, @task], :format => :pdf) - end - end - - def test_nesting_with_array_containing_namespace_and_singleton_resource - with_admin_test_routes do - @project.save - @task.save - assert_equal "http://example.com/admin/projects/#{@project.id}/bid/tasks/#{@task.id}", polymorphic_url([:admin, @project, :bid, @task]) - end - end - - def test_nesting_with_array_containing_nil - with_test_routes do - @project.save - assert_equal "http://example.com/projects/#{@project.id}/bid", polymorphic_url([@project, nil, :bid]) - end - end - - def test_with_array_containing_single_object - with_test_routes do - @project.save - assert_equal "http://example.com/projects/#{@project.id}", polymorphic_url([nil, @project]) - end - end - - def test_with_array_containing_single_name - with_test_routes do - @project.save - assert_equal "http://example.com/projects", polymorphic_url([:projects]) - end - end - - def test_with_array_containing_symbols - with_test_routes do - assert_equal "http://example.com/series/new", polymorphic_url([:new, :series]) - end - end - - def test_with_hash - with_test_routes do - @project.save - assert_equal "http://example.com/projects/#{@project.id}", polymorphic_url(:id => @project) - end - end - - def test_polymorphic_path_accepts_options - with_test_routes do - assert_equal "/projects/new", polymorphic_path(@project, :action => 'new') - end - end - - def test_polymorphic_path_does_not_modify_arguments - with_admin_test_routes do - @project.save - @task.save - - options = {} - object_array = [:admin, @project, @task] - original_args = [object_array.dup, options.dup] - - assert_no_difference('object_array.size') { polymorphic_path(object_array, options) } - assert_equal original_args, [object_array, options] - end - end - - # Tests for names where .plural.singular doesn't round-trip - def test_with_irregular_plural_record - with_test_routes do - @tax.save - assert_equal "http://example.com/taxes/#{@tax.id}", polymorphic_url(@tax) - end - end - - def test_with_irregular_plural_class - with_test_routes do - assert_equal "http://example.com/taxes", polymorphic_url(@tax.class) - end - end - - def test_with_irregular_plural_new_record - with_test_routes do - assert_equal "http://example.com/taxes", polymorphic_url(@tax) - end - end - - def test_with_irregular_plural_destroyed_record - with_test_routes do - @tax.destroy - assert_equal "http://example.com/taxes", polymorphic_url(@tax) - end - end - - def test_with_irregular_plural_record_and_action - with_test_routes do - assert_equal "http://example.com/taxes/new", polymorphic_url(@tax, :action => 'new') - end - end - - def test_irregular_plural_url_helper_prefixed_with_new - with_test_routes do - assert_equal "http://example.com/taxes/new", new_polymorphic_url(@tax) - end - end - - def test_irregular_plural_url_helper_prefixed_with_edit - with_test_routes do - @tax.save - assert_equal "http://example.com/taxes/#{@tax.id}/edit", edit_polymorphic_url(@tax) - end - end - - def test_with_nested_irregular_plurals - with_test_routes do - @tax.save - @fax.save - assert_equal "http://example.com/taxes/#{@tax.id}/faxes/#{@fax.id}", polymorphic_url([@tax, @fax]) - end - end - - def test_with_nested_unsaved_irregular_plurals - with_test_routes do - @tax.save - assert_equal "http://example.com/taxes/#{@tax.id}/faxes", polymorphic_url([@tax, @fax]) - end - end - - def test_new_with_irregular_plural_array_and_namespace - with_admin_test_routes do - assert_equal "http://example.com/admin/taxes/new", polymorphic_url([:admin, @tax], :action => 'new') - end - end - - def test_class_with_irregular_plural_array_and_namespace - with_admin_test_routes do - assert_equal "http://example.com/admin/taxes", polymorphic_url([:admin, @tax.class]) - end - end - - def test_unsaved_with_irregular_plural_array_and_namespace - with_admin_test_routes do - assert_equal "http://example.com/admin/taxes", polymorphic_url([:admin, @tax]) - end - end - - def test_nesting_with_irregular_plurals_and_array_ending_in_singleton_resource - with_test_routes do - @tax.save - assert_equal "http://example.com/taxes/#{@tax.id}/bid", polymorphic_url([@tax, :bid]) - end - end - - def test_with_array_containing_single_irregular_plural_object - with_test_routes do - @tax.save - assert_equal "http://example.com/taxes/#{@tax.id}", polymorphic_url([nil, @tax]) - end - end - - def test_with_array_containing_single_name_irregular_plural - with_test_routes do - @tax.save - assert_equal "http://example.com/taxes", polymorphic_url([:taxes]) - end - end - - # Tests for uncountable names - def test_uncountable_resource - with_test_routes do - @series.save - assert_equal "http://example.com/series/#{@series.id}", polymorphic_url(@series) - assert_equal "http://example.com/series", polymorphic_url(Series.new) - end - end - - def with_test_routes(options = {}) - with_routing do |set| - set.draw do |map| - map.resources :projects do |projects| - projects.resources :tasks - projects.resource :bid do |bid| - bid.resources :tasks - end - end - map.resources :taxes do |taxes| - taxes.resources :faxes - taxes.resource :bid - end - map.resources :series - end - - self.class.send(:include, @routes.url_helpers) - yield - end - end - - def with_admin_test_routes(options = {}) - with_routing do |set| - set.draw do - namespace :admin do - resources :projects do - resources :tasks - resource :bid do - resources :tasks - end - end - resources :taxes do - resources :faxes - end - resources :series - end - end - - self.class.send(:include, @routes.url_helpers) - yield - end - end - - def with_admin_and_site_test_routes(options = {}) - with_routing do |set| - set.draw do - namespace :admin do - resources :projects do - namespace :site do - resources :tasks do - resources :steps - end - end - end - end - end - - self.class.send(:include, @routes.url_helpers) - yield - end - end - -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/activerecord/render_partial_with_record_identification_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/activerecord/render_partial_with_record_identification_test.rb deleted file mode 100644 index adcb47fa3..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/activerecord/render_partial_with_record_identification_test.rb +++ /dev/null @@ -1,190 +0,0 @@ -require 'active_record_unit' - -class RenderPartialWithRecordIdentificationController < ActionController::Base - def render_with_has_many_and_belongs_to_association - @developer = Developer.find(1) - render :partial => @developer.projects - end - - def render_with_has_many_association - @topic = Topic.find(1) - render :partial => @topic.replies - end - - def render_with_named_scope - render :partial => Reply.base - end - - def render_with_has_many_through_association - @developer = Developer.find(:first) - render :partial => @developer.topics - end - - def render_with_has_one_association - @company = Company.find(1) - render :partial => @company.mascot - end - - def render_with_belongs_to_association - @reply = Reply.find(1) - render :partial => @reply.topic - end - - def render_with_record - @developer = Developer.find(:first) - render :partial => @developer - end - - def render_with_record_collection - @developers = Developer.find(:all) - render :partial => @developers - end - - def render_with_record_collection_and_spacer_template - @developer = Developer.find(1) - render :partial => @developer.projects, :spacer_template => 'test/partial_only' - end -end - -class RenderPartialWithRecordIdentificationTest < ActiveRecordTestCase - tests RenderPartialWithRecordIdentificationController - fixtures :developers, :projects, :developers_projects, :topics, :replies, :companies, :mascots - - def test_rendering_partial_with_has_many_and_belongs_to_association - get :render_with_has_many_and_belongs_to_association - assert_template 'projects/_project' - assert_equal assigns(:developer).projects.map(&:name).join, @response.body - end - - def test_rendering_partial_with_has_many_association - get :render_with_has_many_association - assert_template 'replies/_reply' - assert_equal 'Birdman is better!', @response.body - end - - def test_rendering_partial_with_named_scope - get :render_with_named_scope - assert_template 'replies/_reply' - assert_equal 'Birdman is better!Nuh uh!', @response.body - end - - def test_render_with_record - get :render_with_record - assert_template 'developers/_developer' - assert_equal 'David', @response.body - end - - def test_render_with_record_collection - get :render_with_record_collection - assert_template 'developers/_developer' - assert_equal 'DavidJamisfixture_3fixture_4fixture_5fixture_6fixture_7fixture_8fixture_9fixture_10Jamis', @response.body - end - - def test_render_with_record_collection_and_spacer_template - get :render_with_record_collection_and_spacer_template - assert_equal assigns(:developer).projects.map(&:name).join('only partial'), @response.body - end - - def test_rendering_partial_with_has_one_association - mascot = Company.find(1).mascot - get :render_with_has_one_association - assert_template 'mascots/_mascot' - assert_equal mascot.name, @response.body - end -end - -class RenderPartialWithRecordIdentificationController < ActionController::Base - def render_with_has_many_and_belongs_to_association - @developer = Developer.find(1) - render :partial => @developer.projects - end - - def render_with_has_many_association - @topic = Topic.find(1) - render :partial => @topic.replies - end - - def render_with_has_many_through_association - @developer = Developer.find(:first) - render :partial => @developer.topics - end - - def render_with_belongs_to_association - @reply = Reply.find(1) - render :partial => @reply.topic - end - - def render_with_record - @developer = Developer.find(:first) - render :partial => @developer - end - - def render_with_record_collection - @developers = Developer.find(:all) - render :partial => @developers - end -end - -class Game < Struct.new(:name, :id) - extend ActiveModel::Naming - include ActiveModel::Conversion - def to_param - id.to_s - end -end - -module Fun - class NestedController < ActionController::Base - def render_with_record_in_nested_controller - render :partial => Game.new("Pong") - end - - def render_with_record_collection_in_nested_controller - render :partial => [ Game.new("Pong"), Game.new("Tank") ] - end - end - - module Serious - class NestedDeeperController < ActionController::Base - def render_with_record_in_deeper_nested_controller - render :partial => Game.new("Chess") - end - - def render_with_record_collection_in_deeper_nested_controller - render :partial => [ Game.new("Chess"), Game.new("Sudoku"), Game.new("Solitaire") ] - end - end - end -end - -class RenderPartialWithRecordIdentificationAndNestedControllersTest < ActiveRecordTestCase - tests Fun::NestedController - - def test_render_with_record_in_nested_controller - get :render_with_record_in_nested_controller - assert_template 'fun/games/_game' - assert_equal 'Pong', @response.body - end - - def test_render_with_record_collection_in_nested_controller - get :render_with_record_collection_in_nested_controller - assert_template 'fun/games/_game' - assert_equal 'PongTank', @response.body - end -end - -class RenderPartialWithRecordIdentificationAndNestedDeeperControllersTest < ActiveRecordTestCase - tests Fun::Serious::NestedDeeperController - - def test_render_with_record_in_deeper_nested_controller - get :render_with_record_in_deeper_nested_controller - assert_template 'fun/serious/games/_game' - assert_equal 'Chess', @response.body - end - - def test_render_with_record_collection_in_deeper_nested_controller - get :render_with_record_collection_in_deeper_nested_controller - assert_template 'fun/serious/games/_game' - assert_equal 'ChessSudokuSolitaire', @response.body - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/action_pack_assertions_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/action_pack_assertions_test.rb deleted file mode 100644 index c5e518ce1..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/action_pack_assertions_test.rb +++ /dev/null @@ -1,574 +0,0 @@ -require 'abstract_unit' -require 'action_controller/vendor/html-scanner' -require 'controller/fake_controllers' - -# a controller class to facilitate the tests -class ActionPackAssertionsController < ActionController::Base - - # this does absolutely nothing - def nothing() head :ok end - - # a standard template - def hello_world() render :template => "test/hello_world"; end - - # a standard template - def hello_xml_world() render :template => "test/hello_xml_world"; end - - # a standard template rendering PDF - def hello_xml_world_pdf - self.content_type = "application/pdf" - render :template => "test/hello_xml_world" - end - - # a standard template rendering PDF - def hello_xml_world_pdf_header - response.headers["Content-Type"] = "application/pdf; charset=utf-8" - render :template => "test/hello_xml_world" - end - - # a standard partial - def partial() render :partial => 'test/partial'; end - - # a redirect to an internal location - def redirect_internal() redirect_to "/nothing"; end - - def redirect_to_action() redirect_to :action => "flash_me", :id => 1, :params => { "panda" => "fun" }; end - - def redirect_to_controller() redirect_to :controller => "elsewhere", :action => "flash_me"; end - - def redirect_to_controller_with_symbol() redirect_to :controller => :elsewhere, :action => :flash_me; end - - def redirect_to_path() redirect_to '/some/path' end - - def redirect_to_named_route() redirect_to route_one_url end - - # a redirect to an external location - def redirect_external() redirect_to "http://www.rubyonrails.org"; end - - # a 404 - def response404() head '404 AWOL' end - - # a 500 - def response500() head '500 Sorry' end - - # a fictional 599 - def response599() head '599 Whoah!' end - - # putting stuff in the flash - def flash_me - flash['hello'] = 'my name is inigo montoya...' - render :text => "Inconceivable!" - end - - # we have a flash, but nothing is in it - def flash_me_naked - flash.clear - render :text => "wow!" - end - - # assign some template instance variables - def assign_this - @howdy = "ho" - render :inline => "Mr. Henke" - end - - def render_based_on_parameters - render :text => "Mr. #{params[:name]}" - end - - def render_url - render :text => "
#{url_for(:action => 'flash_me', :only_path => true)}
" - end - - def render_text_with_custom_content_type - render :text => "Hello!", :content_type => Mime::RSS - end - - # puts something in the session - def session_stuffing - session['xmas'] = 'turkey' - render :text => "ho ho ho" - end - - # raises exception on get requests - def raise_on_get - raise "get" if request.get? - render :text => "request method: #{request.env['REQUEST_METHOD']}" - end - - # raises exception on post requests - def raise_on_post - raise "post" if request.post? - render :text => "request method: #{request.env['REQUEST_METHOD']}" - end - - def get_valid_record - @record = Class.new do - def valid? - true - end - - def errors - Class.new do - def full_messages; []; end - end.new - end - - end.new - - render :nothing => true - end - - - def get_invalid_record - @record = Class.new do - - def valid? - false - end - - def errors - Class.new do - def full_messages; ['...stuff...']; end - end.new - end - end.new - - render :nothing => true - end - - # 911 - def rescue_action(e) raise; end -end - -# Used to test that assert_response includes the exception message -# in the failure message when an action raises and assert_response -# is expecting something other than an error. -class AssertResponseWithUnexpectedErrorController < ActionController::Base - def index - raise 'FAIL' - end - - def show - render :text => "Boom", :status => 500 - end -end - -class UserController < ActionController::Base -end - -module Admin - class InnerModuleController < ActionController::Base - def index - render :nothing => true - end - - def redirect_to_index - redirect_to admin_inner_module_path - end - - def redirect_to_absolute_controller - redirect_to :controller => '/content' - end - - def redirect_to_fellow_controller - redirect_to :controller => 'user' - end - - def redirect_to_top_level_named_route - redirect_to top_level_url(:id => "foo") - end - end -end - -# require "action_dispatch/test_process" - -# a test case to exercise the new capabilities TestRequest & TestResponse -class ActionPackAssertionsControllerTest < ActionController::TestCase - # -- assertion-based testing ------------------------------------------------ - - def test_assert_tag_and_url_for - get :render_url - assert_tag :content => "/action_pack_assertions/flash_me" - end - - # test the get method, make sure the request really was a get - def test_get - assert_raise(RuntimeError) { get :raise_on_get } - get :raise_on_post - assert_equal @response.body, 'request method: GET' - end - - # test the get method, make sure the request really was a get - def test_post - assert_raise(RuntimeError) { post :raise_on_post } - post :raise_on_get - assert_equal @response.body, 'request method: POST' - end - -# the following test fails because the request_method is now cached on the request instance -# test the get/post switch within one test action -# def test_get_post_switch -# post :raise_on_get -# assert_equal @response.body, 'request method: POST' -# get :raise_on_post -# assert_equal @response.body, 'request method: GET' -# post :raise_on_get -# assert_equal @response.body, 'request method: POST' -# get :raise_on_post -# assert_equal @response.body, 'request method: GET' -# end - - # test the redirection to a named route - def test_assert_redirect_to_named_route - with_routing do |set| - set.draw do |map| - match 'route_one', :to => 'action_pack_assertions#nothing', :as => :route_one - match ':controller/:action' - end - set.install_helpers - - process :redirect_to_named_route - assert_redirected_to 'http://test.host/route_one' - assert_redirected_to route_one_url - end - end - - def test_assert_redirect_to_named_route_failure - with_routing do |set| - set.draw do |map| - match 'route_one', :to => 'action_pack_assertions#nothing', :as => :route_one - match 'route_two', :to => 'action_pack_assertions#nothing', :id => 'two', :as => :route_two - match ':controller/:action' - end - process :redirect_to_named_route - assert_raise(ActiveSupport::TestCase::Assertion) do - assert_redirected_to 'http://test.host/route_two' - end - assert_raise(ActiveSupport::TestCase::Assertion) do - assert_redirected_to :controller => 'action_pack_assertions', :action => 'nothing', :id => 'two' - end - assert_raise(ActiveSupport::TestCase::Assertion) do - assert_redirected_to route_two_url - end - end - end - - def test_assert_redirect_to_nested_named_route - @controller = Admin::InnerModuleController.new - - with_routing do |set| - set.draw do |map| - match 'admin/inner_module', :to => 'admin/inner_module#index', :as => :admin_inner_module - # match ':controller/:action' - map.connect ':controller/:action/:id' - end - process :redirect_to_index - # redirection is <{"action"=>"index", "controller"=>"admin/admin/inner_module"}> - assert_redirected_to admin_inner_module_path - end - end - - def test_assert_redirected_to_top_level_named_route_from_nested_controller - @controller = Admin::InnerModuleController.new - - with_routing do |set| - set.draw do |map| - match '/action_pack_assertions/:id', :to => 'action_pack_assertions#index', :as => :top_level - # match ':controller/:action' - map.connect ':controller/:action/:id' - end - process :redirect_to_top_level_named_route - # assert_redirected_to "http://test.host/action_pack_assertions/foo" would pass because of exact match early return - assert_redirected_to "/action_pack_assertions/foo" - end - end - - def test_assert_redirected_to_top_level_named_route_with_same_controller_name_in_both_namespaces - @controller = Admin::InnerModuleController.new - - with_routing do |set| - set.draw do |map| - # this controller exists in the admin namespace as well which is the only difference from previous test - match '/user/:id', :to => 'user#index', :as => :top_level - # match ':controller/:action' - map.connect ':controller/:action/:id' - end - process :redirect_to_top_level_named_route - # assert_redirected_to top_level_url('foo') would pass because of exact match early return - assert_redirected_to top_level_path('foo') - end - end - - # -- standard request/response object testing -------------------------------- - - # make sure that the template objects exist - def test_template_objects_alive - process :assign_this - assert !@controller.instance_variable_get(:"@hi") - assert @controller.instance_variable_get(:"@howdy") - end - - # make sure we don't have template objects when we shouldn't - def test_template_object_missing - process :nothing - assert_nil @controller.instance_variable_get(:@howdy) - end - - # check the empty flashing - def test_flash_me_naked - process :flash_me_naked - assert_deprecated do - assert !@response.has_flash? - assert !@response.has_flash_with_contents? - end - end - - # check if we have flash objects - def test_flash_haves - process :flash_me - assert_deprecated do - assert @response.has_flash? - assert @response.has_flash_with_contents? - assert @response.has_flash_object?('hello') - end - end - - # ensure we don't have flash objects - def test_flash_have_nots - process :nothing - assert_deprecated do - assert !@response.has_flash? - assert !@response.has_flash_with_contents? - assert_nil @response.flash['hello'] - end - end - - - # check if we were rendered by a file-based template? - def test_rendered_action - process :nothing - assert_template nil - - process :hello_world - assert_template 'hello_world' - end - - # check the redirection location - def test_redirection_location - process :redirect_internal - assert_equal 'http://test.host/nothing', @response.redirect_url - - process :redirect_external - assert_equal 'http://www.rubyonrails.org', @response.redirect_url - end - - def test_no_redirect_url - process :nothing - assert_nil @response.redirect_url - end - - # check server errors - def test_server_error_response_code - process :response500 - assert @response.server_error? - - process :response599 - assert @response.server_error? - - process :response404 - assert !@response.server_error? - end - - # check a 404 response code - def test_missing_response_code - process :response404 - assert @response.missing? - end - - # check client errors - def test_client_error_response_code - process :response404 - assert @response.client_error? - end - - # check to see if our redirection matches a pattern - def test_redirect_url_match - process :redirect_external - assert @response.redirect? - assert_deprecated do - assert @response.redirect_url_match?("rubyonrails") - assert @response.redirect_url_match?(/rubyonrails/) - assert !@response.redirect_url_match?("phpoffrails") - assert !@response.redirect_url_match?(/perloffrails/) - end - end - - # check for a redirection - def test_redirection - process :redirect_internal - assert @response.redirect? - - process :redirect_external - assert @response.redirect? - - process :nothing - assert !@response.redirect? - end - - # check a successful response code - def test_successful_response_code - process :nothing - assert @response.success? - end - - # a basic check to make sure we have a TestResponse object - def test_has_response - process :nothing - assert_kind_of ActionController::TestResponse, @response - end - - def test_render_based_on_parameters - process :render_based_on_parameters, "name" => "David" - assert_equal "Mr. David", @response.body - end - - def test_assert_redirection_fails_with_incorrect_controller - process :redirect_to_controller - assert_raise(ActiveSupport::TestCase::Assertion) do - assert_redirected_to :controller => "action_pack_assertions", :action => "flash_me" - end - end - - def test_assert_redirection_with_extra_controller_option - get :redirect_to_action - assert_redirected_to :controller => 'action_pack_assertions', :action => "flash_me", :id => 1, :params => { :panda => 'fun' } - end - - def test_redirected_to_url_leading_slash - process :redirect_to_path - assert_redirected_to '/some/path' - end - - def test_redirected_to_url_no_leading_slash_fails - process :redirect_to_path - assert_raise ActiveSupport::TestCase::Assertion do - assert_redirected_to 'some/path' - end - end - - def test_redirected_to_url_full_url - process :redirect_to_path - assert_redirected_to 'http://test.host/some/path' - end - - def test_assert_redirection_with_symbol - process :redirect_to_controller_with_symbol - assert_nothing_raised { - assert_redirected_to :controller => "elsewhere", :action => "flash_me" - } - process :redirect_to_controller_with_symbol - assert_nothing_raised { - assert_redirected_to :controller => :elsewhere, :action => :flash_me - } - end - - def test_redirected_to_with_nested_controller - @controller = Admin::InnerModuleController.new - get :redirect_to_absolute_controller - assert_redirected_to :controller => '/content' - - get :redirect_to_fellow_controller - assert_redirected_to :controller => 'admin/user' - end - - def test_assert_response_uses_exception_message - @controller = AssertResponseWithUnexpectedErrorController.new - get :index - assert_response :success - flunk 'Expected non-success response' - rescue RuntimeError => e - assert e.message.include?('FAIL') - end - - def test_assert_response_failure_response_with_no_exception - @controller = AssertResponseWithUnexpectedErrorController.new - get :show - assert_response :success - flunk 'Expected non-success response' - rescue ActiveSupport::TestCase::Assertion - # success - rescue - flunk "assert_response failed to handle failure response with missing, but optional, exception." - end -end - -class AssertTemplateTest < ActionController::TestCase - tests ActionPackAssertionsController - - def test_with_partial - get :partial - assert_template :partial => '_partial' - end - - def test_with_nil_passes_when_no_template_rendered - get :nothing - assert_template nil - end - - def test_with_nil_fails_when_template_rendered - get :hello_world - assert_raise(ActiveSupport::TestCase::Assertion) do - assert_template nil - end - end - - def test_passes_with_correct_string - get :hello_world - assert_template 'hello_world' - assert_template 'test/hello_world' - end - - def test_passes_with_correct_symbol - get :hello_world - assert_template :hello_world - end - - def test_fails_with_incorrect_string - get :hello_world - assert_raise(ActiveSupport::TestCase::Assertion) do - assert_template 'hello_planet' - end - end - - def test_fails_with_incorrect_symbol - get :hello_world - assert_raise(ActiveSupport::TestCase::Assertion) do - assert_template :hello_planet - end - end -end - -class ActionPackHeaderTest < ActionController::TestCase - tests ActionPackAssertionsController - - def test_rendering_xml_sets_content_type - process :hello_xml_world - assert_equal('application/xml; charset=utf-8', @response.headers['Content-Type']) - end - - def test_rendering_xml_respects_content_type - process :hello_xml_world_pdf - assert_equal('application/pdf; charset=utf-8', @response.headers['Content-Type']) - end - - def test_rendering_xml_respects_content_type_when_set_in_the_header - process :hello_xml_world_pdf_header - assert_equal('application/pdf; charset=utf-8', @response.headers['Content-Type']) - end - - def test_render_text_with_custom_content_type - get :render_text_with_custom_content_type - assert_equal 'application/rss+xml; charset=utf-8', @response.headers['Content-Type'] - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/addresses_render_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/addresses_render_test.rb deleted file mode 100644 index 477b6aeb5..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/addresses_render_test.rb +++ /dev/null @@ -1,35 +0,0 @@ -require 'abstract_unit' -require 'logger' -require 'controller/fake_controllers' - -class Address - def Address.count(conditions = nil, join = nil) - nil - end - - def Address.find_all(arg1, arg2, arg3, arg4) - [] - end - - def self.find(*args) - [] - end -end - -class AddressesTest < ActionController::TestCase - tests AddressesController - - def setup - super - # enable a logger so that (e.g.) the benchmarking stuff runs, so we can get - # a more accurate simulation of what happens in "real life". - @controller.logger = Logger.new(nil) - - @request.host = "www.nextangle.com" - end - - def test_list - get :list - assert_equal "We only need to get this far!", @response.body.chomp - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/assert_select_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/assert_select_test.rb deleted file mode 100644 index 3ce4b3a41..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/assert_select_test.rb +++ /dev/null @@ -1,742 +0,0 @@ -# encoding: utf-8 -#-- -# Copyright (c) 2006 Assaf Arkin (http://labnotes.org) -# Under MIT and/or CC By license. -#++ - -require 'abstract_unit' -require 'controller/fake_controllers' - -require 'action_mailer' -ActionMailer::Base.view_paths = FIXTURE_LOAD_PATH - -class AssertSelectTest < ActionController::TestCase - Assertion = ActiveSupport::TestCase::Assertion - - class AssertSelectMailer < ActionMailer::Base - def test(html) - recipients "test " - from "test@test.host" - subject "Test e-mail" - part :content_type=>"text/html", :body=>html - end - end - - class AssertSelectController < ActionController::Base - def response_with=(content) - @content = content - end - - def response_with(&block) - @update = block - end - - def html() - render :text=>@content, :layout=>false, :content_type=>Mime::HTML - @content = nil - end - - def rjs() - render :update do |page| - @update.call page - end - @update = nil - end - - def xml() - render :text=>@content, :layout=>false, :content_type=>Mime::XML - @content = nil - end - - def rescue_action(e) - raise e - end - end - - tests AssertSelectController - - def setup - super - ActionMailer::Base.delivery_method = :test - ActionMailer::Base.perform_deliveries = true - ActionMailer::Base.deliveries = [] - end - - def teardown - super - ActionMailer::Base.deliveries.clear - end - - def assert_failure(message, &block) - e = assert_raise(Assertion, &block) - assert_match(message, e.message) if Regexp === message - assert_equal(message, e.message) if String === message - end - - # - # Test assert select. - # - - def test_assert_select - render_html %Q{
} - assert_select "div", 2 - assert_failure(/Expected at least 1 element matching \"p\", found 0/) { assert_select "p" } - end - - def test_equality_integer - render_html %Q{
} - assert_failure(/Expected exactly 3 elements matching \"div\", found 2/) { assert_select "div", 3 } - assert_failure(/Expected exactly 0 elements matching \"div\", found 2/) { assert_select "div", 0 } - end - - def test_equality_true_false - render_html %Q{
} - assert_nothing_raised { assert_select "div" } - assert_raise(Assertion) { assert_select "p" } - assert_nothing_raised { assert_select "div", true } - assert_raise(Assertion) { assert_select "p", true } - assert_raise(Assertion) { assert_select "div", false } - assert_nothing_raised { assert_select "p", false } - end - - def test_equality_false_message - render_html %Q{
} - assert_failure(/Expected exactly 0 elements matching \"div\", found 2/) { assert_select "div", false } - end - - def test_equality_string_and_regexp - render_html %Q{
foo
foo
} - assert_nothing_raised { assert_select "div", "foo" } - assert_raise(Assertion) { assert_select "div", "bar" } - assert_nothing_raised { assert_select "div", :text=>"foo" } - assert_raise(Assertion) { assert_select "div", :text=>"bar" } - assert_nothing_raised { assert_select "div", /(foo|bar)/ } - assert_raise(Assertion) { assert_select "div", /foobar/ } - assert_nothing_raised { assert_select "div", :text=>/(foo|bar)/ } - assert_raise(Assertion) { assert_select "div", :text=>/foobar/ } - assert_raise(Assertion) { assert_select "p", :text=>/foobar/ } - end - - def test_equality_of_html - render_html %Q{

\n"This is not a big problem," he said.\n

} - text = "\"This is not a big problem,\" he said." - html = "\"This is not a big problem,\" he said." - assert_nothing_raised { assert_select "p", text } - assert_raise(Assertion) { assert_select "p", html } - assert_nothing_raised { assert_select "p", :html=>html } - assert_raise(Assertion) { assert_select "p", :html=>text } - # No stripping for pre. - render_html %Q{
\n"This is not a big problem," he said.\n
} - text = "\n\"This is not a big problem,\" he said.\n" - html = "\n\"This is not a big problem,\" he said.\n" - assert_nothing_raised { assert_select "pre", text } - assert_raise(Assertion) { assert_select "pre", html } - assert_nothing_raised { assert_select "pre", :html=>html } - assert_raise(Assertion) { assert_select "pre", :html=>text } - end - - def test_counts - render_html %Q{
foo
foo
} - assert_nothing_raised { assert_select "div", 2 } - assert_failure(/Expected exactly 3 elements matching \"div\", found 2/) do - assert_select "div", 3 - end - assert_nothing_raised { assert_select "div", 1..2 } - assert_failure(/Expected between 3 and 4 elements matching \"div\", found 2/) do - assert_select "div", 3..4 - end - assert_nothing_raised { assert_select "div", :count=>2 } - assert_failure(/Expected exactly 3 elements matching \"div\", found 2/) do - assert_select "div", :count=>3 - end - assert_nothing_raised { assert_select "div", :minimum=>1 } - assert_nothing_raised { assert_select "div", :minimum=>2 } - assert_failure(/Expected at least 3 elements matching \"div\", found 2/) do - assert_select "div", :minimum=>3 - end - assert_nothing_raised { assert_select "div", :maximum=>2 } - assert_nothing_raised { assert_select "div", :maximum=>3 } - assert_failure(/Expected at most 1 element matching \"div\", found 2/) do - assert_select "div", :maximum=>1 - end - assert_nothing_raised { assert_select "div", :minimum=>1, :maximum=>2 } - assert_failure(/Expected between 3 and 4 elements matching \"div\", found 2/) do - assert_select "div", :minimum=>3, :maximum=>4 - end - end - - def test_substitution_values - render_html %Q{
foo
foo
} - assert_select "div#?", /\d+/ do |elements| - assert_equal 2, elements.size - end - assert_select "div" do - assert_select "div#?", /\d+/ do |elements| - assert_equal 2, elements.size - assert_select "#1" - assert_select "#2" - end - end - end - - def test_nested_assert_select - render_html %Q{
foo
foo
} - assert_select "div" do |elements| - assert_equal 2, elements.size - assert_select elements[0], "#1" - assert_select elements[1], "#2" - end - assert_select "div" do - assert_select "div" do |elements| - assert_equal 2, elements.size - # Testing in a group is one thing - assert_select "#1,#2" - # Testing individually is another. - assert_select "#1" - assert_select "#2" - assert_select "#3", false - end - end - - assert_failure(/Expected at least 1 element matching \"#4\", found 0\./) do - assert_select "div" do - assert_select "#4" - end - end - end - - def test_assert_select_text_match - render_html %Q{
foo
bar
} - assert_select "div" do - assert_nothing_raised { assert_select "div", "foo" } - assert_nothing_raised { assert_select "div", "bar" } - assert_nothing_raised { assert_select "div", /\w*/ } - assert_nothing_raised { assert_select "div", :text => /\w*/, :count=>2 } - assert_raise(Assertion) { assert_select "div", :text=>"foo", :count=>2 } - assert_nothing_raised { assert_select "div", :html=>"bar" } - assert_nothing_raised { assert_select "div", :html=>"bar" } - assert_nothing_raised { assert_select "div", :html=>/\w*/ } - assert_nothing_raised { assert_select "div", :html=>/\w*/, :count=>2 } - assert_raise(Assertion) { assert_select "div", :html=>"foo", :count=>2 } - end - end - - # With single result. - def test_assert_select_from_rjs_with_single_result - render_rjs do |page| - page.replace_html "test", "
foo
\n
foo
" - end - assert_select "div" do |elements| - assert elements.size == 2 - assert_select "#1" - assert_select "#2" - end - assert_select "div#?", /\d+/ do |elements| - assert_select "#1" - assert_select "#2" - end - end - - # With multiple results. - def test_assert_select_from_rjs_with_multiple_results - render_rjs do |page| - page.replace_html "test", "
foo
" - page.replace_html "test2", "
foo
" - end - assert_select "div" do |elements| - assert elements.size == 2 - assert_select "#1" - assert_select "#2" - end - end - - def test_assert_select_rjs_for_positioned_insert_should_fail_when_mixing_arguments - render_rjs do |page| - page.insert_html :top, "test1", "
foo
" - page.insert_html :bottom, "test2", "
foo
" - end - assert_raise(Assertion) {assert_select_rjs :insert, :top, "test2"} - end - - def test_assert_select_rjs_for_redirect_to - render_rjs do |page| - page.redirect_to '/' - end - assert_select_rjs :redirect, '/' - end - - def test_elect_with_xml_namespace_attributes - render_html %Q{} - assert_nothing_raised { assert_select "link[xlink:href=http://nowhere.com]" } - end - - # - # Test css_select. - # - - def test_css_select - render_html %Q{
} - assert_equal 2, css_select("div").size - assert_equal 0, css_select("p").size - end - - def test_nested_css_select - render_html %Q{
foo
foo
} - assert_select "div#?", /\d+/ do |elements| - assert_equal 1, css_select(elements[0], "div").size - assert_equal 1, css_select(elements[1], "div").size - end - assert_select "div" do - assert_equal 2, css_select("div").size - css_select("div").each do |element| - # Testing as a group is one thing - assert !css_select("#1,#2").empty? - # Testing individually is another - assert !css_select("#1").empty? - assert !css_select("#2").empty? - end - end - end - - # With one result. - def test_css_select_from_rjs_with_single_result - render_rjs do |page| - page.replace_html "test", "
foo
\n
foo
" - end - assert_equal 2, css_select("div").size - assert_equal 1, css_select("#1").size - assert_equal 1, css_select("#2").size - end - - # With multiple results. - def test_css_select_from_rjs_with_multiple_results - render_rjs do |page| - page.replace_html "test", "
foo
" - page.replace_html "test2", "
foo
" - end - - assert_equal 2, css_select("div").size - assert_equal 1, css_select("#1").size - assert_equal 1, css_select("#2").size - end - - # - # Test assert_select_rjs. - # - - # Test that we can pick up all statements in the result. - def test_assert_select_rjs_picks_up_all_statements - render_rjs do |page| - page.replace "test", "
foo
" - page.replace_html "test2", "
foo
" - page.insert_html :top, "test3", "
foo
" - end - - found = false - assert_select_rjs do - assert_select "#1" - assert_select "#2" - assert_select "#3" - found = true - end - assert found - end - - # Test that we fail if there is nothing to pick. - def test_assert_select_rjs_fails_if_nothing_to_pick - render_rjs { } - assert_raise(Assertion) { assert_select_rjs } - end - - def test_assert_select_rjs_with_unicode - # Test that non-ascii characters (which are converted into \uXXXX in RJS) are decoded correctly. - render_rjs do |page| - page.replace "test", "
\343\203\201\343\202\261\343\203\203\343\203\210
" - end - assert_select_rjs do - str = "#1" - assert_select str, :text => "\343\203\201\343\202\261\343\203\203\343\203\210" - assert_select str, "\343\203\201\343\202\261\343\203\203\343\203\210" - if str.respond_to?(:force_encoding) - assert_select str, /\343\203\201..\343\203\210/u - assert_raise(Assertion) { assert_select str, /\343\203\201.\343\203\210/u } - else - assert_select str, Regexp.new("\343\203\201..\343\203\210",0,'U') - assert_raise(Assertion) { assert_select str, Regexp.new("\343\203\201.\343\203\210",0,'U') } - end - end - end - - def test_assert_select_rjs_with_id - # Test that we can pick up all statements in the result. - render_rjs do |page| - page.replace "test1", "
foo
" - page.replace_html "test2", "
foo
" - page.insert_html :top, "test3", "
foo
" - end - assert_select_rjs "test1" do - assert_select "div", 1 - assert_select "#1" - end - assert_select_rjs "test2" do - assert_select "div", 1 - assert_select "#2" - end - assert_select_rjs "test3" do - assert_select "div", 1 - assert_select "#3" - end - assert_raise(Assertion) { assert_select_rjs "test4" } - end - - def test_assert_select_rjs_for_replace - render_rjs do |page| - page.replace "test1", "
foo
" - page.replace_html "test2", "
foo
" - page.insert_html :top, "test3", "
foo
" - end - # Replace. - assert_select_rjs :replace do - assert_select "div", 1 - assert_select "#1" - end - assert_select_rjs :replace, "test1" do - assert_select "div", 1 - assert_select "#1" - end - assert_raise(Assertion) { assert_select_rjs :replace, "test2" } - # Replace HTML. - assert_select_rjs :replace_html do - assert_select "div", 1 - assert_select "#2" - end - assert_select_rjs :replace_html, "test2" do - assert_select "div", 1 - assert_select "#2" - end - assert_raise(Assertion) { assert_select_rjs :replace_html, "test1" } - end - - def test_assert_select_rjs_for_chained_replace - render_rjs do |page| - page['test1'].replace "
foo
" - page['test2'].replace_html "
foo
" - page.insert_html :top, "test3", "
foo
" - end - # Replace. - assert_select_rjs :chained_replace do - assert_select "div", 1 - assert_select "#1" - end - assert_select_rjs :chained_replace, "test1" do - assert_select "div", 1 - assert_select "#1" - end - assert_raise(Assertion) { assert_select_rjs :chained_replace, "test2" } - # Replace HTML. - assert_select_rjs :chained_replace_html do - assert_select "div", 1 - assert_select "#2" - end - assert_select_rjs :chained_replace_html, "test2" do - assert_select "div", 1 - assert_select "#2" - end - assert_raise(Assertion) { assert_select_rjs :replace_html, "test1" } - end - - # Simple remove - def test_assert_select_rjs_for_remove - render_rjs do |page| - page.remove "test1" - end - - assert_select_rjs :remove, "test1" - end - - def test_assert_select_rjs_for_remove_offers_useful_error_when_assertion_fails - render_rjs do |page| - page.remove "test_with_typo" - end - - assert_select_rjs :remove, "test1" - - rescue Assertion - assert_equal "No RJS statement that removes 'test1' was rendered.", $!.message - end - - def test_assert_select_rjs_for_remove_ignores_block - render_rjs do |page| - page.remove "test1" - end - - assert_nothing_raised do - assert_select_rjs :remove, "test1" do - assert_select "p" - end - end - end - - # Simple show - def test_assert_select_rjs_for_show - render_rjs do |page| - page.show "test1" - end - - assert_select_rjs :show, "test1" - end - - def test_assert_select_rjs_for_show_offers_useful_error_when_assertion_fails - render_rjs do |page| - page.show "test_with_typo" - end - - assert_select_rjs :show, "test1" - - rescue Assertion - assert_equal "No RJS statement that shows 'test1' was rendered.", $!.message - end - - def test_assert_select_rjs_for_show_ignores_block - render_rjs do |page| - page.show "test1" - end - - assert_nothing_raised do - assert_select_rjs :show, "test1" do - assert_select "p" - end - end - end - - # Simple hide - def test_assert_select_rjs_for_hide - render_rjs do |page| - page.hide "test1" - end - - assert_select_rjs :hide, "test1" - end - - def test_assert_select_rjs_for_hide_offers_useful_error_when_assertion_fails - render_rjs do |page| - page.hide "test_with_typo" - end - - assert_select_rjs :hide, "test1" - - rescue Assertion - assert_equal "No RJS statement that hides 'test1' was rendered.", $!.message - end - - def test_assert_select_rjs_for_hide_ignores_block - render_rjs do |page| - page.hide "test1" - end - - assert_nothing_raised do - assert_select_rjs :hide, "test1" do - assert_select "p" - end - end - end - - # Simple toggle - def test_assert_select_rjs_for_toggle - render_rjs do |page| - page.toggle "test1" - end - - assert_select_rjs :toggle, "test1" - end - - def test_assert_select_rjs_for_toggle_offers_useful_error_when_assertion_fails - render_rjs do |page| - page.toggle "test_with_typo" - end - - assert_select_rjs :toggle, "test1" - - rescue Assertion - assert_equal "No RJS statement that toggles 'test1' was rendered.", $!.message - end - - def test_assert_select_rjs_for_toggle_ignores_block - render_rjs do |page| - page.toggle "test1" - end - - assert_nothing_raised do - assert_select_rjs :toggle, "test1" do - assert_select "p" - end - end - end - - # Non-positioned insert. - def test_assert_select_rjs_for_nonpositioned_insert - render_rjs do |page| - page.replace "test1", "
foo
" - page.replace_html "test2", "
foo
" - page.insert_html :top, "test3", "
foo
" - end - assert_select_rjs :insert_html do - assert_select "div", 1 - assert_select "#3" - end - assert_select_rjs :insert_html, "test3" do - assert_select "div", 1 - assert_select "#3" - end - assert_raise(Assertion) { assert_select_rjs :insert_html, "test1" } - end - - # Positioned insert. - def test_assert_select_rjs_for_positioned_insert - render_rjs do |page| - page.insert_html :top, "test1", "
foo
" - page.insert_html :bottom, "test2", "
foo
" - page.insert_html :before, "test3", "
foo
" - page.insert_html :after, "test4", "
foo
" - end - assert_select_rjs :insert, :top do - assert_select "div", 1 - assert_select "#1" - end - assert_select_rjs :insert, :bottom do - assert_select "div", 1 - assert_select "#2" - end - assert_select_rjs :insert, :before do - assert_select "div", 1 - assert_select "#3" - end - assert_select_rjs :insert, :after do - assert_select "div", 1 - assert_select "#4" - end - assert_select_rjs :insert_html do - assert_select "div", 4 - end - end - - def test_assert_select_rjs_raise_errors - assert_raise(ArgumentError) { assert_select_rjs(:destroy) } - assert_raise(ArgumentError) { assert_select_rjs(:insert, :left) } - end - - # Simple selection from a single result. - def test_nested_assert_select_rjs_with_single_result - render_rjs do |page| - page.replace_html "test", "
foo
\n
foo
" - end - - assert_select_rjs "test" do |elements| - assert_equal 2, elements.size - assert_select "#1" - assert_select "#2" - end - end - - # Deal with two results. - def test_nested_assert_select_rjs_with_two_results - render_rjs do |page| - page.replace_html "test", "
foo
" - page.replace_html "test2", "
foo
" - end - - assert_select_rjs "test" do |elements| - assert_equal 1, elements.size - assert_select "#1" - end - - assert_select_rjs "test2" do |elements| - assert_equal 1, elements.size - assert_select "#2" - end - end - - def test_feed_item_encoded - render_xml <<-EOF - - - - - Test 1

- ]]> -
-
- - - Test 2

- ]]> -
-
-
-
-EOF - assert_select "channel item description" do - # Test element regardless of wrapper. - assert_select_encoded do - assert_select "p", :count=>2, :text=>/Test/ - end - # Test through encoded wrapper. - assert_select_encoded do - assert_select "encoded p", :count=>2, :text=>/Test/ - end - # Use :root instead (recommended) - assert_select_encoded do - assert_select ":root p", :count=>2, :text=>/Test/ - end - # Test individually. - assert_select "description" do |elements| - assert_select_encoded elements[0] do - assert_select "p", "Test 1" - end - assert_select_encoded elements[1] do - assert_select "p", "Test 2" - end - end - end - - # Test that we only un-encode element itself. - assert_select "channel item" do - assert_select_encoded do - assert_select "p", 0 - end - end - end - - # - # Test assert_select_email - # - - def test_assert_select_email - assert_raise(Assertion) { assert_select_email {} } - AssertSelectMailer.test("

foo

bar

").deliver - assert_select_email do - assert_select "div:root" do - assert_select "p:first-child", "foo" - assert_select "p:last-child", "bar" - end - end - end - - protected - def render_html(html) - @controller.response_with = html - get :html - end - - def render_rjs(&block) - @controller.response_with &block - get :rjs - end - - def render_xml(xml) - @controller.response_with = xml - get :xml - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/base_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/base_test.rb deleted file mode 100644 index 4ee3a483e..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/base_test.rb +++ /dev/null @@ -1,318 +0,0 @@ -require 'abstract_unit' -require 'logger' -require 'pp' # require 'pp' early to prevent hidden_methods from not picking up the pretty-print methods until too late - -# Provide some controller to run the tests on. -module Submodule - class ContainedEmptyController < ActionController::Base - end - - class ContainedNonEmptyController < ActionController::Base - def public_action - render :nothing => true - end - - hide_action :hidden_action - def hidden_action - raise "Noooo!" - end - - def another_hidden_action - end - hide_action :another_hidden_action - end - - class SubclassedController < ContainedNonEmptyController - hide_action :public_action # Hiding it here should not affect the superclass. - end -end - -class EmptyController < ActionController::Base -end - -class NonEmptyController < ActionController::Base - def public_action - render :nothing => true - end - - hide_action :hidden_action - def hidden_action - end -end - -class MethodMissingController < ActionController::Base - hide_action :shouldnt_be_called - def shouldnt_be_called - raise "NO WAY!" - end - -protected - - def method_missing(selector) - render :text => selector.to_s - end -end - -class AnotherMethodMissingController < ActionController::Base - cattr_accessor :_exception - rescue_from Exception, :with => :_exception= - - protected - def method_missing(*attrs, &block) - super - end -end - -class DefaultUrlOptionsController < ActionController::Base - def from_view - render :inline => "<%= #{params[:route]} %>" - end - - def default_url_options(options = nil) - { :host => 'www.override.com', :action => 'new', :locale => 'en' } - end -end - -class UrlOptionsController < ActionController::Base - def from_view - render :inline => "<%= #{params[:route]} %>" - end - - def url_options - super.merge(:host => 'www.override.com', :action => 'new', :locale => 'en') - end -end - -class RecordIdentifierController < ActionController::Base -end - -class ControllerClassTests < ActiveSupport::TestCase - - def test_controller_path - assert_equal 'empty', EmptyController.controller_path - assert_equal EmptyController.controller_path, EmptyController.new.controller_path - assert_equal 'submodule/contained_empty', Submodule::ContainedEmptyController.controller_path - assert_equal Submodule::ContainedEmptyController.controller_path, Submodule::ContainedEmptyController.new.controller_path - end - - def test_controller_name - assert_equal 'empty', EmptyController.controller_name - assert_equal 'contained_empty', Submodule::ContainedEmptyController.controller_name - end - - def test_filter_parameter_logging - parameters = [] - config = mock(:config => mock(:filter_parameters => parameters)) - Rails.expects(:application).returns(config) - - assert_deprecated do - Class.new(ActionController::Base) do - filter_parameter_logging :password - end - end - - assert_equal [:password], parameters - end - - def test_record_identifier - assert_respond_to RecordIdentifierController.new, :dom_id - assert_respond_to RecordIdentifierController.new, :dom_class - end -end - -class ControllerInstanceTests < Test::Unit::TestCase - def setup - @empty = EmptyController.new - @contained = Submodule::ContainedEmptyController.new - @empty_controllers = [@empty, @contained, Submodule::SubclassedController.new] - - @non_empty_controllers = [NonEmptyController.new, - Submodule::ContainedNonEmptyController.new] - end - - def test_action_methods - @empty_controllers.each do |c| - assert_equal Set.new, c.class.action_methods, "#{c.controller_path} should be empty!" - end - - @non_empty_controllers.each do |c| - assert_equal Set.new(%w(public_action)), c.class.action_methods, "#{c.controller_path} should not be empty!" - end - end - - def test_temporary_anonymous_controllers - name = 'ExamplesController' - klass = Class.new(ActionController::Base) - Object.const_set(name, klass) - - controller = klass.new - assert_equal "examples", controller.controller_path - end -end - -class PerformActionTest < ActionController::TestCase - def use_controller(controller_class) - @controller = controller_class.new - - # enable a logger so that (e.g.) the benchmarking stuff runs, so we can get - # a more accurate simulation of what happens in "real life". - @controller.logger = Logger.new(nil) - - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new - @request.host = "www.nextangle.com" - - rescue_action_in_public! - end - - def test_process_should_be_precise - use_controller EmptyController - exception = assert_raise AbstractController::ActionNotFound do - get :non_existent - end - assert_equal exception.message, "The action 'non_existent' could not be found for EmptyController" - end - - def test_get_on_priv_should_show_selector - use_controller MethodMissingController - get :shouldnt_be_called - assert_response :success - assert_equal 'shouldnt_be_called', @response.body - end - - def test_method_missing_is_not_an_action_name - use_controller MethodMissingController - assert !@controller.__send__(:action_method?, 'method_missing') - - get :method_missing - assert_response :success - assert_equal 'method_missing', @response.body - end - - def test_method_missing_should_recieve_symbol - use_controller AnotherMethodMissingController - get :some_action - assert_kind_of NameError, @controller._exception - end - - def test_get_on_hidden_should_fail - use_controller NonEmptyController - assert_raise(ActionController::UnknownAction) { get :hidden_action } - assert_raise(ActionController::UnknownAction) { get :another_hidden_action } - end -end - -class UrlOptionsTest < ActionController::TestCase - tests UrlOptionsController - - def setup - super - @request.host = 'www.example.com' - rescue_action_in_public! - end - - def test_url_options_override - with_routing do |set| - set.draw do - match 'from_view', :to => 'url_options#from_view', :as => :from_view - match ':controller/:action' - end - - get :from_view, :route => "from_view_url" - - assert_equal 'http://www.override.com/from_view?locale=en', @response.body - assert_equal 'http://www.override.com/from_view?locale=en', @controller.send(:from_view_url) - assert_equal 'http://www.override.com/default_url_options/new?locale=en', @controller.url_for(:controller => 'default_url_options') - end - end - - def test_url_helpers_does_not_become_actions - with_routing do |set| - set.draw do - match "account/overview" - end - - @controller.class.send(:include, set.url_helpers) - assert !@controller.class.action_methods.include?("account_overview_path") - end - end -end - -class DefaultUrlOptionsTest < ActionController::TestCase - tests DefaultUrlOptionsController - - def setup - super - @request.host = 'www.example.com' - rescue_action_in_public! - end - - def test_default_url_options_override - with_routing do |set| - set.draw do - match 'from_view', :to => 'default_url_options#from_view', :as => :from_view - match ':controller/:action' - end - - get :from_view, :route => "from_view_url" - - assert_equal 'http://www.override.com/from_view?locale=en', @response.body - assert_equal 'http://www.override.com/from_view?locale=en', @controller.send(:from_view_url) - assert_equal 'http://www.override.com/default_url_options/new?locale=en', @controller.url_for(:controller => 'default_url_options') - end - end - - def test_default_url_options_are_used_in_non_positional_parameters - with_routing do |set| - set.draw do - scope("/:locale") do - resources :descriptions - end - match ':controller/:action' - end - - get :from_view, :route => "description_path(1)" - - assert_equal '/en/descriptions/1', @response.body - assert_equal '/en/descriptions', @controller.send(:descriptions_path) - assert_equal '/pl/descriptions', @controller.send(:descriptions_path, "pl") - assert_equal '/pl/descriptions', @controller.send(:descriptions_path, :locale => "pl") - assert_equal '/pl/descriptions.xml', @controller.send(:descriptions_path, "pl", "xml") - assert_equal '/en/descriptions.xml', @controller.send(:descriptions_path, :format => "xml") - assert_equal '/en/descriptions/1', @controller.send(:description_path, 1) - assert_equal '/pl/descriptions/1', @controller.send(:description_path, "pl", 1) - assert_equal '/pl/descriptions/1', @controller.send(:description_path, 1, :locale => "pl") - assert_equal '/pl/descriptions/1.xml', @controller.send(:description_path, "pl", 1, "xml") - assert_equal '/en/descriptions/1.xml', @controller.send(:description_path, 1, :format => "xml") - end - end - -end - -class EmptyUrlOptionsTest < ActionController::TestCase - tests NonEmptyController - - def setup - super - @request.host = 'www.example.com' - rescue_action_in_public! - end - - def test_ensure_url_for_works_as_expected_when_called_with_no_options_if_default_url_options_is_not_set - get :public_action - assert_equal "http://www.example.com/non_empty/public_action", @controller.url_for - end - - def test_named_routes_with_path_without_doing_a_request_first - @controller = EmptyController.new - @controller.request = @request - - with_routing do |set| - set.draw do |map| - resources :things - end - - assert_equal '/things', @controller.send(:things_path) - end - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/caching_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/caching_test.rb deleted file mode 100644 index 1ef425e02..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/caching_test.rb +++ /dev/null @@ -1,768 +0,0 @@ -require 'fileutils' -require 'abstract_unit' -require 'active_record_unit' - -CACHE_DIR = 'test_cache' -# Don't change '/../temp/' cavalierly or you might hose something you don't want hosed -FILE_STORE_PATH = File.join(File.dirname(__FILE__), '/../temp/', CACHE_DIR) -ActionController::Base.page_cache_directory = FILE_STORE_PATH - -class CachingController < ActionController::Base - abstract! - - self.cache_store = :file_store, FILE_STORE_PATH -end - -class PageCachingTestController < CachingController - caches_page :ok, :no_content, :if => Proc.new { |c| !c.request.format.json? } - caches_page :found, :not_found - - - def ok - head :ok - end - - def no_content - head :no_content - end - - def found - redirect_to :action => 'ok' - end - - def not_found - head :not_found - end - - def custom_path - render :text => "Super soaker" - cache_page("Super soaker", "/index.html") - end - - def expire_custom_path - expire_page("/index.html") - head :ok - end - - def trailing_slash - render :text => "Sneak attack" - end -end - -class PageCachingTest < ActionController::TestCase - def setup - super - - @request = ActionController::TestRequest.new - @request.host = 'hostname.com' - @request.env.delete('PATH_INFO') - - @controller = PageCachingTestController.new - @controller.perform_caching = true - @controller.cache_store = :file_store, FILE_STORE_PATH - - @response = ActionController::TestResponse.new - - @params = {:controller => 'posts', :action => 'index', :only_path => true} - - FileUtils.rm_rf(File.dirname(FILE_STORE_PATH)) - FileUtils.mkdir_p(FILE_STORE_PATH) - end - - def teardown - FileUtils.rm_rf(File.dirname(FILE_STORE_PATH)) - @controller.perform_caching = false - end - - def test_page_caching_resources_saves_to_correct_path_with_extension_even_if_default_route - with_routing do |set| - set.draw do |map| - match 'posts.:format', :to => 'posts#index', :as => :formatted_posts - match '/', :to => 'posts#index', :as => :main - end - @params[:format] = 'rss' - assert_equal '/posts.rss', @routes.url_for(@params) - @params[:format] = nil - assert_equal '/', @routes.url_for(@params) - end - end - - def test_should_cache_get_with_ok_status - get :ok - assert_response :ok - assert_page_cached :ok, "get with ok status should have been cached" - end - - def test_should_cache_with_custom_path - get :custom_path - assert File.exist?("#{FILE_STORE_PATH}/index.html") - end - - def test_should_expire_cache_with_custom_path - get :custom_path - assert File.exist?("#{FILE_STORE_PATH}/index.html") - - get :expire_custom_path - assert !File.exist?("#{FILE_STORE_PATH}/index.html") - end - - def test_should_cache_without_trailing_slash_on_url - @controller.class.cache_page 'cached content', '/page_caching_test/trailing_slash' - assert File.exist?("#{FILE_STORE_PATH}/page_caching_test/trailing_slash.html") - end - - def test_should_cache_with_trailing_slash_on_url - @controller.class.cache_page 'cached content', '/page_caching_test/trailing_slash/' - assert File.exist?("#{FILE_STORE_PATH}/page_caching_test/trailing_slash.html") - end - - def test_should_cache_ok_at_custom_path - @request.env['PATH_INFO'] = '/index.html' - get :ok - assert_response :ok - assert File.exist?("#{FILE_STORE_PATH}/index.html") - end - - [:ok, :no_content, :found, :not_found].each do |status| - [:get, :post, :put, :delete].each do |method| - unless method == :get and status == :ok - define_method "test_shouldnt_cache_#{method}_with_#{status}_status" do - send(method, status) - assert_response status - assert_page_not_cached status, "#{method} with #{status} status shouldn't have been cached" - end - end - end - end - - def test_page_caching_conditional_options - get :ok, :format=>'json' - assert_page_not_cached :ok - end - - private - def assert_page_cached(action, message = "#{action} should have been cached") - assert page_cached?(action), message - end - - def assert_page_not_cached(action, message = "#{action} shouldn't have been cached") - assert !page_cached?(action), message - end - - def page_cached?(action) - File.exist? "#{FILE_STORE_PATH}/page_caching_test/#{action}.html" - end -end - -class ActionCachingTestController < CachingController - rescue_from(Exception) { head 500 } - if defined? ActiveRecord - rescue_from(ActiveRecord::RecordNotFound) { head :not_found } - end - - caches_action :index, :redirected, :forbidden, :if => Proc.new { |c| !c.request.format.json? }, :expires_in => 1.hour - caches_action :show, :cache_path => 'http://test.host/custom/show' - caches_action :edit, :cache_path => Proc.new { |c| c.params[:id] ? "http://test.host/#{c.params[:id]};edit" : "http://test.host/edit" } - caches_action :with_layout - caches_action :layout_false, :layout => false - caches_action :record_not_found, :four_oh_four, :simple_runtime_error - - layout 'talk_from_action.erb' - - def index - @cache_this = MockTime.now.to_f.to_s - render :text => @cache_this - end - - def redirected - redirect_to :action => 'index' - end - - def forbidden - render :text => "Forbidden" - response.status = "403 Forbidden" - end - - def with_layout - @cache_this = MockTime.now.to_f.to_s - render :text => @cache_this, :layout => true - end - - def record_not_found - raise ActiveRecord::RecordNotFound, "oops!" - end - - def four_oh_four - render :text => "404'd!", :status => 404 - end - - def simple_runtime_error - raise "oops!" - end - - alias_method :show, :index - alias_method :edit, :index - alias_method :destroy, :index - alias_method :layout_false, :with_layout - - def expire - expire_action :controller => 'action_caching_test', :action => 'index' - render :nothing => true - end - - def expire_xml - expire_action :controller => 'action_caching_test', :action => 'index', :format => 'xml' - render :nothing => true - end -end - -class MockTime < Time - # Let Time spicy to assure that Time.now != Time.now - def to_f - super+rand - end -end - -class ActionCachingMockController - attr_accessor :mock_url_for - attr_accessor :mock_path - - def initialize - yield self if block_given? - end - - def url_for(*args) - @mock_url_for - end - - def params - request.parameters - end - - def request - mocked_path = @mock_path - Object.new.instance_eval(<<-EVAL) - def path; '#{@mock_path}' end - def format; 'all' end - def parameters; {:format => nil}; end - self - EVAL - end -end - -class ActionCacheTest < ActionController::TestCase - def setup - super - reset! - FileUtils.mkdir_p(FILE_STORE_PATH) - @path_class = ActionController::Caching::Actions::ActionCachePath - @mock_controller = ActionCachingMockController.new - end - - def teardown - FileUtils.rm_rf(File.dirname(FILE_STORE_PATH)) - end - - def test_simple_action_cache - get :index - assert_response :success - cached_time = content_to_cache - assert_equal cached_time, @response.body - assert fragment_exist?('hostname.com/action_caching_test') - reset! - - get :index - assert_response :success - assert_equal cached_time, @response.body - end - - def test_simple_action_not_cached - get :destroy - assert_response :success - cached_time = content_to_cache - assert_equal cached_time, @response.body - assert !fragment_exist?('hostname.com/action_caching_test/destroy') - reset! - - get :destroy - assert_response :success - assert_not_equal cached_time, @response.body - end - - include RackTestUtils - - def test_action_cache_with_layout - get :with_layout - assert_response :success - cached_time = content_to_cache - assert_not_equal cached_time, @response.body - assert fragment_exist?('hostname.com/action_caching_test/with_layout') - reset! - - get :with_layout - assert_response :success - assert_not_equal cached_time, @response.body - body = body_to_string(read_fragment('hostname.com/action_caching_test/with_layout')) - assert_equal @response.body, body - end - - def test_action_cache_with_layout_and_layout_cache_false - get :layout_false - assert_response :success - cached_time = content_to_cache - assert_not_equal cached_time, @response.body - assert fragment_exist?('hostname.com/action_caching_test/layout_false') - reset! - - get :layout_false - assert_response :success - assert_not_equal cached_time, @response.body - - body = body_to_string(read_fragment('hostname.com/action_caching_test/layout_false')) - assert_equal cached_time, body - end - - def test_action_cache_conditional_options - @request.env['HTTP_ACCEPT'] = 'application/json' - get :index - assert_response :success - assert !fragment_exist?('hostname.com/action_caching_test') - end - - def test_action_cache_with_store_options - MockTime.expects(:now).returns(12345).once - @controller.expects(:read_fragment).with('hostname.com/action_caching_test', :expires_in => 1.hour).once - @controller.expects(:write_fragment).with('hostname.com/action_caching_test', '12345.0', :expires_in => 1.hour).once - get :index - assert_response :success - end - - def test_action_cache_with_custom_cache_path - get :show - assert_response :success - cached_time = content_to_cache - assert_equal cached_time, @response.body - assert fragment_exist?('test.host/custom/show') - reset! - - get :show - assert_response :success - assert_equal cached_time, @response.body - end - - def test_action_cache_with_custom_cache_path_in_block - get :edit - assert_response :success - assert fragment_exist?('test.host/edit') - reset! - - get :edit, :id => 1 - assert_response :success - assert fragment_exist?('test.host/1;edit') - end - - def test_cache_expiration - get :index - assert_response :success - cached_time = content_to_cache - reset! - - get :index - assert_response :success - assert_equal cached_time, @response.body - reset! - - get :expire - assert_response :success - reset! - - get :index - assert_response :success - new_cached_time = content_to_cache - assert_not_equal cached_time, @response.body - reset! - - get :index - assert_response :success - assert_equal new_cached_time, @response.body - end - - def test_cache_expiration_isnt_affected_by_request_format - get :index - cached_time = content_to_cache - reset! - - @request.request_uri = "/action_caching_test/expire.xml" - get :expire, :format => :xml - assert_response :success - reset! - - get :index - assert_response :success - new_cached_time = content_to_cache - assert_not_equal cached_time, @response.body - end - - def test_cache_is_scoped_by_subdomain - @request.host = 'jamis.hostname.com' - get :index - assert_response :success - jamis_cache = content_to_cache - - reset! - - @request.host = 'david.hostname.com' - get :index - assert_response :success - david_cache = content_to_cache - assert_not_equal jamis_cache, @response.body - - reset! - - @request.host = 'jamis.hostname.com' - get :index - assert_response :success - assert_equal jamis_cache, @response.body - - reset! - - @request.host = 'david.hostname.com' - get :index - assert_response :success - assert_equal david_cache, @response.body - end - - def test_redirect_is_not_cached - get :redirected - assert_response :redirect - reset! - - get :redirected - assert_response :redirect - end - - def test_forbidden_is_not_cached - get :forbidden - assert_response :forbidden - reset! - - get :forbidden - assert_response :forbidden - end - - def test_xml_version_of_resource_is_treated_as_different_cache - with_routing do |set| - set.draw do |map| - match ':controller(/:action(.:format))' - end - - get :index, :format => 'xml' - assert_response :success - cached_time = content_to_cache - assert_equal cached_time, @response.body - assert fragment_exist?('hostname.com/action_caching_test/index.xml') - reset! - - get :index, :format => 'xml' - assert_response :success - assert_equal cached_time, @response.body - assert_equal 'application/xml', @response.content_type - reset! - - get :expire_xml - assert_response :success - reset! - - get :index, :format => 'xml' - assert_response :success - assert_not_equal cached_time, @response.body - end - end - - def test_correct_content_type_is_returned_for_cache_hit - # run it twice to cache it the first time - get :index, :id => 'content-type', :format => 'xml' - get :index, :id => 'content-type', :format => 'xml' - assert_response :success - assert_equal 'application/xml', @response.content_type - end - - def test_correct_content_type_is_returned_for_cache_hit_on_action_with_string_key - # run it twice to cache it the first time - get :show, :format => 'xml' - get :show, :format => 'xml' - assert_response :success - assert_equal 'application/xml', @response.content_type - end - - def test_correct_content_type_is_returned_for_cache_hit_on_action_with_string_key_from_proc - # run it twice to cache it the first time - get :edit, :id => 1, :format => 'xml' - get :edit, :id => 1, :format => 'xml' - assert_response :success - assert_equal 'application/xml', @response.content_type - end - - def test_empty_path_is_normalized - @mock_controller.mock_url_for = 'http://example.org/' - @mock_controller.mock_path = '/' - - assert_equal 'example.org/index', @path_class.new(@mock_controller, {}).path - end - - def test_file_extensions - get :index, :id => 'kitten.jpg' - get :index, :id => 'kitten.jpg' - - assert_response :success - end - - if defined? ActiveRecord - def test_record_not_found_returns_404_for_multiple_requests - get :record_not_found - assert_response 404 - get :record_not_found - assert_response 404 - end - end - - def test_four_oh_four_returns_404_for_multiple_requests - get :four_oh_four - assert_response 404 - get :four_oh_four - assert_response 404 - end - - def test_simple_runtime_error_returns_500_for_multiple_requests - get :simple_runtime_error - assert_response 500 - get :simple_runtime_error - assert_response 500 - end - - private - def content_to_cache - assigns(:cache_this) - end - - def reset! - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new - @controller = ActionCachingTestController.new - @controller.singleton_class.send(:include, @routes.url_helpers) - @request.host = 'hostname.com' - end - - def fragment_exist?(path) - @controller.fragment_exist?(path) - end - - def read_fragment(path) - @controller.read_fragment(path) - end -end - -class FragmentCachingTestController < CachingController - def some_action; end; -end - -class FragmentCachingTest < ActionController::TestCase - def setup - super - @store = ActiveSupport::Cache::MemoryStore.new - @controller = FragmentCachingTestController.new - @controller.perform_caching = true - @controller.cache_store = @store - @params = {:controller => 'posts', :action => 'index'} - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new - @controller.params = @params - @controller.request = @request - @controller.response = @response - @controller.send(:initialize_template_class, @response) - @controller.send(:assign_shortcuts, @request, @response) - end - - def test_fragment_cache_key - assert_equal 'views/what a key', @controller.fragment_cache_key('what a key') - assert_equal "views/test.host/fragment_caching_test/some_action", - @controller.fragment_cache_key(:controller => 'fragment_caching_test',:action => 'some_action') - end - - def test_read_fragment_with_caching_enabled - @store.write('views/name', 'value') - assert_equal 'value', @controller.read_fragment('name') - end - - def test_read_fragment_with_caching_disabled - @controller.perform_caching = false - @store.write('views/name', 'value') - assert_nil @controller.read_fragment('name') - end - - def test_fragment_exist_with_caching_enabled - @store.write('views/name', 'value') - assert @controller.fragment_exist?('name') - assert !@controller.fragment_exist?('other_name') - end - - def test_fragment_exist_with_caching_disabled - @controller.perform_caching = false - @store.write('views/name', 'value') - assert !@controller.fragment_exist?('name') - assert !@controller.fragment_exist?('other_name') - end - - def test_write_fragment_with_caching_enabled - assert_nil @store.read('views/name') - assert_equal 'value', @controller.write_fragment('name', 'value') - assert_equal 'value', @store.read('views/name') - end - - def test_write_fragment_with_caching_disabled - assert_nil @store.read('views/name') - @controller.perform_caching = false - assert_equal 'value', @controller.write_fragment('name', 'value') - assert_nil @store.read('views/name') - end - - def test_expire_fragment_with_simple_key - @store.write('views/name', 'value') - @controller.expire_fragment 'name' - assert_nil @store.read('views/name') - end - - def test_expire_fragment_with_regexp - @store.write('views/name', 'value') - @store.write('views/another_name', 'another_value') - @store.write('views/primalgrasp', 'will not expire ;-)') - - @controller.expire_fragment /name/ - - assert_nil @store.read('views/name') - assert_nil @store.read('views/another_name') - assert_equal 'will not expire ;-)', @store.read('views/primalgrasp') - end - - def test_fragment_for - @store.write('views/expensive', 'fragment content') - fragment_computed = false - - view_context = @controller.view_context - - buffer = 'generated till now -> '.html_safe - buffer << view_context.send(:fragment_for, 'expensive') { fragment_computed = true } - - assert !fragment_computed - assert_equal 'generated till now -> fragment content', buffer - end - - def test_html_safety - assert_nil @store.read('views/name') - content = 'value'.html_safe - assert_equal content, @controller.write_fragment('name', content) - - cached = @store.read('views/name') - assert_equal content, cached - assert_equal String, cached.class - - html_safe = @controller.read_fragment('name') - assert_equal content, html_safe - assert html_safe.html_safe? - end -end - -class FunctionalCachingController < CachingController - def fragment_cached - end - - def html_fragment_cached_with_partial - respond_to do |format| - format.html - end - end - - def js_fragment_cached_with_partial - respond_to do |format| - format.js - end - end - - def formatted_fragment_cached - respond_to do |format| - format.html - format.xml - format.js - end - end - - def rescue_action(e) - raise e - end -end - -class FunctionalFragmentCachingTest < ActionController::TestCase - def setup - super - @store = ActiveSupport::Cache::MemoryStore.new - @controller = FunctionalCachingController.new - @controller.perform_caching = true - @controller.cache_store = @store - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new - end - - def test_fragment_caching - get :fragment_cached - assert_response :success - expected_body = <<-CACHED -Hello -This bit's fragment cached -CACHED - assert_equal expected_body, @response.body - - assert_equal "This bit's fragment cached", @store.read('views/test.host/functional_caching/fragment_cached') - end - - def test_fragment_caching_in_partials - get :html_fragment_cached_with_partial - assert_response :success - assert_match /Old fragment caching in a partial/, @response.body - assert_match "Old fragment caching in a partial", @store.read('views/test.host/functional_caching/html_fragment_cached_with_partial') - end - - def test_render_inline_before_fragment_caching - get :inline_fragment_cached - assert_response :success - assert_match /Some inline content/, @response.body - assert_match /Some cached content/, @response.body - assert_match "Some cached content", @store.read('views/test.host/functional_caching/inline_fragment_cached') - end - - def test_fragment_caching_in_rjs_partials - xhr :get, :js_fragment_cached_with_partial - assert_response :success - assert_match /Old fragment caching in a partial/, @response.body - assert_match "Old fragment caching in a partial", @store.read('views/test.host/functional_caching/js_fragment_cached_with_partial') - end - - def test_html_formatted_fragment_caching - get :formatted_fragment_cached, :format => "html" - assert_response :success - expected_body = "\n

ERB

\n\n" - - assert_equal expected_body, @response.body - - assert_equal "

ERB

", @store.read('views/test.host/functional_caching/formatted_fragment_cached') - end - - def test_xml_formatted_fragment_caching - get :formatted_fragment_cached, :format => "xml" - assert_response :success - expected_body = "\n

Builder

\n\n" - - assert_equal expected_body, @response.body - - assert_equal "

Builder

\n", @store.read('views/test.host/functional_caching/formatted_fragment_cached') - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/capture_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/capture_test.rb deleted file mode 100644 index 94e3d1666..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/capture_test.rb +++ /dev/null @@ -1,73 +0,0 @@ -require 'abstract_unit' -require 'logger' - -class CaptureController < ActionController::Base - def self.controller_name; "test"; end - def self.controller_path; "test"; end - - def content_for - render :layout => "talk_from_action" - end - - def content_for_with_parameter - render :layout => "talk_from_action" - end - - def content_for_concatenated - render :layout => "talk_from_action" - end - - def non_erb_block_content_for - render :layout => "talk_from_action" - end - - def rescue_action(e) raise end -end - -class CaptureTest < ActionController::TestCase - tests CaptureController - - def setup - super - # enable a logger so that (e.g.) the benchmarking stuff runs, so we can get - # a more accurate simulation of what happens in "real life". - @controller.logger = Logger.new(nil) - - @request.host = "www.nextangle.com" - end - - def test_simple_capture - get :capturing - assert_equal "Dreamy days", @response.body.strip - end - - def test_content_for - get :content_for - assert_equal expected_content_for_output, @response.body - end - - def test_should_concatentate_content_for - get :content_for_concatenated - assert_equal expected_content_for_output, @response.body - end - - def test_should_set_content_for_with_parameter - get :content_for_with_parameter - assert_equal expected_content_for_output, @response.body - end - - def test_non_erb_block_content_for - get :non_erb_block_content_for - assert_equal expected_content_for_output, @response.body - end - - def test_proper_block_detection - @todo = "some todo" - get :proper_block_detection - end - - private - def expected_content_for_output - "Putting stuff in the title!\nGreat stuff!" - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/content_type_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/content_type_test.rb deleted file mode 100644 index 15459f255..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/content_type_test.rb +++ /dev/null @@ -1,169 +0,0 @@ -require 'abstract_unit' - -class OldContentTypeController < ActionController::Base - # :ported: - def render_content_type_from_body - response.content_type = Mime::RSS - render :text => "hello world!" - end - - # :ported: - def render_defaults - render :text => "hello world!" - end - - # :ported: - def render_content_type_from_render - render :text => "hello world!", :content_type => Mime::RSS - end - - # :ported: - def render_charset_from_body - response.charset = "utf-16" - render :text => "hello world!" - end - - # :ported: - def render_nil_charset_from_body - response.charset = nil - render :text => "hello world!" - end - - def render_default_for_rhtml - end - - def render_default_for_rxml - end - - def render_default_for_rjs - end - - def render_change_for_rxml - response.content_type = Mime::HTML - render :action => "render_default_for_rxml" - end - - def render_default_content_types_for_respond_to - respond_to do |format| - format.html { render :text => "hello world!" } - format.xml { render :action => "render_default_content_types_for_respond_to" } - format.js { render :text => "hello world!" } - format.rss { render :text => "hello world!", :content_type => Mime::XML } - end - end - - def rescue_action(e) raise end -end - -class ContentTypeTest < ActionController::TestCase - tests OldContentTypeController - - def setup - super - # enable a logger so that (e.g.) the benchmarking stuff runs, so we can get - # a more accurate simulation of what happens in "real life". - @controller.logger = Logger.new(nil) - end - - # :ported: - def test_render_defaults - get :render_defaults - assert_equal "utf-8", @response.charset - assert_equal Mime::HTML, @response.content_type - end - - def test_render_changed_charset_default - OldContentTypeController.default_charset = "utf-16" - get :render_defaults - assert_equal "utf-16", @response.charset - assert_equal Mime::HTML, @response.content_type - OldContentTypeController.default_charset = "utf-8" - end - - # :ported: - def test_content_type_from_body - get :render_content_type_from_body - assert_equal Mime::RSS, @response.content_type - assert_equal "utf-8", @response.charset - end - - # :ported: - def test_content_type_from_render - get :render_content_type_from_render - assert_equal Mime::RSS, @response.content_type - assert_equal "utf-8", @response.charset - end - - # :ported: - def test_charset_from_body - get :render_charset_from_body - assert_equal Mime::HTML, @response.content_type - assert_equal "utf-16", @response.charset - end - - # :ported: - def test_nil_charset_from_body - get :render_nil_charset_from_body - assert_equal Mime::HTML, @response.content_type - assert_equal "utf-8", @response.charset, @response.headers.inspect - end - - def test_nil_default_for_rhtml - OldContentTypeController.default_charset = nil - get :render_default_for_rhtml - assert_equal Mime::HTML, @response.content_type - assert_nil @response.charset, @response.headers.inspect - ensure - OldContentTypeController.default_charset = "utf-8" - end - - def test_default_for_rhtml - get :render_default_for_rhtml - assert_equal Mime::HTML, @response.content_type - assert_equal "utf-8", @response.charset - end - - def test_default_for_rxml - get :render_default_for_rxml - assert_equal Mime::XML, @response.content_type - assert_equal "utf-8", @response.charset - end - - def test_default_for_rjs - xhr :post, :render_default_for_rjs - assert_equal Mime::JS, @response.content_type - assert_equal "utf-8", @response.charset - end - - def test_change_for_rxml - get :render_change_for_rxml - assert_equal Mime::HTML, @response.content_type - assert_equal "utf-8", @response.charset - end -end - -class AcceptBasedContentTypeTest < ActionController::TestCase - tests OldContentTypeController - - def test_render_default_content_types_for_respond_to - @request.accept = Mime::HTML.to_s - get :render_default_content_types_for_respond_to - assert_equal Mime::HTML, @response.content_type - - @request.accept = Mime::JS.to_s - get :render_default_content_types_for_respond_to - assert_equal Mime::JS, @response.content_type - end - - def test_render_default_content_types_for_respond_to_with_template - @request.accept = Mime::XML.to_s - get :render_default_content_types_for_respond_to - assert_equal Mime::XML, @response.content_type - end - - def test_render_default_content_types_for_respond_to_with_overwrite - @request.accept = Mime::RSS.to_s - get :render_default_content_types_for_respond_to - assert_equal Mime::XML, @response.content_type - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/controller_fixtures/app/controllers/admin/user_controller.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/controller_fixtures/app/controllers/admin/user_controller.rb deleted file mode 100644 index e69de29bb..000000000 diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/controller_fixtures/app/controllers/user_controller.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/controller_fixtures/app/controllers/user_controller.rb deleted file mode 100644 index e69de29bb..000000000 diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/controller_fixtures/vendor/plugins/bad_plugin/lib/plugin_controller.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/controller_fixtures/vendor/plugins/bad_plugin/lib/plugin_controller.rb deleted file mode 100644 index e69de29bb..000000000 diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/deprecation/deprecated_base_methods_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/deprecation/deprecated_base_methods_test.rb deleted file mode 100644 index 59604480a..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/deprecation/deprecated_base_methods_test.rb +++ /dev/null @@ -1,26 +0,0 @@ -require 'abstract_unit' - -class DeprecatedBaseMethodsTest < ActionController::TestCase - class Target < ActionController::Base - def home_url(greeting) - "http://example.com/#{greeting}" - end - - def raises_name_error - this_method_doesnt_exist - end - - def rescue_action(e) raise e end - end - - tests Target - - if defined? Test::Unit::Error - def test_assertion_failed_error_silences_deprecation_warnings - get :raises_name_error - rescue => e - error = Test::Unit::Error.new('testing ur doodz', e) - assert_not_deprecated { error.message } - end - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/dispatcher_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/dispatcher_test.rb deleted file mode 100644 index 0497109fc..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/dispatcher_test.rb +++ /dev/null @@ -1,59 +0,0 @@ -require 'abstract_unit' - -# Ensure deprecated dispatcher works -class DeprecatedDispatcherTest < ActiveSupport::TestCase - class DummyApp - def call(env) - [200, {}, 'response'] - end - end - - def setup - ActionDispatch::Callbacks.reset_callbacks(:prepare) - ActionDispatch::Callbacks.reset_callbacks(:call) - end - - def test_assert_deprecated_to_prepare - a = nil - - assert_deprecated do - ActionController::Dispatcher.to_prepare { a = 1 } - end - - assert_nil a - dispatch - assert_equal 1, a - end - - def test_assert_deprecated_before_dispatch - a = nil - - assert_deprecated do - ActionController::Dispatcher.before_dispatch { a = 1 } - end - - assert_nil a - dispatch - assert_equal 1, a - end - - def test_assert_deprecated_after_dispatch - a = nil - - assert_deprecated do - ActionController::Dispatcher.after_dispatch { a = 1 } - end - - assert_nil a - dispatch - assert_equal 1, a - end - - private - - def dispatch(cache_classes = true) - @dispatcher ||= ActionDispatch::Callbacks.new(DummyApp.new, !cache_classes) - @dispatcher.call({'rack.input' => StringIO.new('')}) - end - -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/filters_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/filters_test.rb deleted file mode 100644 index a5f9a0283..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/filters_test.rb +++ /dev/null @@ -1,938 +0,0 @@ -require 'abstract_unit' - -class ActionController::Base - class << self - %w(append_around_filter prepend_after_filter prepend_around_filter prepend_before_filter skip_after_filter skip_before_filter skip_filter).each do |pending| - define_method(pending) do |*args| - $stderr.puts "#{pending} unimplemented: #{args.inspect}" - end unless method_defined?(pending) - end - - def before_filters - filters = _process_action_callbacks.select { |c| c.kind == :before } - filters.map! { |c| c.instance_variable_get(:@raw_filter) } - end - end - - def assigns(key = nil) - assigns = {} - instance_variable_names.each do |ivar| - next if ActionController::Base.protected_instance_variables.include?(ivar) - assigns[ivar[1..-1]] = instance_variable_get(ivar) - end - - key.nil? ? assigns : assigns[key.to_s] - end -end - -class FilterTest < ActionController::TestCase - - class TestController < ActionController::Base - before_filter :ensure_login - after_filter :clean_up - - def show - render :inline => "ran action" - end - - private - def ensure_login - @ran_filter ||= [] - @ran_filter << "ensure_login" - end - - def clean_up - @ran_after_filter ||= [] - @ran_after_filter << "clean_up" - end - end - - class ChangingTheRequirementsController < TestController - before_filter :ensure_login, :except => [:go_wild] - - def go_wild - render :text => "gobble" - end - end - - class TestMultipleFiltersController < ActionController::Base - before_filter :try_1 - before_filter :try_2 - before_filter :try_3 - - (1..3).each do |i| - define_method "fail_#{i}" do - render :text => i.to_s - end - end - - protected - (1..3).each do |i| - define_method "try_#{i}" do - instance_variable_set :@try, i - if action_name == "fail_#{i}" - head(404) - end - end - end - end - - class RenderingController < ActionController::Base - before_filter :render_something_else - - def show - @ran_action = true - render :inline => "ran action" - end - - private - def render_something_else - render :inline => "something else" - end - end - - class ConditionalFilterController < ActionController::Base - def show - render :inline => "ran action" - end - - def another_action - render :inline => "ran action" - end - - def show_without_filter - render :inline => "ran action without filter" - end - - private - def ensure_login - @ran_filter ||= [] - @ran_filter << "ensure_login" - end - - def clean_up_tmp - @ran_filter ||= [] - @ran_filter << "clean_up_tmp" - end - - def rescue_action(e) raise(e) end - end - - class ConditionalCollectionFilterController < ConditionalFilterController - before_filter :ensure_login, :except => [ :show_without_filter, :another_action ] - end - - class OnlyConditionSymController < ConditionalFilterController - before_filter :ensure_login, :only => :show - end - - class ExceptConditionSymController < ConditionalFilterController - before_filter :ensure_login, :except => :show_without_filter - end - - class BeforeAndAfterConditionController < ConditionalFilterController - before_filter :ensure_login, :only => :show - after_filter :clean_up_tmp, :only => :show - end - - class OnlyConditionProcController < ConditionalFilterController - before_filter(:only => :show) {|c| c.instance_variable_set(:"@ran_proc_filter", true) } - end - - class ExceptConditionProcController < ConditionalFilterController - before_filter(:except => :show_without_filter) {|c| c.instance_variable_set(:"@ran_proc_filter", true) } - end - - class ConditionalClassFilter - def self.filter(controller) controller.instance_variable_set(:"@ran_class_filter", true) end - end - - class OnlyConditionClassController < ConditionalFilterController - before_filter ConditionalClassFilter, :only => :show - end - - class ExceptConditionClassController < ConditionalFilterController - before_filter ConditionalClassFilter, :except => :show_without_filter - end - - class AnomolousYetValidConditionController < ConditionalFilterController - before_filter(ConditionalClassFilter, :ensure_login, Proc.new {|c| c.instance_variable_set(:"@ran_proc_filter1", true)}, :except => :show_without_filter) { |c| c.instance_variable_set(:"@ran_proc_filter2", true)} - end - - class ConditionalOptionsFilter < ConditionalFilterController - before_filter :ensure_login, :if => Proc.new { |c| true } - before_filter :clean_up_tmp, :if => Proc.new { |c| false } - end - - class PrependingController < TestController - prepend_before_filter :wonderful_life - # skip_before_filter :fire_flash - - private - def wonderful_life - @ran_filter ||= [] - @ran_filter << "wonderful_life" - end - end - - class SkippingAndLimitedController < TestController - skip_before_filter :ensure_login - before_filter :ensure_login, :only => :index - - def index - render :text => 'ok' - end - - def public - render :text => 'ok' - end - end - - class SkippingAndReorderingController < TestController - skip_before_filter :ensure_login - before_filter :find_record - before_filter :ensure_login - - def index - render :text => 'ok' - end - - private - def find_record - @ran_filter ||= [] - @ran_filter << "find_record" - end - end - - class ConditionalSkippingController < TestController - skip_before_filter :ensure_login, :only => [ :login ] - skip_after_filter :clean_up, :only => [ :login ] - - before_filter :find_user, :only => [ :change_password ] - - def login - render :inline => "ran action" - end - - def change_password - render :inline => "ran action" - end - - protected - def find_user - @ran_filter ||= [] - @ran_filter << "find_user" - end - end - - class ConditionalParentOfConditionalSkippingController < ConditionalFilterController - before_filter :conditional_in_parent_before, :only => [:show, :another_action] - after_filter :conditional_in_parent_after, :only => [:show, :another_action] - - private - - def conditional_in_parent_before - @ran_filter ||= [] - @ran_filter << 'conditional_in_parent_before' - end - - def conditional_in_parent_after - @ran_filter ||= [] - @ran_filter << 'conditional_in_parent_after' - end - end - - class ChildOfConditionalParentController < ConditionalParentOfConditionalSkippingController - skip_before_filter :conditional_in_parent_before, :only => :another_action - skip_after_filter :conditional_in_parent_after, :only => :another_action - end - - class AnotherChildOfConditionalParentController < ConditionalParentOfConditionalSkippingController - skip_before_filter :conditional_in_parent_before, :only => :show - end - - class ProcController < PrependingController - before_filter(proc { |c| c.instance_variable_set(:"@ran_proc_filter", true) }) - end - - class ImplicitProcController < PrependingController - before_filter { |c| c.instance_variable_set(:"@ran_proc_filter", true) } - end - - class AuditFilter - def self.filter(controller) - controller.instance_variable_set(:"@was_audited", true) - end - end - - class AroundFilter - def before(controller) - @execution_log = "before" - controller.class.execution_log << " before aroundfilter " if controller.respond_to? :execution_log - controller.instance_variable_set(:"@before_ran", true) - end - - def after(controller) - controller.instance_variable_set(:"@execution_log", @execution_log + " and after") - controller.instance_variable_set(:"@after_ran", true) - controller.class.execution_log << " after aroundfilter " if controller.respond_to? :execution_log - end - end - - class AppendedAroundFilter - def before(controller) - controller.class.execution_log << " before appended aroundfilter " - end - - def after(controller) - controller.class.execution_log << " after appended aroundfilter " - end - end - - class AuditController < ActionController::Base - before_filter(AuditFilter) - - def show - render :text => "hello" - end - end - - class AroundFilterController < PrependingController - around_filter AroundFilter.new - end - - class BeforeAfterClassFilterController < PrependingController - begin - filter = AroundFilter.new - before_filter filter - after_filter filter - end - end - - class MixedFilterController < PrependingController - cattr_accessor :execution_log - - def initialize - @@execution_log = "" - end - - before_filter { |c| c.class.execution_log << " before procfilter " } - prepend_around_filter AroundFilter.new - - after_filter { |c| c.class.execution_log << " after procfilter " } - append_around_filter AppendedAroundFilter.new - end - - class MixedSpecializationController < ActionController::Base - class OutOfOrder < StandardError; end - - before_filter :first - before_filter :second, :only => :foo - - def foo - render :text => 'foo' - end - - def bar - render :text => 'bar' - end - - protected - def first - @first = true - end - - def second - raise OutOfOrder unless @first - end - end - - class DynamicDispatchController < ActionController::Base - before_filter :choose - - %w(foo bar baz).each do |action| - define_method(action) { render :text => action } - end - - private - def choose - self.action_name = params[:choose] - end - end - - class PrependingBeforeAndAfterController < ActionController::Base - prepend_before_filter :before_all - prepend_after_filter :after_all - before_filter :between_before_all_and_after_all - - def before_all - @ran_filter ||= [] - @ran_filter << 'before_all' - end - - def after_all - @ran_filter ||= [] - @ran_filter << 'after_all' - end - - def between_before_all_and_after_all - @ran_filter ||= [] - @ran_filter << 'between_before_all_and_after_all' - end - def show - render :text => 'hello' - end - end - - class ErrorToRescue < Exception; end - - class RescuingAroundFilterWithBlock - def filter(controller) - begin - yield - rescue ErrorToRescue => ex - controller.__send__ :render, :text => "I rescued this: #{ex.inspect}" - end - end - end - - class RescuedController < ActionController::Base - around_filter RescuingAroundFilterWithBlock.new - - def show - raise ErrorToRescue.new("Something made the bad noise.") - end - - private - def rescue_action(exception) - raise exception - end - end - - class NonYieldingAroundFilterController < ActionController::Base - - before_filter :filter_one - around_filter :non_yielding_filter - before_filter :filter_two - after_filter :filter_three - - def index - render :inline => "index" - end - - #make sure the controller complains - def rescue_action(e); raise e; end - - private - - def filter_one - @filters ||= [] - @filters << "filter_one" - end - - def filter_two - @filters << "filter_two" - end - - def non_yielding_filter - @filters << "it didn't yield" - @filter_return_value - end - - def filter_three - @filters << "filter_three" - end - - end - - class ::AppSweeper < ActionController::Caching::Sweeper; end - class SweeperTestController < ActionController::Base - cache_sweeper :app_sweeper - def show - render :text => 'hello world' - end - end - def test_sweeper_should_not_block_rendering - response = test_process(SweeperTestController) - assert_equal 'hello world', response.body - end - - def test_before_method_of_sweeper_should_always_return_true - sweeper = ActionController::Caching::Sweeper.send(:new) - assert sweeper.before(TestController.new) - end - - def test_non_yielding_around_filters_not_returning_false_do_not_raise - controller = NonYieldingAroundFilterController.new - controller.instance_variable_set "@filter_return_value", true - assert_nothing_raised do - test_process(controller, "index") - end - end - - def test_non_yielding_around_filters_returning_false_do_not_raise - controller = NonYieldingAroundFilterController.new - controller.instance_variable_set "@filter_return_value", false - assert_nothing_raised do - test_process(controller, "index") - end - end - - def test_after_filters_are_not_run_if_around_filter_returns_false - controller = NonYieldingAroundFilterController.new - controller.instance_variable_set "@filter_return_value", false - test_process(controller, "index") - assert_equal ["filter_one", "it didn't yield"], controller.assigns['filters'] - end - - def test_after_filters_are_not_run_if_around_filter_does_not_yield - controller = NonYieldingAroundFilterController.new - controller.instance_variable_set "@filter_return_value", true - test_process(controller, "index") - assert_equal ["filter_one", "it didn't yield"], controller.assigns['filters'] - end - - def test_added_filter_to_inheritance_graph - assert_equal [ :ensure_login ], TestController.before_filters - end - - def test_base_class_in_isolation - assert_equal [ ], ActionController::Base.before_filters - end - - def test_prepending_filter - assert_equal [ :wonderful_life, :ensure_login ], PrependingController.before_filters - end - - def test_running_filters - test_process(PrependingController) - assert_equal %w( wonderful_life ensure_login ), assigns["ran_filter"] - end - - def test_running_filters_with_proc - test_process(ProcController) - assert assigns["ran_proc_filter"] - end - - def test_running_filters_with_implicit_proc - test_process(ImplicitProcController) - assert assigns["ran_proc_filter"] - end - - def test_running_filters_with_class - test_process(AuditController) - assert assigns["was_audited"] - end - - def test_running_anomolous_yet_valid_condition_filters - test_process(AnomolousYetValidConditionController) - assert_equal %w( ensure_login ), assigns["ran_filter"] - assert assigns["ran_class_filter"] - assert assigns["ran_proc_filter1"] - assert assigns["ran_proc_filter2"] - - test_process(AnomolousYetValidConditionController, "show_without_filter") - assert_nil assigns["ran_filter"] - assert !assigns["ran_class_filter"] - assert !assigns["ran_proc_filter1"] - assert !assigns["ran_proc_filter2"] - end - - def test_running_conditional_options - test_process(ConditionalOptionsFilter) - assert_equal %w( ensure_login ), assigns["ran_filter"] - end - - def test_running_collection_condition_filters - test_process(ConditionalCollectionFilterController) - assert_equal %w( ensure_login ), assigns["ran_filter"] - test_process(ConditionalCollectionFilterController, "show_without_filter") - assert_nil assigns["ran_filter"] - test_process(ConditionalCollectionFilterController, "another_action") - assert_nil assigns["ran_filter"] - end - - def test_running_only_condition_filters - test_process(OnlyConditionSymController) - assert_equal %w( ensure_login ), assigns["ran_filter"] - test_process(OnlyConditionSymController, "show_without_filter") - assert_nil assigns["ran_filter"] - - test_process(OnlyConditionProcController) - assert assigns["ran_proc_filter"] - test_process(OnlyConditionProcController, "show_without_filter") - assert !assigns["ran_proc_filter"] - - test_process(OnlyConditionClassController) - assert assigns["ran_class_filter"] - test_process(OnlyConditionClassController, "show_without_filter") - assert !assigns["ran_class_filter"] - end - - def test_running_except_condition_filters - test_process(ExceptConditionSymController) - assert_equal %w( ensure_login ), assigns["ran_filter"] - test_process(ExceptConditionSymController, "show_without_filter") - assert_nil assigns["ran_filter"] - - test_process(ExceptConditionProcController) - assert assigns["ran_proc_filter"] - test_process(ExceptConditionProcController, "show_without_filter") - assert !assigns["ran_proc_filter"] - - test_process(ExceptConditionClassController) - assert assigns["ran_class_filter"] - test_process(ExceptConditionClassController, "show_without_filter") - assert !assigns["ran_class_filter"] - end - - def test_running_before_and_after_condition_filters - test_process(BeforeAndAfterConditionController) - assert_equal %w( ensure_login clean_up_tmp), assigns["ran_filter"] - test_process(BeforeAndAfterConditionController, "show_without_filter") - assert_nil assigns["ran_filter"] - end - - def test_around_filter - test_process(AroundFilterController) - assert assigns["before_ran"] - assert assigns["after_ran"] - end - - def test_before_after_class_filter - test_process(BeforeAfterClassFilterController) - assert assigns["before_ran"] - assert assigns["after_ran"] - end - - def test_having_properties_in_around_filter - test_process(AroundFilterController) - assert_equal "before and after", assigns["execution_log"] - end - - def test_prepending_and_appending_around_filter - controller = test_process(MixedFilterController) - assert_equal " before aroundfilter before procfilter before appended aroundfilter " + - " after appended aroundfilter after procfilter after aroundfilter ", - MixedFilterController.execution_log - end - - def test_rendering_breaks_filtering_chain - response = test_process(RenderingController) - assert_equal "something else", response.body - assert !assigns["ran_action"] - end - - def test_filters_with_mixed_specialization_run_in_order - assert_nothing_raised do - response = test_process(MixedSpecializationController, 'bar') - assert_equal 'bar', response.body - end - - assert_nothing_raised do - response = test_process(MixedSpecializationController, 'foo') - assert_equal 'foo', response.body - end - end - - def test_dynamic_dispatch - %w(foo bar baz).each do |action| - request = ActionController::TestRequest.new - request.query_parameters[:choose] = action - response = DynamicDispatchController.action(action).call(request.env).last - assert_equal action, response.body - end - end - - def test_running_prepended_before_and_after_filter - test_process(PrependingBeforeAndAfterController) - assert_equal %w( before_all between_before_all_and_after_all after_all ), assigns["ran_filter"] - end - - def test_skipping_and_limiting_controller - test_process(SkippingAndLimitedController, "index") - assert_equal %w( ensure_login ), assigns["ran_filter"] - test_process(SkippingAndLimitedController, "public") - assert_nil assigns["ran_filter"] - end - - def test_skipping_and_reordering_controller - test_process(SkippingAndReorderingController, "index") - assert_equal %w( find_record ensure_login ), assigns["ran_filter"] - end - - def test_conditional_skipping_of_filters - test_process(ConditionalSkippingController, "login") - assert_nil assigns["ran_filter"] - test_process(ConditionalSkippingController, "change_password") - assert_equal %w( ensure_login find_user ), assigns["ran_filter"] - - test_process(ConditionalSkippingController, "login") - assert_nil @controller.instance_variable_get("@ran_after_filter") - test_process(ConditionalSkippingController, "change_password") - assert_equal %w( clean_up ), @controller.instance_variable_get("@ran_after_filter") - end - - def test_conditional_skipping_of_filters_when_parent_filter_is_also_conditional - test_process(ChildOfConditionalParentController) - assert_equal %w( conditional_in_parent_before conditional_in_parent_after ), assigns['ran_filter'] - test_process(ChildOfConditionalParentController, 'another_action') - assert_nil assigns['ran_filter'] - end - - def test_condition_skipping_of_filters_when_siblings_also_have_conditions - test_process(ChildOfConditionalParentController) - assert_equal %w( conditional_in_parent_before conditional_in_parent_after ), assigns['ran_filter'] - test_process(AnotherChildOfConditionalParentController) - assert_equal %w( conditional_in_parent_after ), assigns['ran_filter'] - test_process(ChildOfConditionalParentController) - assert_equal %w( conditional_in_parent_before conditional_in_parent_after ), assigns['ran_filter'] - end - - def test_changing_the_requirements - test_process(ChangingTheRequirementsController, "go_wild") - assert_nil assigns['ran_filter'] - end - - def test_a_rescuing_around_filter - response = nil - assert_nothing_raised do - response = test_process(RescuedController) - end - - assert response.success? - assert_equal("I rescued this: #", response.body) - end - - private - def test_process(controller, action = "show") - @controller = controller.is_a?(Class) ? controller.new : controller - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new - - process(action) - end -end - - - -class PostsController < ActionController::Base - def rescue_action(e); raise e; end - - module AroundExceptions - class Error < StandardError ; end - class Before < Error ; end - class After < Error ; end - end - include AroundExceptions - - class DefaultFilter - include AroundExceptions - end - - module_eval %w(raises_before raises_after raises_both no_raise no_filter).map { |action| "def #{action}; default_action end" }.join("\n") - - private - def default_action - render :inline => "#{action_name} called" - end -end - -class ControllerWithSymbolAsFilter < PostsController - around_filter :raise_before, :only => :raises_before - around_filter :raise_after, :only => :raises_after - around_filter :without_exception, :only => :no_raise - - private - def raise_before - raise Before - yield - end - - def raise_after - yield - raise After - end - - def without_exception - # Do stuff... - 1 + 1 - - yield - - # Do stuff... - 1 + 1 - end -end - -class ControllerWithFilterClass < PostsController - class YieldingFilter < DefaultFilter - def self.filter(controller) - yield - raise After - end - end - - around_filter YieldingFilter, :only => :raises_after -end - -class ControllerWithFilterInstance < PostsController - class YieldingFilter < DefaultFilter - def filter(controller) - yield - raise After - end - end - - around_filter YieldingFilter.new, :only => :raises_after -end - -class ControllerWithFilterMethod < PostsController - class YieldingFilter < DefaultFilter - def filter(controller) - yield - raise After - end - end - - around_filter YieldingFilter.new.method(:filter), :only => :raises_after -end - -class ControllerWithProcFilter < PostsController - around_filter(:only => :no_raise) do |c,b| - c.instance_variable_set(:"@before", true) - b.call - c.instance_variable_set(:"@after", true) - end -end - -class ControllerWithNestedFilters < ControllerWithSymbolAsFilter - around_filter :raise_before, :raise_after, :without_exception, :only => :raises_both -end - -class ControllerWithAllTypesOfFilters < PostsController - before_filter :before - around_filter :around - after_filter :after - around_filter :around_again - - private - def before - @ran_filter ||= [] - @ran_filter << 'before' - end - - def around - @ran_filter << 'around (before yield)' - yield - @ran_filter << 'around (after yield)' - end - - def after - @ran_filter << 'after' - end - - def around_again - @ran_filter << 'around_again (before yield)' - yield - @ran_filter << 'around_again (after yield)' - end -end - -class ControllerWithTwoLessFilters < ControllerWithAllTypesOfFilters - $vbf = true - skip_filter :around_again - $vbf = false - skip_filter :after -end - -class YieldingAroundFiltersTest < ActionController::TestCase - include PostsController::AroundExceptions - - def test_base - controller = PostsController - assert_nothing_raised { test_process(controller,'no_raise') } - assert_nothing_raised { test_process(controller,'raises_before') } - assert_nothing_raised { test_process(controller,'raises_after') } - assert_nothing_raised { test_process(controller,'no_filter') } - end - - def test_with_symbol - controller = ControllerWithSymbolAsFilter - assert_nothing_raised { test_process(controller,'no_raise') } - assert_raise(Before) { test_process(controller,'raises_before') } - assert_raise(After) { test_process(controller,'raises_after') } - assert_nothing_raised { test_process(controller,'no_raise') } - end - - def test_with_class - controller = ControllerWithFilterClass - assert_nothing_raised { test_process(controller,'no_raise') } - assert_raise(After) { test_process(controller,'raises_after') } - end - - def test_with_instance - controller = ControllerWithFilterInstance - assert_nothing_raised { test_process(controller,'no_raise') } - assert_raise(After) { test_process(controller,'raises_after') } - end - - def test_with_proc - test_process(ControllerWithProcFilter,'no_raise') - assert assigns['before'] - assert assigns['after'] - end - - def test_nested_filters - controller = ControllerWithNestedFilters - assert_nothing_raised do - begin - test_process(controller,'raises_both') - rescue Before, After - end - end - assert_raise Before do - begin - test_process(controller,'raises_both') - rescue After - end - end - end - - def test_filter_order_with_all_filter_types - test_process(ControllerWithAllTypesOfFilters,'no_raise') - assert_equal 'before around (before yield) around_again (before yield) around_again (after yield) after around (after yield)', assigns['ran_filter'].join(' ') - end - - def test_filter_order_with_skip_filter_method - test_process(ControllerWithTwoLessFilters,'no_raise') - assert_equal 'before around (before yield) around (after yield)', assigns['ran_filter'].join(' ') - end - - def test_first_filter_in_multiple_before_filter_chain_halts - controller = ::FilterTest::TestMultipleFiltersController.new - response = test_process(controller, 'fail_1') - assert_equal ' ', response.body - assert_equal 1, controller.instance_variable_get(:@try) - end - - def test_second_filter_in_multiple_before_filter_chain_halts - controller = ::FilterTest::TestMultipleFiltersController.new - response = test_process(controller, 'fail_2') - assert_equal ' ', response.body - assert_equal 2, controller.instance_variable_get(:@try) - end - - def test_last_filter_in_multiple_before_filter_chain_halts - controller = ::FilterTest::TestMultipleFiltersController.new - response = test_process(controller, 'fail_3') - assert_equal ' ', response.body - assert_equal 3, controller.instance_variable_get(:@try) - end - - protected - def test_process(controller, action = "show") - @controller = controller.is_a?(Class) ? controller.new : controller - process(action) - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/flash_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/flash_test.rb deleted file mode 100644 index feeb6d9a1..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/flash_test.rb +++ /dev/null @@ -1,271 +0,0 @@ -require 'abstract_unit' - -class FlashTest < ActionController::TestCase - class TestController < ActionController::Base - def set_flash - flash["that"] = "hello" - render :inline => "hello" - end - - def set_flash_now - flash.now["that"] = "hello" - flash.now["foo"] ||= "bar" - flash.now["foo"] ||= "err" - @flashy = flash.now["that"] - @flash_copy = {}.update flash - render :inline => "hello" - end - - def attempt_to_use_flash_now - @flash_copy = {}.update flash - @flashy = flash["that"] - render :inline => "hello" - end - - def use_flash - @flash_copy = {}.update flash - @flashy = flash["that"] - render :inline => "hello" - end - - def use_flash_and_keep_it - @flash_copy = {}.update flash - @flashy = flash["that"] - flash.keep - render :inline => "hello" - end - - def use_flash_and_update_it - flash.update("this" => "hello again") - @flash_copy = {}.update flash - render :inline => "hello" - end - - def use_flash_after_reset_session - flash["that"] = "hello" - @flashy_that = flash["that"] - reset_session - @flashy_that_reset = flash["that"] - flash["this"] = "good-bye" - @flashy_this = flash["this"] - render :inline => "hello" - end - - def rescue_action(e) - raise unless ActionView::MissingTemplate === e - end - - # methods for test_sweep_after_halted_filter_chain - before_filter :halt_and_redir, :only => "filter_halting_action" - - def std_action - @flash_copy = {}.update(flash) - render :nothing => true - end - - def filter_halting_action - @flash_copy = {}.update(flash) - end - - def halt_and_redir - flash["foo"] = "bar" - redirect_to :action => "std_action" - @flash_copy = {}.update(flash) - end - - def redirect_with_alert - redirect_to '/nowhere', :alert => "Beware the nowheres!" - end - - def redirect_with_notice - redirect_to '/somewhere', :notice => "Good luck in the somewheres!" - end - - def render_with_flash_now_alert - flash.now.alert = "Beware the nowheres now!" - render :inline => "hello" - end - - def render_with_flash_now_notice - flash.now.notice = "Good luck in the somewheres now!" - render :inline => "hello" - end - - def redirect_with_other_flashes - redirect_to '/wonderland', :flash => { :joyride => "Horses!" } - end - end - - tests TestController - - def test_flash - get :set_flash - - get :use_flash - assert_equal "hello", assigns["flash_copy"]["that"] - assert_equal "hello", assigns["flashy"] - - get :use_flash - assert_nil assigns["flash_copy"]["that"], "On second flash" - end - - def test_keep_flash - get :set_flash - - get :use_flash_and_keep_it - assert_equal "hello", assigns["flash_copy"]["that"] - assert_equal "hello", assigns["flashy"] - - get :use_flash - assert_equal "hello", assigns["flash_copy"]["that"], "On second flash" - - get :use_flash - assert_nil assigns["flash_copy"]["that"], "On third flash" - end - - def test_flash_now - get :set_flash_now - assert_equal "hello", assigns["flash_copy"]["that"] - assert_equal "bar" , assigns["flash_copy"]["foo"] - assert_equal "hello", assigns["flashy"] - - get :attempt_to_use_flash_now - assert_nil assigns["flash_copy"]["that"] - assert_nil assigns["flash_copy"]["foo"] - assert_nil assigns["flashy"] - end - - def test_update_flash - get :set_flash - get :use_flash_and_update_it - assert_equal "hello", assigns["flash_copy"]["that"] - assert_equal "hello again", assigns["flash_copy"]["this"] - get :use_flash - assert_nil assigns["flash_copy"]["that"], "On second flash" - assert_equal "hello again", assigns["flash_copy"]["this"], "On second flash" - end - - def test_flash_after_reset_session - get :use_flash_after_reset_session - assert_equal "hello", assigns["flashy_that"] - assert_equal "good-bye", assigns["flashy_this"] - assert_nil assigns["flashy_that_reset"] - end - - def test_does_not_set_the_session_if_the_flash_is_empty - get :std_action - assert_nil session["flash"] - end - - def test_sweep_after_halted_filter_chain - get :std_action - assert_nil assigns["flash_copy"]["foo"] - get :filter_halting_action - assert_equal "bar", assigns["flash_copy"]["foo"] - get :std_action # follow redirection - assert_equal "bar", assigns["flash_copy"]["foo"] - get :std_action - assert_nil assigns["flash_copy"]["foo"] - end - - def test_keep_and_discard_return_values - flash = ActionDispatch::Flash::FlashHash.new - flash.update(:foo => :foo_indeed, :bar => :bar_indeed) - - assert_equal(:foo_indeed, flash.discard(:foo)) # valid key passed - assert_nil flash.discard(:unknown) # non existant key passed - assert_equal({:foo => :foo_indeed, :bar => :bar_indeed}, flash.discard()) # nothing passed - assert_equal({:foo => :foo_indeed, :bar => :bar_indeed}, flash.discard(nil)) # nothing passed - - assert_equal(:foo_indeed, flash.keep(:foo)) # valid key passed - assert_nil flash.keep(:unknown) # non existant key passed - assert_equal({:foo => :foo_indeed, :bar => :bar_indeed}, flash.keep()) # nothing passed - assert_equal({:foo => :foo_indeed, :bar => :bar_indeed}, flash.keep(nil)) # nothing passed - end - - def test_redirect_to_with_alert - get :redirect_with_alert - assert_equal "Beware the nowheres!", @controller.send(:flash)[:alert] - end - - def test_redirect_to_with_notice - get :redirect_with_notice - assert_equal "Good luck in the somewheres!", @controller.send(:flash)[:notice] - end - - def test_render_with_flash_now_alert - get :render_with_flash_now_alert - assert_equal "Beware the nowheres now!", @controller.send(:flash)[:alert] - end - - def test_render_with_flash_now_notice - get :render_with_flash_now_notice - assert_equal "Good luck in the somewheres now!", @controller.send(:flash)[:notice] - end - - def test_redirect_to_with_other_flashes - get :redirect_with_other_flashes - assert_equal "Horses!", @controller.send(:flash)[:joyride] - end -end - -class FlashIntegrationTest < ActionController::IntegrationTest - SessionKey = '_myapp_session' - SessionSecret = 'b3c631c314c0bbca50c1b2843150fe33' - - class TestController < ActionController::Base - def set_flash - flash["that"] = "hello" - head :ok - end - - def use_flash - render :inline => "flash: #{flash["that"]}" - end - end - - def test_flash - with_test_route_set do - get '/set_flash' - assert_response :success - assert_equal "hello", @request.flash["that"] - - get '/use_flash' - assert_response :success - assert_equal "flash: hello", @response.body - end - end - - def test_just_using_flash_does_not_stream_a_cookie_back - with_test_route_set do - get '/use_flash' - assert_response :success - assert_nil @response.headers["Set-Cookie"] - assert_equal "flash: ", @response.body - end - end - - private - - # Overwrite get to send SessionSecret in env hash - def get(path, parameters = nil, env = {}) - env["action_dispatch.secret_token"] ||= SessionSecret - super - end - - def with_test_route_set - with_routing do |set| - set.draw do |map| - match ':action', :to => FlashIntegrationTest::TestController - end - - @app = self.class.build_app(set) do |middleware| - middleware.use ActionDispatch::Session::CookieStore, :key => SessionKey - middleware.use ActionDispatch::Flash - middleware.delete "ActionDispatch::ShowExceptions" - end - - yield - end - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/helper_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/helper_test.rb deleted file mode 100644 index 4642ce220..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/helper_test.rb +++ /dev/null @@ -1,258 +0,0 @@ -require 'abstract_unit' -require 'active_support/core_ext/kernel/reporting' - -ActionController::Base.helpers_path = File.expand_path('../../fixtures/helpers', __FILE__) - -module Fun - class GamesController < ActionController::Base - def render_hello_world - render :inline => "hello: <%= stratego %>" - end - - def rescue_action(e) raise end - end - - class PdfController < ActionController::Base - def test - render :inline => "test: <%= foobar %>" - end - - def rescue_action(e) raise end - end -end - -class AllHelpersController < ActionController::Base - helper :all -end - -module ImpressiveLibrary - extend ActiveSupport::Concern - included do - helper_method :useful_function - end - - def useful_function() end -end - -ActionController::Base.send :include, ImpressiveLibrary - -class JustMeController < ActionController::Base - clear_helpers - - def flash - render :inline => "

<%= notice %>

" - end - - def lib - render :inline => '<%= useful_function %>' - end -end - -class MeTooController < JustMeController -end - -module LocalAbcHelper - def a() end - def b() end - def c() end -end - -class HelperTest < ActiveSupport::TestCase - class TestController < ActionController::Base - attr_accessor :delegate_attr - def delegate_method() end - def rescue_action(e) raise end - end - - def setup - # Increment symbol counter. - @symbol = (@@counter ||= 'A0').succ!.dup - - # Generate new controller class. - controller_class_name = "Helper#{@symbol}Controller" - eval("class #{controller_class_name} < TestController; end") - @controller_class = self.class.const_get(controller_class_name) - - # Set default test helper. - self.test_helper = LocalAbcHelper - end - - def test_deprecated_helper - assert_equal expected_helper_methods, missing_methods - assert_nothing_raised { @controller_class.helper TestHelper } - assert_equal [], missing_methods - end - - def test_helper_method - assert_nothing_raised { @controller_class.helper_method :delegate_method } - assert master_helper_methods.include?('delegate_method') - end - - def test_helper_attr - assert_nothing_raised { @controller_class.helper_attr :delegate_attr } - assert master_helper_methods.include?('delegate_attr') - assert master_helper_methods.include?('delegate_attr=') - end - - def call_controller(klass, action) - request = ActionController::TestRequest.new - klass.action(action).call(request.env) - end - - def test_helper_for_nested_controller - assert_equal 'hello: Iz guuut!', - call_controller(Fun::GamesController, "render_hello_world").last.body - # request = ActionController::TestRequest.new - # - # resp = Fun::GamesController.action(:render_hello_world).call(request.env) - # assert_equal 'hello: Iz guuut!', resp.last.body - end - - def test_helper_for_acronym_controller - assert_equal "test: baz", call_controller(Fun::PdfController, "test").last.body - # - # request = ActionController::TestRequest.new - # response = ActionController::TestResponse.new - # request.action = 'test' - # - # assert_equal 'test: baz', Fun::PdfController.process(request, response).body - end - - def test_default_helpers_only - assert_equal [JustMeHelper], JustMeController._helpers.ancestors.reject(&:anonymous?) - assert_equal [MeTooHelper, JustMeHelper], MeTooController._helpers.ancestors.reject(&:anonymous?) - end - - def test_base_helper_methods_after_clear_helpers - assert_nothing_raised do - call_controller(JustMeController, "flash") - end - end - - def test_lib_helper_methods_after_clear_helpers - assert_nothing_raised do - call_controller(JustMeController, "lib") - end - end - - def test_all_helpers - methods = AllHelpersController._helpers.instance_methods.map {|m| m.to_s} - - # abc_helper.rb - assert methods.include?('bare_a') - - # fun/games_helper.rb - assert methods.include?('stratego') - - # fun/pdf_helper.rb - assert methods.include?('foobar') - end - - def test_all_helpers_with_alternate_helper_dir - @controller_class.helpers_path = File.expand_path('../../fixtures/alternate_helpers', __FILE__) - - # Reload helpers - @controller_class._helpers = Module.new - @controller_class.helper :all - - # helpers/abc_helper.rb should not be included - assert !master_helper_methods.include?('bare_a') - - # alternate_helpers/foo_helper.rb - assert master_helper_methods.include?('baz') - end - - def test_helper_proxy - methods = AllHelpersController.helpers.methods.map(&:to_s) - - # Action View - assert methods.include?('pluralize') - - # abc_helper.rb - assert methods.include?('bare_a') - - # fun/games_helper.rb - assert methods.include?('stratego') - - # fun/pdf_helper.rb - assert methods.include?('foobar') - end - - def test_deprecation - assert_deprecated do - ActionController::Base.helpers_dir = "some/foo/bar" - end - assert_deprecated do - assert_equal ["some/foo/bar"], ActionController::Base.helpers_dir - end - ensure - ActionController::Base.helpers_path = File.expand_path('../../fixtures/helpers', __FILE__) - end - - private - def expected_helper_methods - TestHelper.instance_methods.map {|m| m.to_s } - end - - def master_helper_methods - @controller_class._helpers.instance_methods.map {|m| m.to_s } - end - - def missing_methods - expected_helper_methods - master_helper_methods - end - - def test_helper=(helper_module) - silence_warnings { self.class.const_set('TestHelper', helper_module) } - end -end - - -class IsolatedHelpersTest < ActiveSupport::TestCase - class A < ActionController::Base - def index - render :inline => '<%= shout %>' - end - - def rescue_action(e) raise end - end - - class B < A - helper { def shout; 'B' end } - - def index - render :inline => '<%= shout %>' - end - end - - class C < A - helper { def shout; 'C' end } - - def index - render :inline => '<%= shout %>' - end - end - - def call_controller(klass, action) - request = ActionController::TestRequest.new - klass.action(action).call(request.env) - end - - def setup - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new - @request.action = 'index' - end - - def test_helper_in_a - assert_raise(ActionView::Template::Error) { call_controller(A, "index") } - end - - def test_helper_in_b - assert_equal 'B', call_controller(B, "index").last.body - end - - def test_helper_in_c - assert_equal 'C', call_controller(C, "index").last.body - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/http_basic_authentication_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/http_basic_authentication_test.rb deleted file mode 100644 index 4bf865363..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/http_basic_authentication_test.rb +++ /dev/null @@ -1,113 +0,0 @@ -require 'abstract_unit' - -class HttpBasicAuthenticationTest < ActionController::TestCase - class DummyController < ActionController::Base - before_filter :authenticate, :only => :index - before_filter :authenticate_with_request, :only => :display - before_filter :authenticate_long_credentials, :only => :show - - def index - render :text => "Hello Secret" - end - - def display - render :text => 'Definitely Maybe' - end - - def show - render :text => 'Only for loooooong credentials' - end - - private - - def authenticate - authenticate_or_request_with_http_basic do |username, password| - username == 'lifo' && password == 'world' - end - end - - def authenticate_with_request - if authenticate_with_http_basic { |username, password| username == 'pretty' && password == 'please' } - @logged_in = true - else - request_http_basic_authentication("SuperSecret") - end - end - - def authenticate_long_credentials - authenticate_or_request_with_http_basic do |username, password| - username == '1234567890123456789012345678901234567890' && password == '1234567890123456789012345678901234567890' - end - end - end - - AUTH_HEADERS = ['HTTP_AUTHORIZATION', 'X-HTTP_AUTHORIZATION', 'X_HTTP_AUTHORIZATION', 'REDIRECT_X_HTTP_AUTHORIZATION'] - - tests DummyController - - AUTH_HEADERS.each do |header| - test "successful authentication with #{header.downcase}" do - @request.env[header] = encode_credentials('lifo', 'world') - get :index - - assert_response :success - assert_equal 'Hello Secret', @response.body, "Authentication failed for request header #{header}" - end - test "successful authentication with #{header.downcase} and long credentials" do - @request.env[header] = encode_credentials('1234567890123456789012345678901234567890', '1234567890123456789012345678901234567890') - get :show - - assert_response :success - assert_equal 'Only for loooooong credentials', @response.body, "Authentication failed for request header #{header} and long credentials" - end - end - - AUTH_HEADERS.each do |header| - test "unsuccessful authentication with #{header.downcase}" do - @request.env[header] = encode_credentials('h4x0r', 'world') - get :index - - assert_response :unauthorized - assert_equal "HTTP Basic: Access denied.\n", @response.body, "Authentication didn't fail for request header #{header}" - end - test "unsuccessful authentication with #{header.downcase} and long credentials" do - @request.env[header] = encode_credentials('h4x0rh4x0rh4x0rh4x0rh4x0rh4x0rh4x0rh4x0r', 'worldworldworldworldworldworldworldworld') - get :show - - assert_response :unauthorized - assert_equal "HTTP Basic: Access denied.\n", @response.body, "Authentication didn't fail for request header #{header} and long credentials" - end - end - - test "authentication request without credential" do - get :display - - assert_response :unauthorized - assert_equal "HTTP Basic: Access denied.\n", @response.body - assert_equal 'Basic realm="SuperSecret"', @response.headers['WWW-Authenticate'] - end - - test "authentication request with invalid credential" do - @request.env['HTTP_AUTHORIZATION'] = encode_credentials('pretty', 'foo') - get :display - - assert_response :unauthorized - assert_equal "HTTP Basic: Access denied.\n", @response.body - assert_equal 'Basic realm="SuperSecret"', @response.headers['WWW-Authenticate'] - end - - test "authentication request with valid credential" do - @request.env['HTTP_AUTHORIZATION'] = encode_credentials('pretty', 'please') - get :display - - assert_response :success - assert assigns(:logged_in) - assert_equal 'Definitely Maybe', @response.body - end - - private - - def encode_credentials(username, password) - "Basic #{ActiveSupport::Base64.encode64("#{username}:#{password}")}" - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/http_digest_authentication_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/http_digest_authentication_test.rb deleted file mode 100644 index e8c07d60e..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/http_digest_authentication_test.rb +++ /dev/null @@ -1,238 +0,0 @@ -require 'abstract_unit' - -class HttpDigestAuthenticationTest < ActionController::TestCase - class DummyDigestController < ActionController::Base - before_filter :authenticate, :only => :index - before_filter :authenticate_with_request, :only => :display - - USERS = { 'lifo' => 'world', 'pretty' => 'please', - 'dhh' => ::Digest::MD5::hexdigest(["dhh","SuperSecret","secret"].join(":"))} - - def index - render :text => "Hello Secret" - end - - def display - render :text => 'Definitely Maybe' - end - - private - - def authenticate - authenticate_or_request_with_http_digest("SuperSecret") do |username| - # Return the password - USERS[username] - end - end - - def authenticate_with_request - if authenticate_with_http_digest("SuperSecret") { |username| USERS[username] } - @logged_in = true - else - request_http_digest_authentication("SuperSecret", "Authentication Failed") - end - end - end - - AUTH_HEADERS = ['HTTP_AUTHORIZATION', 'X-HTTP_AUTHORIZATION', 'X_HTTP_AUTHORIZATION', 'REDIRECT_X_HTTP_AUTHORIZATION'] - - tests DummyDigestController - - setup do - # Used as secret in generating nonce to prevent tampering of timestamp - @secret = "session_options_secret" - @request.env["action_dispatch.secret_token"] = @secret - end - - teardown do - # ActionController::Base.session_options[:secret] = @old_secret - end - - AUTH_HEADERS.each do |header| - test "successful authentication with #{header.downcase}" do - @request.env[header] = encode_credentials(:username => 'lifo', :password => 'world') - get :index - - assert_response :success - assert_equal 'Hello Secret', @response.body, "Authentication failed for request header #{header}" - end - end - - AUTH_HEADERS.each do |header| - test "unsuccessful authentication with #{header.downcase}" do - @request.env[header] = encode_credentials(:username => 'h4x0r', :password => 'world') - get :index - - assert_response :unauthorized - assert_equal "HTTP Digest: Access denied.\n", @response.body, "Authentication didn't fail for request header #{header}" - end - end - - test "authentication request without credential" do - get :display - - assert_response :unauthorized - assert_equal "Authentication Failed", @response.body - credentials = decode_credentials(@response.headers['WWW-Authenticate']) - assert_equal 'SuperSecret', credentials[:realm] - end - - test "authentication request with nil credentials" do - @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => nil, :password => nil) - get :index - - assert_response :unauthorized - assert_equal "HTTP Digest: Access denied.\n", @response.body, "Authentication didn't fail for request" - assert_not_equal 'Hello Secret', @response.body, "Authentication didn't fail for request" - end - - test "authentication request with invalid password" do - @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'foo') - get :display - - assert_response :unauthorized - assert_equal "Authentication Failed", @response.body - end - - test "authentication request with invalid nonce" do - @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please', :nonce => "xxyyzz") - get :display - - assert_response :unauthorized - assert_equal "Authentication Failed", @response.body - end - - test "authentication request with invalid opaque" do - @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'foo', :opaque => "xxyyzz") - get :display - - assert_response :unauthorized - assert_equal "Authentication Failed", @response.body - end - - test "authentication request with invalid realm" do - @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'foo', :realm => "NotSecret") - get :display - - assert_response :unauthorized - assert_equal "Authentication Failed", @response.body - end - - test "authentication request with valid credential" do - @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please') - get :display - - assert_response :success - assert assigns(:logged_in) - assert_equal 'Definitely Maybe', @response.body - end - - test "authentication request with valid credential and nil session" do - @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please') - - get :display - - assert_response :success - assert assigns(:logged_in) - assert_equal 'Definitely Maybe', @response.body - end - - test "authentication request with request-uri that doesn't match credentials digest-uri" do - @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please') - @request.env['PATH_INFO'] = "/http_digest_authentication_test/dummy_digest/altered/uri" - get :display - - assert_response :unauthorized - assert_equal "Authentication Failed", @response.body - end - - test "authentication request with absolute request uri (as in webrick)" do - @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please') - @request.env["SERVER_NAME"] = "test.host" - @request.env['PATH_INFO'] = "/http_digest_authentication_test/dummy_digest" - - get :display - - assert_response :success - assert assigns(:logged_in) - assert_equal 'Definitely Maybe', @response.body - end - - test "authentication request with absolute uri in credentials (as in IE)" do - @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:url => "http://test.host/http_digest_authentication_test/dummy_digest", - :username => 'pretty', :password => 'please') - - get :display - - assert_response :success - assert assigns(:logged_in) - assert_equal 'Definitely Maybe', @response.body - end - - test "authentication request with absolute uri in both request and credentials (as in Webrick with IE)" do - @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:url => "http://test.host/http_digest_authentication_test/dummy_digest", - :username => 'pretty', :password => 'please') - @request.env['SERVER_NAME'] = "test.host" - @request.env['PATH_INFO'] = "/http_digest_authentication_test/dummy_digest" - - get :display - - assert_response :success - assert assigns(:logged_in) - assert_equal 'Definitely Maybe', @response.body - end - - test "authentication request with password stored as ha1 digest hash" do - @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'dhh', - :password => ::Digest::MD5::hexdigest(["dhh","SuperSecret","secret"].join(":")), - :password_is_ha1 => true) - get :display - - assert_response :success - assert assigns(:logged_in) - assert_equal 'Definitely Maybe', @response.body - end - - test "authentication request with _method" do - @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please', :method => :post) - @request.env['rack.methodoverride.original_method'] = 'POST' - put :display - - assert_response :success - assert assigns(:logged_in) - assert_equal 'Definitely Maybe', @response.body - end - - test "validate_digest_response should fail with nil returning password_procedure" do - @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => nil, :password => nil) - assert !ActionController::HttpAuthentication::Digest.validate_digest_response(@request, "SuperSecret"){nil} - end - - private - - def encode_credentials(options) - options.reverse_merge!(:nc => "00000001", :cnonce => "0a4f113b", :password_is_ha1 => false) - password = options.delete(:password) - - # Perform unauthenticated request to retrieve digest parameters to use on subsequent request - method = options.delete(:method) || 'GET' - - case method.to_s.upcase - when 'GET' - get :index - when 'POST' - post :index - end - - assert_response :unauthorized - - credentials = decode_credentials(@response.headers['WWW-Authenticate']) - credentials.merge!(options) - credentials.merge!(:uri => @request.env['PATH_INFO'].to_s) - ActionController::HttpAuthentication::Digest.encode_credentials(method, credentials, password, options[:password_is_ha1]) - end - - def decode_credentials(header) - ActionController::HttpAuthentication::Digest.decode_credentials(@response.headers['WWW-Authenticate']) - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/http_token_authentication_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/http_token_authentication_test.rb deleted file mode 100644 index af6ecea6a..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/http_token_authentication_test.rb +++ /dev/null @@ -1,113 +0,0 @@ -require 'abstract_unit' - -class HttpTokenAuthenticationTest < ActionController::TestCase - class DummyController < ActionController::Base - before_filter :authenticate, :only => :index - before_filter :authenticate_with_request, :only => :display - before_filter :authenticate_long_credentials, :only => :show - - def index - render :text => "Hello Secret" - end - - def display - render :text => 'Definitely Maybe' - end - - def show - render :text => 'Only for loooooong credentials' - end - - private - - def authenticate - authenticate_or_request_with_http_token do |token, options| - token == 'lifo' - end - end - - def authenticate_with_request - if authenticate_with_http_token { |token, options| token == '"quote" pretty' && options[:algorithm] == 'test' } - @logged_in = true - else - request_http_token_authentication("SuperSecret") - end - end - - def authenticate_long_credentials - authenticate_or_request_with_http_token do |token, options| - token == '1234567890123456789012345678901234567890' && options[:algorithm] == 'test' - end - end - end - - AUTH_HEADERS = ['HTTP_AUTHORIZATION', 'X-HTTP_AUTHORIZATION', 'X_HTTP_AUTHORIZATION', 'REDIRECT_X_HTTP_AUTHORIZATION'] - - tests DummyController - - AUTH_HEADERS.each do |header| - test "successful authentication with #{header.downcase}" do - @request.env[header] = encode_credentials('lifo') - get :index - - assert_response :success - assert_equal 'Hello Secret', @response.body, "Authentication failed for request header #{header}" - end - test "successful authentication with #{header.downcase} and long credentials" do - @request.env[header] = encode_credentials('1234567890123456789012345678901234567890', :algorithm => 'test') - get :show - - assert_response :success - assert_equal 'Only for loooooong credentials', @response.body, "Authentication failed for request header #{header} and long credentials" - end - end - - AUTH_HEADERS.each do |header| - test "unsuccessful authentication with #{header.downcase}" do - @request.env[header] = encode_credentials('h4x0r') - get :index - - assert_response :unauthorized - assert_equal "HTTP Token: Access denied.\n", @response.body, "Authentication didn't fail for request header #{header}" - end - test "unsuccessful authentication with #{header.downcase} and long credentials" do - @request.env[header] = encode_credentials('h4x0rh4x0rh4x0rh4x0rh4x0rh4x0rh4x0rh4x0r') - get :show - - assert_response :unauthorized - assert_equal "HTTP Token: Access denied.\n", @response.body, "Authentication didn't fail for request header #{header} and long credentials" - end - end - - test "authentication request without credential" do - get :display - - assert_response :unauthorized - assert_equal "HTTP Token: Access denied.\n", @response.body - assert_equal 'Token realm="SuperSecret"', @response.headers['WWW-Authenticate'] - end - - test "authentication request with invalid credential" do - @request.env['HTTP_AUTHORIZATION'] = encode_credentials('"quote" pretty') - get :display - - assert_response :unauthorized - assert_equal "HTTP Token: Access denied.\n", @response.body - assert_equal 'Token realm="SuperSecret"', @response.headers['WWW-Authenticate'] - end - - test "authentication request with valid credential" do - @request.env['HTTP_AUTHORIZATION'] = encode_credentials('"quote" pretty', :algorithm => 'test') - get :display - - assert_response :success - assert assigns(:logged_in) - assert_equal 'Definitely Maybe', @response.body - end - - private - - def encode_credentials(token, options = {}) - ActionController::HttpAuthentication::Token.encode_credentials(token, options) - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/integration_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/integration_test.rb deleted file mode 100644 index 46d53b772..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/integration_test.rb +++ /dev/null @@ -1,524 +0,0 @@ -require 'abstract_unit' -require 'controller/fake_controllers' -require 'action_controller/vendor/html-scanner' - -class SessionTest < Test::Unit::TestCase - StubApp = lambda { |env| - [200, {"Content-Type" => "text/html", "Content-Length" => "13"}, ["Hello, World!"]] - } - - def setup - @session = ActionController::Integration::Session.new(StubApp) - end - - def test_https_bang_works_and_sets_truth_by_default - assert !@session.https? - @session.https! - assert @session.https? - @session.https! false - assert !@session.https? - end - - def test_host! - assert_not_equal "glu.ttono.us", @session.host - @session.host! "rubyonrails.com" - assert_equal "rubyonrails.com", @session.host - end - - def test_follow_redirect_raises_when_no_redirect - @session.stubs(:redirect?).returns(false) - assert_raise(RuntimeError) { @session.follow_redirect! } - end - - def test_request_via_redirect_uses_given_method - path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue"} - @session.expects(:process).with(:put, path, args, headers) - @session.stubs(:redirect?).returns(false) - @session.request_via_redirect(:put, path, args, headers) - end - - def test_request_via_redirect_follows_redirects - path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue"} - @session.stubs(:redirect?).returns(true, true, false) - @session.expects(:follow_redirect!).times(2) - @session.request_via_redirect(:get, path, args, headers) - end - - def test_request_via_redirect_returns_status - path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue"} - @session.stubs(:redirect?).returns(false) - @session.stubs(:status).returns(200) - assert_equal 200, @session.request_via_redirect(:get, path, args, headers) - end - - def test_get_via_redirect - path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue" } - @session.expects(:request_via_redirect).with(:get, path, args, headers) - @session.get_via_redirect(path, args, headers) - end - - def test_post_via_redirect - path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue" } - @session.expects(:request_via_redirect).with(:post, path, args, headers) - @session.post_via_redirect(path, args, headers) - end - - def test_put_via_redirect - path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue" } - @session.expects(:request_via_redirect).with(:put, path, args, headers) - @session.put_via_redirect(path, args, headers) - end - - def test_delete_via_redirect - path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue" } - @session.expects(:request_via_redirect).with(:delete, path, args, headers) - @session.delete_via_redirect(path, args, headers) - end - - def test_get - path = "/index"; params = "blah"; headers = {:location => 'blah'} - @session.expects(:process).with(:get,path,params,headers) - @session.get(path,params,headers) - end - - def test_post - path = "/index"; params = "blah"; headers = {:location => 'blah'} - @session.expects(:process).with(:post,path,params,headers) - @session.post(path,params,headers) - end - - def test_put - path = "/index"; params = "blah"; headers = {:location => 'blah'} - @session.expects(:process).with(:put,path,params,headers) - @session.put(path,params,headers) - end - - def test_delete - path = "/index"; params = "blah"; headers = {:location => 'blah'} - @session.expects(:process).with(:delete,path,params,headers) - @session.delete(path,params,headers) - end - - def test_head - path = "/index"; params = "blah"; headers = {:location => 'blah'} - @session.expects(:process).with(:head,path,params,headers) - @session.head(path,params,headers) - end - - def test_xml_http_request_get - path = "/index"; params = "blah"; headers = {:location => 'blah'} - headers_after_xhr = headers.merge( - "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest", - "HTTP_ACCEPT" => "text/javascript, text/html, application/xml, text/xml, */*" - ) - @session.expects(:process).with(:get,path,params,headers_after_xhr) - @session.xml_http_request(:get,path,params,headers) - end - - def test_xml_http_request_post - path = "/index"; params = "blah"; headers = {:location => 'blah'} - headers_after_xhr = headers.merge( - "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest", - "HTTP_ACCEPT" => "text/javascript, text/html, application/xml, text/xml, */*" - ) - @session.expects(:process).with(:post,path,params,headers_after_xhr) - @session.xml_http_request(:post,path,params,headers) - end - - def test_xml_http_request_put - path = "/index"; params = "blah"; headers = {:location => 'blah'} - headers_after_xhr = headers.merge( - "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest", - "HTTP_ACCEPT" => "text/javascript, text/html, application/xml, text/xml, */*" - ) - @session.expects(:process).with(:put,path,params,headers_after_xhr) - @session.xml_http_request(:put,path,params,headers) - end - - def test_xml_http_request_delete - path = "/index"; params = "blah"; headers = {:location => 'blah'} - headers_after_xhr = headers.merge( - "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest", - "HTTP_ACCEPT" => "text/javascript, text/html, application/xml, text/xml, */*" - ) - @session.expects(:process).with(:delete,path,params,headers_after_xhr) - @session.xml_http_request(:delete,path,params,headers) - end - - def test_xml_http_request_head - path = "/index"; params = "blah"; headers = {:location => 'blah'} - headers_after_xhr = headers.merge( - "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest", - "HTTP_ACCEPT" => "text/javascript, text/html, application/xml, text/xml, */*" - ) - @session.expects(:process).with(:head,path,params,headers_after_xhr) - @session.xml_http_request(:head,path,params,headers) - end - - def test_xml_http_request_override_accept - path = "/index"; params = "blah"; headers = {:location => 'blah', "HTTP_ACCEPT" => "application/xml"} - headers_after_xhr = headers.merge( - "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest" - ) - @session.expects(:process).with(:post,path,params,headers_after_xhr) - @session.xml_http_request(:post,path,params,headers) - end -end - -class IntegrationTestTest < Test::Unit::TestCase - def setup - @test = ::ActionController::IntegrationTest.new(:default_test) - @test.class.stubs(:fixture_table_names).returns([]) - @session = @test.open_session - end - - def test_opens_new_session - session1 = @test.open_session { |sess| } - session2 = @test.open_session # implicit session - - assert_respond_to session1, :assert_template, "open_session makes assert_template available" - assert_respond_to session2, :assert_template, "open_session makes assert_template available" - assert !session1.equal?(session2) - end - - # RSpec mixes Matchers (which has a #method_missing) into - # IntegrationTest's superclass. Make sure IntegrationTest does not - # try to delegate these methods to the session object. - def test_does_not_prevent_method_missing_passing_up_to_ancestors - mixin = Module.new do - def method_missing(name, *args) - name.to_s == 'foo' ? 'pass' : super - end - end - @test.class.superclass.__send__(:include, mixin) - begin - assert_equal 'pass', @test.foo - ensure - # leave other tests as unaffected as possible - mixin.__send__(:remove_method, :method_missing) - end - end -end - -# Tests that integration tests don't call Controller test methods for processing. -# Integration tests have their own setup and teardown. -class IntegrationTestUsesCorrectClass < ActionController::IntegrationTest - def self.fixture_table_names - [] - end - - def test_integration_methods_called - reset! - @integration_session.stubs(:generic_url_rewriter) - @integration_session.stubs(:process) - - %w( get post head put delete ).each do |verb| - assert_nothing_raised("'#{verb}' should use integration test methods") { __send__(verb, '/') } - end - end -end - -class IntegrationProcessTest < ActionController::IntegrationTest - class IntegrationController < ActionController::Base - def get - respond_to do |format| - format.html { render :text => "OK", :status => 200 } - format.js { render :text => "JS OK", :status => 200 } - end - end - - def get_with_params - render :text => "foo: #{params[:foo]}", :status => 200 - end - - def post - render :text => "Created", :status => 201 - end - - def method - render :text => "method: #{request.method.downcase}" - end - - def cookie_monster - cookies["cookie_1"] = nil - cookies["cookie_3"] = "chocolate" - render :text => "Gone", :status => 410 - end - - def set_cookie - cookies["foo"] = 'bar' - head :ok - end - - def get_cookie - render :text => cookies["foo"] - end - - def redirect - redirect_to :action => "get" - end - end - - def test_get - with_test_route_set do - get '/get' - assert_equal 200, status - assert_equal "OK", status_message - assert_response 200 - assert_response :success - assert_response :ok - assert_equal({}, cookies.to_hash) - assert_equal "OK", body - assert_equal "OK", response.body - assert_kind_of HTML::Document, html_document - assert_equal 1, request_count - end - end - - def test_post - with_test_route_set do - post '/post' - assert_equal 201, status - assert_equal "Created", status_message - assert_response 201 - assert_response :success - assert_response :created - assert_equal({}, cookies.to_hash) - assert_equal "Created", body - assert_equal "Created", response.body - assert_kind_of HTML::Document, html_document - assert_equal 1, request_count - end - end - - test 'response cookies are added to the cookie jar for the next request' do - with_test_route_set do - self.cookies['cookie_1'] = "sugar" - self.cookies['cookie_2'] = "oatmeal" - get '/cookie_monster' - assert_equal "cookie_1=; path=/\ncookie_3=chocolate; path=/", headers["Set-Cookie"] - assert_equal({"cookie_1"=>"", "cookie_2"=>"oatmeal", "cookie_3"=>"chocolate"}, cookies.to_hash) - end - end - - test 'cookie persist to next request' do - with_test_route_set do - get '/set_cookie' - assert_response :success - - assert_equal "foo=bar; path=/", headers["Set-Cookie"] - assert_equal({"foo"=>"bar"}, cookies.to_hash) - - get '/get_cookie' - assert_response :success - assert_equal "bar", body - - assert_equal nil, headers["Set-Cookie"] - assert_equal({"foo"=>"bar"}, cookies.to_hash) - end - end - - test 'cookie persist to next request on another domain' do - with_test_route_set do - host! "37s.backpack.test" - - get '/set_cookie' - assert_response :success - - assert_equal "foo=bar; path=/", headers["Set-Cookie"] - assert_equal({"foo"=>"bar"}, cookies.to_hash) - - get '/get_cookie' - assert_response :success - assert_equal "bar", body - - assert_equal nil, headers["Set-Cookie"] - assert_equal({"foo"=>"bar"}, cookies.to_hash) - end - end - - def test_redirect - with_test_route_set do - get '/redirect' - assert_equal 302, status - assert_equal "Found", status_message - assert_response 302 - assert_response :redirect - assert_response :found - assert_equal "You are being redirected.", response.body - assert_kind_of HTML::Document, html_document - assert_equal 1, request_count - - follow_redirect! - assert_response :success - assert_equal "/get", path - end - end - - def test_xml_http_request_get - with_test_route_set do - xhr :get, '/get' - assert_equal 200, status - assert_equal "OK", status_message - assert_response 200 - assert_response :success - assert_response :ok - assert_equal "JS OK", response.body - end - end - - def test_get_with_query_string - with_test_route_set do - get '/get_with_params?foo=bar' - assert_equal '/get_with_params?foo=bar', request.env["REQUEST_URI"] - assert_equal '/get_with_params?foo=bar', request.fullpath - assert_equal "foo=bar", request.env["QUERY_STRING"] - assert_equal 'foo=bar', request.query_string - assert_equal 'bar', request.parameters['foo'] - - assert_equal 200, status - assert_equal "foo: bar", response.body - end - end - - def test_get_with_parameters - with_test_route_set do - get '/get_with_params', :foo => "bar" - assert_equal '/get_with_params', request.env["PATH_INFO"] - assert_equal '/get_with_params', request.path_info - assert_equal 'foo=bar', request.env["QUERY_STRING"] - assert_equal 'foo=bar', request.query_string - assert_equal 'bar', request.parameters['foo'] - - assert_equal 200, status - assert_equal "foo: bar", response.body - end - end - - def test_head - with_test_route_set do - head '/get' - assert_equal 200, status - assert_equal "", body - - head '/post' - assert_equal 201, status - assert_equal "", body - - get '/get/method' - assert_equal 200, status - assert_equal "method: get", body - - head '/get/method' - assert_equal 200, status - assert_equal "", body - end - end - - def test_generate_url_with_controller - assert_equal 'http://www.example.com/foo', url_for(:controller => "foo") - end - - private - def with_test_route_set - with_routing do |set| - controller = ::IntegrationProcessTest::IntegrationController.clone - controller.class_eval do - include set.url_helpers - end - - set.draw do |map| - match ':action', :to => controller - get 'get/:action', :to => controller - end - - self.singleton_class.send(:include, set.url_helpers) - - yield - end - end -end - -class MetalIntegrationTest < ActionController::IntegrationTest - include SharedTestRoutes.url_helpers - - class Poller - def self.call(env) - if env["PATH_INFO"] =~ /^\/success/ - [200, {"Content-Type" => "text/plain", "Content-Length" => "12"}, ["Hello World!"]] - else - [404, {"Content-Type" => "text/plain", "Content-Length" => "0"}, []] - end - end - end - - def setup - @app = Poller - end - - def test_successful_get - get "/success" - assert_response 200 - assert_response :success - assert_response :ok - assert_equal "Hello World!", response.body - end - - def test_failed_get - get "/failure" - assert_response 404 - assert_response :not_found - assert_equal '', response.body - end - - def test_generate_url_without_controller - assert_equal 'http://www.example.com/foo', url_for(:controller => "foo") - end -end - -class ApplicationIntegrationTest < ActionController::IntegrationTest - class TestController < ActionController::Base - def index - render :text => "index" - end - end - - def self.call(env) - routes.call(env) - end - - def self.routes - @routes ||= ActionDispatch::Routing::RouteSet.new - end - - routes.draw do - match 'foo', :to => 'application_integration_test/test#index', :as => :foo - match 'bar', :to => 'application_integration_test/test#index', :as => :bar - end - - def app - self.class - end - - test "includes route helpers" do - assert_equal '/foo', foo_path - assert_equal '/bar', bar_path - end - - test "route helpers after controller access" do - get '/foo' - assert_equal '/foo', foo_path - - get '/bar' - assert_equal '/bar', bar_path - end - - test "missing route helper before controller access" do - assert_raise(NameError) { missing_path } - end - - test "missing route helper after controller access" do - get '/foo' - assert_raise(NameError) { missing_path } - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/layout_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/layout_test.rb deleted file mode 100644 index 28bdda4e6..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/layout_test.rb +++ /dev/null @@ -1,224 +0,0 @@ -require 'abstract_unit' -require 'rbconfig' - -# The view_paths array must be set on Base and not LayoutTest so that LayoutTest's inherited -# method has access to the view_paths array when looking for a layout to automatically assign. -old_load_paths = ActionController::Base.view_paths - -ActionView::Template::register_template_handler :mab, - lambda { |template| template.source.inspect } - -ActionController::Base.view_paths = [ File.dirname(__FILE__) + '/../fixtures/layout_tests/' ] - -class LayoutTest < ActionController::Base - def self.controller_path; 'views' end - def self._implied_layout_name; to_s.underscore.gsub(/_controller$/, '') ; end - self.view_paths = ActionController::Base.view_paths.dup -end - -# Restore view_paths to previous value -ActionController::Base.view_paths = old_load_paths - -class ProductController < LayoutTest -end - -class ItemController < LayoutTest -end - -class ThirdPartyTemplateLibraryController < LayoutTest -end - -module ControllerNameSpace -end - -class ControllerNameSpace::NestedController < LayoutTest -end - -class MultipleExtensions < LayoutTest -end - -class LayoutAutoDiscoveryTest < ActionController::TestCase - def setup - super - @request.host = "www.nextangle.com" - end - - def test_application_layout_is_default_when_no_controller_match - @controller = ProductController.new - get :hello - assert_equal 'layout_test.rhtml hello.rhtml', @response.body - end - - def test_controller_name_layout_name_match - @controller = ItemController.new - get :hello - assert_equal 'item.rhtml hello.rhtml', @response.body - end - - def test_third_party_template_library_auto_discovers_layout - @controller = ThirdPartyTemplateLibraryController.new - get :hello - assert_response :success - assert_equal 'layouts/third_party_template_library.mab', @response.body - end - - def test_namespaced_controllers_auto_detect_layouts1 - @controller = ControllerNameSpace::NestedController.new - get :hello - assert_equal 'controller_name_space/nested.rhtml hello.rhtml', @response.body - end - - def test_namespaced_controllers_auto_detect_layouts2 - @controller = MultipleExtensions.new - get :hello - assert_equal 'multiple_extensions.html.erb hello.rhtml', @response.body.strip - end -end - -class DefaultLayoutController < LayoutTest -end - -class AbsolutePathLayoutController < LayoutTest - layout File.expand_path(File.expand_path(__FILE__) + '/../../fixtures/layout_tests/layouts/layout_test.rhtml') -end - -class HasOwnLayoutController < LayoutTest - layout 'item' -end - -class PrependsViewPathController < LayoutTest - def hello - prepend_view_path File.dirname(__FILE__) + '/../fixtures/layout_tests/alt/' - render :layout => 'alt' - end -end - -class OnlyLayoutController < LayoutTest - layout 'item', :only => "hello" -end - -class ExceptLayoutController < LayoutTest - layout 'item', :except => "goodbye" -end - -class SetsLayoutInRenderController < LayoutTest - def hello - render :layout => 'third_party_template_library' - end -end - -class RendersNoLayoutController < LayoutTest - def hello - render :layout => false - end -end - -class LayoutSetInResponseTest < ActionController::TestCase - include ActionView::Template::Handlers - - def test_layout_set_when_using_default_layout - @controller = DefaultLayoutController.new - get :hello - assert_template :layout => "layouts/layout_test" - end - - def test_layout_set_when_set_in_controller - @controller = HasOwnLayoutController.new - get :hello - assert_template :layout => "layouts/item" - end - - def test_layout_only_exception_when_included - @controller = OnlyLayoutController.new - get :hello - assert_template :layout => "layouts/item" - end - - def test_layout_only_exception_when_excepted - @controller = OnlyLayoutController.new - get :goodbye - assert !@response.body.include?("item.rhtml"), "#{@response.body.inspect} included 'item.rhtml'" - end - - def test_layout_except_exception_when_included - @controller = ExceptLayoutController.new - get :hello - assert_template :layout => "layouts/item" - end - - def test_layout_except_exception_when_excepted - @controller = ExceptLayoutController.new - get :goodbye - assert !@response.body.include?("item.rhtml"), "#{@response.body.inspect} included 'item.rhtml'" - end - - def test_layout_set_when_using_render - @controller = SetsLayoutInRenderController.new - get :hello - assert_template :layout => "layouts/third_party_template_library" - end - - def test_layout_is_not_set_when_none_rendered - @controller = RendersNoLayoutController.new - get :hello - assert_template :layout => nil - end - - def test_layout_is_picked_from_the_controller_instances_view_path - @controller = PrependsViewPathController.new - get :hello - assert_template :layout => /layouts\/alt\.\w+/ - end - - def test_absolute_pathed_layout - @controller = AbsolutePathLayoutController.new - get :hello - assert_equal "layout_test.rhtml hello.rhtml", @response.body.strip - end -end - -class RenderWithTemplateOptionController < LayoutTest - def hello - render :template => 'alt/hello' - end -end - -class SetsNonExistentLayoutFile < LayoutTest - layout "nofile.rhtml" -end - -class LayoutExceptionRaised < ActionController::TestCase - def test_exception_raised_when_layout_file_not_found - @controller = SetsNonExistentLayoutFile.new - assert_raise(ActionView::MissingTemplate) { get :hello } - end -end - -class LayoutStatusIsRendered < LayoutTest - def hello - render :status => 401 - end -end - -class LayoutStatusIsRenderedTest < ActionController::TestCase - def test_layout_status_is_rendered - @controller = LayoutStatusIsRendered.new - get :hello - assert_response 401 - end -end - -unless RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ - class LayoutSymlinkedTest < LayoutTest - layout "symlinked/symlinked_layout" - end - - class LayoutSymlinkedIsRenderedTest < ActionController::TestCase - def test_symlinked_layout_is_rendered - @controller = LayoutSymlinkedTest.new - get :hello - assert_response 200 - assert_template :layout => "layouts/symlinked/symlinked_layout" - end - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/localized_templates_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/localized_templates_test.rb deleted file mode 100644 index 6808f4114..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/localized_templates_test.rb +++ /dev/null @@ -1,22 +0,0 @@ -require 'abstract_unit' - -class LocalizedController < ActionController::Base - def hello_world - end -end - -class LocalizedTemplatesTest < ActionController::TestCase - tests LocalizedController - - def test_localized_template_is_used - I18n.locale = :de - get :hello_world - assert_equal "Gutten Tag", @response.body - end - - def test_default_locale_template_is_used_when_locale_is_missing - I18n.locale = :dk - get :hello_world - assert_equal "Hello World", @response.body - end -end \ No newline at end of file diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/log_subscriber_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/log_subscriber_test.rb deleted file mode 100644 index 7bb96399a..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/log_subscriber_test.rb +++ /dev/null @@ -1,172 +0,0 @@ -require "abstract_unit" -require "active_support/log_subscriber/test_helper" -require "action_controller/log_subscriber" - -module Another - class LogSubscribersController < ActionController::Base - def show - render :nothing => true - end - - def redirector - redirect_to "http://foo.bar/" - end - - def data_sender - send_data "cool data", :filename => "file.txt" - end - - def xfile_sender - send_file File.expand_path("company.rb", FIXTURE_LOAD_PATH), :x_sendfile => true - end - - def file_sender - send_file File.expand_path("company.rb", FIXTURE_LOAD_PATH) - end - - def with_fragment_cache - render :inline => "<%= cache('foo'){ 'bar' } %>" - end - - def with_page_cache - cache_page("Super soaker", "/index.html") - render :nothing => true - end - end -end - -class ACLogSubscriberTest < ActionController::TestCase - tests Another::LogSubscribersController - include ActiveSupport::LogSubscriber::TestHelper - - def setup - super - - @old_logger = ActionController::Base.logger - - @cache_path = File.expand_path('../temp/test_cache', File.dirname(__FILE__)) - ActionController::Base.page_cache_directory = @cache_path - @controller.cache_store = :file_store, @cache_path - ActionController::LogSubscriber.attach_to :action_controller - end - - def teardown - super - ActiveSupport::LogSubscriber.log_subscribers.clear - FileUtils.rm_rf(@cache_path) - ActionController::Base.logger = @old_logger - end - - def set_logger(logger) - ActionController::Base.logger = logger - end - - def test_start_processing - get :show - wait - assert_equal 2, logs.size - assert_equal "Processing by Another::LogSubscribersController#show as HTML", logs.first - end - - def test_process_action - get :show - wait - assert_equal 2, logs.size - assert_match /Completed/, logs.last - assert_match /200 OK/, logs.last - end - - def test_process_action_without_parameters - get :show - wait - assert_nil logs.detect {|l| l =~ /Parameters/ } - end - - def test_process_action_with_parameters - get :show, :id => '10' - wait - - assert_equal 3, logs.size - assert_equal 'Parameters: {"id"=>"10"}', logs[1] - end - - def test_process_action_with_view_runtime - get :show - wait - assert_match /\(Views: [\d\.]+ms\)/, logs[1] - end - - def test_process_action_with_filter_parameters - @request.env["action_dispatch.parameter_filter"] = [:lifo, :amount] - - get :show, :lifo => 'Pratik', :amount => '420', :step => '1' - wait - - params = logs[1] - assert_match /"amount"=>"\[FILTERED\]"/, params - assert_match /"lifo"=>"\[FILTERED\]"/, params - assert_match /"step"=>"1"/, params - end - - def test_redirect_to - get :redirector - wait - - assert_equal 3, logs.size - assert_equal "Redirected to http://foo.bar/", logs[1] - end - - def test_send_data - get :data_sender - wait - - assert_equal 3, logs.size - assert_match /Sent data file\.txt/, logs[1] - end - - def test_send_file - get :file_sender - wait - - assert_equal 3, logs.size - assert_match /Sent file/, logs[1] - assert_match /test\/fixtures\/company\.rb/, logs[1] - end - - def test_send_xfile - assert_deprecated { get :xfile_sender } - wait - - assert_equal 3, logs.size - assert_match /Sent file/, logs[1] - assert_match /test\/fixtures\/company\.rb/, logs[1] - end - - def test_with_fragment_cache - @controller.config.perform_caching = true - get :with_fragment_cache - wait - - assert_equal 4, logs.size - assert_match /Exist fragment\? views\/foo/, logs[1] - assert_match /Write fragment views\/foo/, logs[2] - ensure - @controller.config.perform_caching = true - end - - def test_with_page_cache - @controller.config.perform_caching = true - get :with_page_cache - wait - - assert_equal 3, logs.size - assert_match /Write page/, logs[1] - assert_match /\/index\.html/, logs[1] - ensure - @controller.config.perform_caching = true - end - - def logs - @logs ||= @logger.logged(:info) - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/mime_responds_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/mime_responds_test.rb deleted file mode 100644 index c209acbfa..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/mime_responds_test.rb +++ /dev/null @@ -1,941 +0,0 @@ -require 'abstract_unit' -require 'controller/fake_models' -require 'active_support/core_ext/hash/conversions' - -class RespondToController < ActionController::Base - layout :set_layout - - def html_xml_or_rss - respond_to do |type| - type.html { render :text => "HTML" } - type.xml { render :text => "XML" } - type.rss { render :text => "RSS" } - type.all { render :text => "Nothing" } - end - end - - def js_or_html - respond_to do |type| - type.html { render :text => "HTML" } - type.js { render :text => "JS" } - type.all { render :text => "Nothing" } - end - end - - def json_or_yaml - respond_to do |type| - type.json { render :text => "JSON" } - type.yaml { render :text => "YAML" } - end - end - - def html_or_xml - respond_to do |type| - type.html { render :text => "HTML" } - type.xml { render :text => "XML" } - type.all { render :text => "Nothing" } - end - end - - def json_xml_or_html - respond_to do |type| - type.json { render :text => 'JSON' } - type.xml { render :xml => 'XML' } - type.html { render :text => 'HTML' } - end - end - - - def forced_xml - request.format = :xml - - respond_to do |type| - type.html { render :text => "HTML" } - type.xml { render :text => "XML" } - end - end - - def just_xml - respond_to do |type| - type.xml { render :text => "XML" } - end - end - - def using_defaults - respond_to do |type| - type.html - type.js - type.xml - end - end - - def using_defaults_with_type_list - respond_to(:html, :js, :xml) - end - - def made_for_content_type - respond_to do |type| - type.rss { render :text => "RSS" } - type.atom { render :text => "ATOM" } - type.all { render :text => "Nothing" } - end - end - - def custom_type_handling - respond_to do |type| - type.html { render :text => "HTML" } - type.custom("application/crazy-xml") { render :text => "Crazy XML" } - type.all { render :text => "Nothing" } - end - end - - Mime::Type.register("text/x-mobile", :mobile) - - def custom_constant_handling - respond_to do |type| - type.html { render :text => "HTML" } - type.mobile { render :text => "Mobile" } - end - end - - def custom_constant_handling_without_block - respond_to do |type| - type.html { render :text => "HTML" } - type.mobile - end - end - - def handle_any - respond_to do |type| - type.html { render :text => "HTML" } - type.any(:js, :xml) { render :text => "Either JS or XML" } - end - end - - def handle_any_any - respond_to do |type| - type.html { render :text => 'HTML' } - type.any { render :text => 'Whatever you ask for, I got it' } - end - end - - def all_types_with_layout - respond_to do |type| - type.html - type.js - end - end - - Mime::Type.register_alias("text/html", :iphone) - - def iphone_with_html_response_type - request.format = :iphone if request.env["HTTP_ACCEPT"] == "text/iphone" - - respond_to do |type| - type.html { @type = "Firefox" } - type.iphone { @type = "iPhone" } - end - end - - def iphone_with_html_response_type_without_layout - request.format = "iphone" if request.env["HTTP_ACCEPT"] == "text/iphone" - - respond_to do |type| - type.html { @type = "Firefox"; render :action => "iphone_with_html_response_type" } - type.iphone { @type = "iPhone" ; render :action => "iphone_with_html_response_type" } - end - end - - def rescue_action(e) - raise - end - - protected - def set_layout - if ["all_types_with_layout", "iphone_with_html_response_type"].include?(action_name) - "respond_to/layouts/standard" - elsif action_name == "iphone_with_html_response_type_without_layout" - "respond_to/layouts/missing" - end - end -end - -class RespondToControllerTest < ActionController::TestCase - tests RespondToController - - def setup - super - @request.host = "www.example.com" - end - - def teardown - super - end - - def test_html - @request.accept = "text/html" - get :js_or_html - assert_equal 'HTML', @response.body - - get :html_or_xml - assert_equal 'HTML', @response.body - - get :just_xml - assert_response 406 - end - - def test_all - @request.accept = "*/*" - get :js_or_html - assert_equal 'HTML', @response.body # js is not part of all - - get :html_or_xml - assert_equal 'HTML', @response.body - - get :just_xml - assert_equal 'XML', @response.body - end - - def test_xml - @request.accept = "application/xml" - get :html_xml_or_rss - assert_equal 'XML', @response.body - end - - def test_js_or_html - @request.accept = "text/javascript, text/html" - xhr :get, :js_or_html - assert_equal 'JS', @response.body - - @request.accept = "text/javascript, text/html" - xhr :get, :html_or_xml - assert_equal 'HTML', @response.body - - @request.accept = "text/javascript, text/html" - xhr :get, :just_xml - assert_response 406 - end - - def test_json_or_yaml - xhr :get, :json_or_yaml - assert_equal 'JSON', @response.body - - get :json_or_yaml, :format => 'json' - assert_equal 'JSON', @response.body - - get :json_or_yaml, :format => 'yaml' - assert_equal 'YAML', @response.body - - { 'YAML' => %w(text/yaml), - 'JSON' => %w(application/json text/x-json) - }.each do |body, content_types| - content_types.each do |content_type| - @request.accept = content_type - get :json_or_yaml - assert_equal body, @response.body - end - end - end - - def test_js_or_anything - @request.accept = "text/javascript, */*" - xhr :get, :js_or_html - assert_equal 'JS', @response.body - - xhr :get, :html_or_xml - assert_equal 'HTML', @response.body - - xhr :get, :just_xml - assert_equal 'XML', @response.body - end - - def test_using_defaults - @request.accept = "*/*" - get :using_defaults - assert_equal "text/html", @response.content_type - assert_equal 'Hello world!', @response.body - - @request.accept = "text/javascript" - get :using_defaults - assert_equal "text/javascript", @response.content_type - assert_equal '$("body").visualEffect("highlight");', @response.body - - @request.accept = "application/xml" - get :using_defaults - assert_equal "application/xml", @response.content_type - assert_equal "

Hello world!

\n", @response.body - end - - def test_using_defaults_with_type_list - @request.accept = "*/*" - get :using_defaults_with_type_list - assert_equal "text/html", @response.content_type - assert_equal 'Hello world!', @response.body - - @request.accept = "text/javascript" - get :using_defaults_with_type_list - assert_equal "text/javascript", @response.content_type - assert_equal '$("body").visualEffect("highlight");', @response.body - - @request.accept = "application/xml" - get :using_defaults_with_type_list - assert_equal "application/xml", @response.content_type - assert_equal "

Hello world!

\n", @response.body - end - - def test_with_atom_content_type - @request.accept = "" - @request.env["CONTENT_TYPE"] = "application/atom+xml" - xhr :get, :made_for_content_type - assert_equal "ATOM", @response.body - end - - def test_with_rss_content_type - @request.accept = "" - @request.env["CONTENT_TYPE"] = "application/rss+xml" - xhr :get, :made_for_content_type - assert_equal "RSS", @response.body - end - - def test_synonyms - @request.accept = "application/javascript" - get :js_or_html - assert_equal 'JS', @response.body - - @request.accept = "application/x-xml" - get :html_xml_or_rss - assert_equal "XML", @response.body - end - - def test_custom_types - @request.accept = "application/crazy-xml" - get :custom_type_handling - assert_equal "application/crazy-xml", @response.content_type - assert_equal 'Crazy XML', @response.body - - @request.accept = "text/html" - get :custom_type_handling - assert_equal "text/html", @response.content_type - assert_equal 'HTML', @response.body - end - - def test_xhtml_alias - @request.accept = "application/xhtml+xml,application/xml" - get :html_or_xml - assert_equal 'HTML', @response.body - end - - def test_firefox_simulation - @request.accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5" - get :html_or_xml - assert_equal 'HTML', @response.body - end - - def test_handle_any - @request.accept = "*/*" - get :handle_any - assert_equal 'HTML', @response.body - - @request.accept = "text/javascript" - get :handle_any - assert_equal 'Either JS or XML', @response.body - - @request.accept = "text/xml" - get :handle_any - assert_equal 'Either JS or XML', @response.body - end - - def test_handle_any_any - @request.accept = "*/*" - get :handle_any_any - assert_equal 'HTML', @response.body - end - - def test_handle_any_any_parameter_format - get :handle_any_any, {:format=>'html'} - assert_equal 'HTML', @response.body - end - - def test_handle_any_any_explicit_html - @request.accept = "text/html" - get :handle_any_any - assert_equal 'HTML', @response.body - end - - def test_handle_any_any_javascript - @request.accept = "text/javascript" - get :handle_any_any - assert_equal 'Whatever you ask for, I got it', @response.body - end - - def test_handle_any_any_xml - @request.accept = "text/xml" - get :handle_any_any - assert_equal 'Whatever you ask for, I got it', @response.body - end - - def test_browser_check_with_any_any - @request.accept = "application/json, application/xml" - get :json_xml_or_html - assert_equal 'JSON', @response.body - - @request.accept = "application/json, application/xml, */*" - get :json_xml_or_html - assert_equal 'HTML', @response.body - end - - - def test_rjs_type_skips_layout - @request.accept = "text/javascript" - get :all_types_with_layout - assert_equal 'RJS for all_types_with_layout', @response.body - end - - def test_html_type_with_layout - @request.accept = "text/html" - get :all_types_with_layout - assert_equal '
HTML for all_types_with_layout
', @response.body - end - - def test_xhr - xhr :get, :js_or_html - assert_equal 'JS', @response.body - - xhr :get, :using_defaults - assert_equal '$("body").visualEffect("highlight");', @response.body - end - - def test_custom_constant - get :custom_constant_handling, :format => "mobile" - assert_equal "text/x-mobile", @response.content_type - assert_equal "Mobile", @response.body - end - - def test_custom_constant_handling_without_block - get :custom_constant_handling_without_block, :format => "mobile" - assert_equal "text/x-mobile", @response.content_type - assert_equal "Mobile", @response.body - end - - def test_forced_format - get :html_xml_or_rss - assert_equal "HTML", @response.body - - get :html_xml_or_rss, :format => "html" - assert_equal "HTML", @response.body - - get :html_xml_or_rss, :format => "xml" - assert_equal "XML", @response.body - - get :html_xml_or_rss, :format => "rss" - assert_equal "RSS", @response.body - end - - def test_internally_forced_format - get :forced_xml - assert_equal "XML", @response.body - - get :forced_xml, :format => "html" - assert_equal "XML", @response.body - end - - def test_extension_synonyms - get :html_xml_or_rss, :format => "xhtml" - assert_equal "HTML", @response.body - end - - def test_render_action_for_html - @controller.instance_eval do - def render(*args) - @action = args.first[:action] unless args.empty? - @action ||= action_name - - response.body = "#{@action} - #{formats}" - end - end - - get :using_defaults - assert_equal "using_defaults - #{[:html].to_s}", @response.body - - get :using_defaults, :format => "xml" - assert_equal "using_defaults - #{[:xml].to_s}", @response.body - end - - def test_format_with_custom_response_type - get :iphone_with_html_response_type - assert_equal '
Hello future from Firefox!
', @response.body - - get :iphone_with_html_response_type, :format => "iphone" - assert_equal "text/html", @response.content_type - assert_equal '
Hello iPhone future from iPhone!
', @response.body - end - - def test_format_with_custom_response_type_and_request_headers - @request.accept = "text/iphone" - get :iphone_with_html_response_type - assert_equal '
Hello iPhone future from iPhone!
', @response.body - assert_equal "text/html", @response.content_type - end -end - -class RespondWithController < ActionController::Base - respond_to :html, :json - respond_to :xml, :except => :using_resource_with_block - respond_to :js, :only => [ :using_resource_with_block, :using_resource ] - - def using_resource - respond_with(resource) - end - - def using_resource_with_block - respond_with(resource) do |format| - format.csv { render :text => "CSV" } - end - end - - def using_resource_with_overwrite_block - respond_with(resource) do |format| - format.html { render :text => "HTML" } - end - end - - def using_resource_with_collection - respond_with([resource, Customer.new("jamis", 9)]) - end - - def using_resource_with_parent - respond_with(Quiz::Store.new("developer?", 11), Customer.new("david", 13)) - end - - def using_resource_with_status_and_location - respond_with(resource, :location => "http://test.host/", :status => :created) - end - - def using_resource_with_responder - responder = proc { |c, r, o| c.render :text => "Resource name is #{r.first.name}" } - respond_with(resource, :responder => responder) - end - - def using_resource_with_action - respond_with(resource, :action => :foo) do |format| - format.html { raise ActionView::MissingTemplate.new([], "foo/bar", {}, false) } - end - end - - def using_responder_with_respond - responder = Class.new(ActionController::Responder) do - def respond; @controller.render :text => "respond #{format}"; end - end - respond_with(resource, :responder => responder) - end - -protected - - def resource - Customer.new("david", request.delete? ? nil : 13) - end - - def _render_js(js, options) - self.content_type ||= Mime::JS - self.response_body = js.respond_to?(:to_js) ? js.to_js : js - end -end - -class InheritedRespondWithController < RespondWithController - clear_respond_to - respond_to :xml, :json - - def index - respond_with(resource) do |format| - format.json { render :text => "JSON" } - end - end -end - -class EmptyRespondWithController < ActionController::Base - def index - respond_with(Customer.new("david", 13)) - end -end - -class RespondWithControllerTest < ActionController::TestCase - tests RespondWithController - - def setup - super - @request.host = "www.example.com" - end - - def teardown - super - end - - def test_using_resource - @request.accept = "text/javascript" - get :using_resource - assert_equal "text/javascript", @response.content_type - assert_equal '$("body").visualEffect("highlight");', @response.body - - @request.accept = "application/xml" - get :using_resource - assert_equal "application/xml", @response.content_type - assert_equal "david", @response.body - - @request.accept = "application/json" - assert_raise ActionView::MissingTemplate do - get :using_resource - end - end - - def test_using_resource_with_block - @request.accept = "*/*" - get :using_resource_with_block - assert_equal "text/html", @response.content_type - assert_equal 'Hello world!', @response.body - - @request.accept = "text/csv" - get :using_resource_with_block - assert_equal "text/csv", @response.content_type - assert_equal "CSV", @response.body - - @request.accept = "application/xml" - get :using_resource - assert_equal "application/xml", @response.content_type - assert_equal "david", @response.body - end - - def test_using_resource_with_overwrite_block - get :using_resource_with_overwrite_block - assert_equal "text/html", @response.content_type - assert_equal "HTML", @response.body - end - - def test_not_acceptable - @request.accept = "application/xml" - get :using_resource_with_block - assert_equal 406, @response.status - - @request.accept = "text/javascript" - get :using_resource_with_overwrite_block - assert_equal 406, @response.status - end - - def test_using_resource_for_post_with_html_redirects_on_success - with_test_route_set do - post :using_resource - assert_equal "text/html", @response.content_type - assert_equal 302, @response.status - assert_equal "http://www.example.com/customers/13", @response.location - assert @response.redirect? - end - end - - def test_using_resource_for_post_with_html_rerender_on_failure - with_test_route_set do - errors = { :name => :invalid } - Customer.any_instance.stubs(:errors).returns(errors) - post :using_resource - assert_equal "text/html", @response.content_type - assert_equal 200, @response.status - assert_equal "New world!\n", @response.body - assert_nil @response.location - end - end - - def test_using_resource_for_post_with_xml_yields_created_on_success - with_test_route_set do - @request.accept = "application/xml" - post :using_resource - assert_equal "application/xml", @response.content_type - assert_equal 201, @response.status - assert_equal "david", @response.body - assert_equal "http://www.example.com/customers/13", @response.location - end - end - - def test_using_resource_for_post_with_xml_yields_unprocessable_entity_on_failure - with_test_route_set do - @request.accept = "application/xml" - errors = { :name => :invalid } - Customer.any_instance.stubs(:errors).returns(errors) - post :using_resource - assert_equal "application/xml", @response.content_type - assert_equal 422, @response.status - assert_equal errors.to_xml, @response.body - assert_nil @response.location - end - end - - def test_using_resource_for_put_with_html_redirects_on_success - with_test_route_set do - put :using_resource - assert_equal "text/html", @response.content_type - assert_equal 302, @response.status - assert_equal "http://www.example.com/customers/13", @response.location - assert @response.redirect? - end - end - - def test_using_resource_for_put_with_html_rerender_on_failure - with_test_route_set do - errors = { :name => :invalid } - Customer.any_instance.stubs(:errors).returns(errors) - put :using_resource - assert_equal "text/html", @response.content_type - assert_equal 200, @response.status - assert_equal "Edit world!\n", @response.body - assert_nil @response.location - end - end - - def test_using_resource_for_put_with_html_rerender_on_failure_even_on_method_override - with_test_route_set do - errors = { :name => :invalid } - Customer.any_instance.stubs(:errors).returns(errors) - @request.env["rack.methodoverride.original_method"] = "POST" - put :using_resource - assert_equal "text/html", @response.content_type - assert_equal 200, @response.status - assert_equal "Edit world!\n", @response.body - assert_nil @response.location - end - end - - def test_using_resource_for_put_with_xml_yields_ok_on_success - @request.accept = "application/xml" - put :using_resource - assert_equal "application/xml", @response.content_type - assert_equal 200, @response.status - assert_equal " ", @response.body - end - - def test_using_resource_for_put_with_xml_yields_unprocessable_entity_on_failure - @request.accept = "application/xml" - errors = { :name => :invalid } - Customer.any_instance.stubs(:errors).returns(errors) - put :using_resource - assert_equal "application/xml", @response.content_type - assert_equal 422, @response.status - assert_equal errors.to_xml, @response.body - assert_nil @response.location - end - - def test_using_resource_for_delete_with_html_redirects_on_success - with_test_route_set do - Customer.any_instance.stubs(:destroyed?).returns(true) - delete :using_resource - assert_equal "text/html", @response.content_type - assert_equal 302, @response.status - assert_equal "http://www.example.com/customers", @response.location - end - end - - def test_using_resource_for_delete_with_xml_yields_ok_on_success - Customer.any_instance.stubs(:destroyed?).returns(true) - @request.accept = "application/xml" - delete :using_resource - assert_equal "application/xml", @response.content_type - assert_equal 200, @response.status - assert_equal " ", @response.body - end - - def test_using_resource_for_delete_with_html_redirects_on_failure - with_test_route_set do - errors = { :name => :invalid } - Customer.any_instance.stubs(:errors).returns(errors) - Customer.any_instance.stubs(:destroyed?).returns(false) - delete :using_resource - assert_equal "text/html", @response.content_type - assert_equal 302, @response.status - assert_equal "http://www.example.com/customers", @response.location - end - end - - def test_using_resource_with_parent_for_get - @request.accept = "application/xml" - get :using_resource_with_parent - assert_equal "application/xml", @response.content_type - assert_equal 200, @response.status - assert_equal "david", @response.body - end - - def test_using_resource_with_parent_for_post - with_test_route_set do - @request.accept = "application/xml" - - post :using_resource_with_parent - assert_equal "application/xml", @response.content_type - assert_equal 201, @response.status - assert_equal "david", @response.body - assert_equal "http://www.example.com/quiz_stores/11/customers/13", @response.location - - errors = { :name => :invalid } - Customer.any_instance.stubs(:errors).returns(errors) - post :using_resource - assert_equal "application/xml", @response.content_type - assert_equal 422, @response.status - assert_equal errors.to_xml, @response.body - assert_nil @response.location - end - end - - def test_using_resource_with_collection - @request.accept = "application/xml" - get :using_resource_with_collection - assert_equal "application/xml", @response.content_type - assert_equal 200, @response.status - assert_match /david<\/name>/, @response.body - assert_match /jamis<\/name>/, @response.body - end - - def test_using_resource_with_action - @controller.instance_eval do - def render(params={}) - self.response_body = "#{params[:action]} - #{formats}" - end - end - - errors = { :name => :invalid } - Customer.any_instance.stubs(:errors).returns(errors) - - post :using_resource_with_action - assert_equal "foo - #{[:html].to_s}", @controller.response.body - end - - def test_respond_as_responder_entry_point - @request.accept = "text/html" - get :using_responder_with_respond - assert_equal "respond html", @response.body - - @request.accept = "application/xml" - get :using_responder_with_respond - assert_equal "respond xml", @response.body - end - - def test_clear_respond_to - @controller = InheritedRespondWithController.new - @request.accept = "text/html" - get :index - assert_equal 406, @response.status - end - - def test_first_in_respond_to_has_higher_priority - @controller = InheritedRespondWithController.new - @request.accept = "*/*" - get :index - assert_equal "application/xml", @response.content_type - assert_equal "david", @response.body - end - - def test_block_inside_respond_with_is_rendered - @controller = InheritedRespondWithController.new - @request.accept = "application/json" - get :index - assert_equal "JSON", @response.body - end - - def test_no_double_render_is_raised - @request.accept = "text/html" - assert_raise ActionView::MissingTemplate do - get :using_resource - end - end - - def test_using_resource_with_status_and_location - @request.accept = "text/html" - post :using_resource_with_status_and_location - assert @response.redirect? - assert_equal "http://test.host/", @response.location - - @request.accept = "application/xml" - get :using_resource_with_status_and_location - assert_equal 201, @response.status - end - - def test_using_resource_with_responder - get :using_resource_with_responder - assert_equal "Resource name is david", @response.body - end - - def test_using_resource_with_set_responder - RespondWithController.responder = proc { |c, r, o| c.render :text => "Resource name is #{r.first.name}" } - get :using_resource - assert_equal "Resource name is david", @response.body - ensure - RespondWithController.responder = ActionController::Responder - end - - def test_error_is_raised_if_no_respond_to_is_declared_and_respond_with_is_called - @controller = EmptyRespondWithController.new - @request.accept = "*/*" - assert_raise RuntimeError do - get :index - end - end - - private - def with_test_route_set - with_routing do |set| - set.draw do |map| - resources :customers - resources :quiz_stores do - resources :customers - end - match ":controller/:action" - end - yield - end - end -end - -class AbstractPostController < ActionController::Base - self.view_paths = File.dirname(__FILE__) + "/../fixtures/post_test/" -end - -# For testing layouts which are set automatically -class PostController < AbstractPostController - around_filter :with_iphone - - def index - respond_to(:html, :iphone) - end - -protected - - def with_iphone - request.format = "iphone" if request.env["HTTP_ACCEPT"] == "text/iphone" - yield - end -end - -class SuperPostController < PostController -end - -class MimeControllerLayoutsTest < ActionController::TestCase - tests PostController - - def setup - super - @request.host = "www.example.com" - end - - def test_missing_layout_renders_properly - get :index - assert_equal '
Hello Firefox
', @response.body - - @request.accept = "text/iphone" - get :index - assert_equal 'Hello iPhone', @response.body - end - - def test_format_with_inherited_layouts - @controller = SuperPostController.new - - get :index - assert_equal '
Super Firefox
', @response.body - - @request.accept = "text/iphone" - get :index - assert_equal '
Super iPhone
', @response.body - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/bare_metal_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/bare_metal_test.rb deleted file mode 100644 index 575a1eba8..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/bare_metal_test.rb +++ /dev/null @@ -1,27 +0,0 @@ -require "abstract_unit" - -module BareMetalTest - class BareController < ActionController::Metal - def index - self.response_body = "Hello world" - end - end - - class BareTest < ActiveSupport::TestCase - test "response body is a Rack-compatible response" do - status, headers, body = BareController.action(:index).call(Rack::MockRequest.env_for("/")) - assert_equal 200, status - string = "" - - body.each do |part| - assert part.is_a?(String), "Each part of the body must be a String" - string << part - end - - assert_kind_of Hash, headers, "Headers must be a Hash" - assert headers["Content-Type"], "Content-Type must exist" - - assert_equal "Hello world", string - end - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/base_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/base_test.rb deleted file mode 100644 index 33bf4d849..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/base_test.rb +++ /dev/null @@ -1,132 +0,0 @@ -require 'abstract_unit' - -# Tests the controller dispatching happy path -module Dispatching - class SimpleController < ActionController::Base - before_filter :authenticate - - def index - render :text => "success" - end - - def modify_response_body - self.response_body = "success" - end - - def modify_response_body_twice - ret = (self.response_body = "success") - self.response_body = "#{ret}!" - end - - def modify_response_headers - end - - def show_actions - render :text => "actions: #{action_methods.to_a.sort.join(', ')}" - end - - protected - def authenticate - end - end - - class EmptyController < ActionController::Base ; end - class SubEmptyController < EmptyController ; end - class NonDefaultPathController < ActionController::Base - def self.controller_path; "i_am_not_default"; end - end - - module Submodule - class ContainedEmptyController < ActionController::Base ; end - class ContainedSubEmptyController < ContainedEmptyController ; end - class ContainedNonDefaultPathController < ActionController::Base - def self.controller_path; "i_am_extremly_not_default"; end - end - end - - class BaseTest < Rack::TestCase - # :api: plugin - test "simple dispatching" do - get "/dispatching/simple/index" - - assert_body "success" - assert_status 200 - assert_content_type "text/html; charset=utf-8" - end - - # :api: plugin - test "directly modifying response body" do - get "/dispatching/simple/modify_response_body" - - assert_body "success" - end - - # :api: plugin - test "directly modifying response body twice" do - get "/dispatching/simple/modify_response_body_twice" - - assert_body "success!" - end - - test "controller path" do - assert_equal 'dispatching/empty', EmptyController.controller_path - assert_equal EmptyController.controller_path, EmptyController.new.controller_path - end - - test "non-default controller path" do - assert_equal 'i_am_not_default', NonDefaultPathController.controller_path - assert_equal NonDefaultPathController.controller_path, NonDefaultPathController.new.controller_path - end - - test "sub controller path" do - assert_equal 'dispatching/sub_empty', SubEmptyController.controller_path - assert_equal SubEmptyController.controller_path, SubEmptyController.new.controller_path - end - - test "namespaced controller path" do - assert_equal 'dispatching/submodule/contained_empty', Submodule::ContainedEmptyController.controller_path - assert_equal Submodule::ContainedEmptyController.controller_path, Submodule::ContainedEmptyController.new.controller_path - end - - test "namespaced non-default controller path" do - assert_equal 'i_am_extremly_not_default', Submodule::ContainedNonDefaultPathController.controller_path - assert_equal Submodule::ContainedNonDefaultPathController.controller_path, Submodule::ContainedNonDefaultPathController.new.controller_path - end - - test "namespaced sub controller path" do - assert_equal 'dispatching/submodule/contained_sub_empty', Submodule::ContainedSubEmptyController.controller_path - assert_equal Submodule::ContainedSubEmptyController.controller_path, Submodule::ContainedSubEmptyController.new.controller_path - end - - test "controller name" do - assert_equal 'empty', EmptyController.controller_name - assert_equal 'contained_empty', Submodule::ContainedEmptyController.controller_name - end - - test "non-default path controller name" do - assert_equal 'non_default_path', NonDefaultPathController.controller_name - assert_equal 'contained_non_default_path', Submodule::ContainedNonDefaultPathController.controller_name - end - - test "sub controller name" do - assert_equal 'sub_empty', SubEmptyController.controller_name - assert_equal 'contained_sub_empty', Submodule::ContainedSubEmptyController.controller_name - end - - test "action methods" do - assert_equal Set.new(%w( - index - modify_response_headers - modify_response_body_twice - modify_response_body - show_actions - )), SimpleController.action_methods - - assert_equal Set.new, EmptyController.action_methods - assert_equal Set.new, Submodule::ContainedEmptyController.action_methods - - get "/dispatching/simple/show_actions" - assert_body "actions: index, modify_response_body, modify_response_body_twice, modify_response_headers, show_actions" - end - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/content_negotiation_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/content_negotiation_test.rb deleted file mode 100644 index 16639a84b..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/content_negotiation_test.rb +++ /dev/null @@ -1,18 +0,0 @@ -require 'abstract_unit' - -module ContentNegotiation - - # This has no layout and it works - class BasicController < ActionController::Base - self.view_paths = [ActionView::FixtureResolver.new( - "content_negotiation/basic/hello.html.erb" => "Hello world <%= request.formats.first.to_s %>!" - )] - end - - class TestContentNegotiation < Rack::TestCase - test "A */* Accept header will return HTML" do - get "/content_negotiation/basic/hello", {}, "HTTP_ACCEPT" => "*/*" - assert_body "Hello world */*!" - end - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/content_type_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/content_type_test.rb deleted file mode 100644 index 0d4f1b073..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/content_type_test.rb +++ /dev/null @@ -1,113 +0,0 @@ -require 'abstract_unit' - -module ContentType - class BaseController < ActionController::Base - def index - render :text => "Hello world!" - end - - def set_on_response_obj - response.content_type = Mime::RSS - render :text => "Hello world!" - end - - def set_on_render - render :text => "Hello world!", :content_type => Mime::RSS - end - end - - class ImpliedController < ActionController::Base - # Template's mime type is used if no content_type is specified - - self.view_paths = [ActionView::FixtureResolver.new( - "content_type/implied/i_am_html_erb.html.erb" => "Hello world!", - "content_type/implied/i_am_xml_erb.xml.erb" => "Hello world!", - "content_type/implied/i_am_html_builder.html.builder" => "xml.p 'Hello'", - "content_type/implied/i_am_xml_builder.xml.builder" => "xml.awesome 'Hello'", - "content_type/implied/i_am_js_rjs.js.rjs" => "page.alert 'hello'" - )] - end - - class CharsetController < ActionController::Base - def set_on_response_obj - response.charset = "utf-16" - render :text => "Hello world!" - end - - def set_as_nil_on_response_obj - response.charset = nil - render :text => "Hello world!" - end - end - - class ExplicitContentTypeTest < Rack::TestCase - test "default response is HTML and UTF8" do - get "/content_type/base" - - assert_body "Hello world!" - assert_header "Content-Type", "text/html; charset=utf-8" - end - - test "setting the content type of the response directly on the response object" do - get "/content_type/base/set_on_response_obj" - - assert_body "Hello world!" - assert_header "Content-Type", "application/rss+xml; charset=utf-8" - end - - test "setting the content type of the response as an option to render" do - get "/content_type/base/set_on_render" - - assert_body "Hello world!" - assert_header "Content-Type", "application/rss+xml; charset=utf-8" - end - end - - class ImpliedContentTypeTest < Rack::TestCase - test "sets Content-Type as text/html when rendering *.html.erb" do - get "/content_type/implied/i_am_html_erb" - - assert_header "Content-Type", "text/html; charset=utf-8" - end - - test "sets Content-Type as application/xml when rendering *.xml.erb" do - get "/content_type/implied/i_am_xml_erb", "format" => "xml" - - assert_header "Content-Type", "application/xml; charset=utf-8" - end - - test "sets Content-Type as text/html when rendering *.html.builder" do - get "/content_type/implied/i_am_html_builder" - - assert_header "Content-Type", "text/html; charset=utf-8" - end - - test "sets Content-Type as application/xml when rendering *.xml.builder" do - get "/content_type/implied/i_am_xml_builder", "format" => "xml" - - assert_header "Content-Type", "application/xml; charset=utf-8" - end - - test "sets Content-Type as text/javascript when rendering *.js" do - get "/content_type/implied/i_am_js_rjs", "format" => "js" - - assert_header "Content-Type", "text/javascript; charset=utf-8" - end - end - - class ExplicitCharsetTest < Rack::TestCase - test "setting the charset of the response directly on the response object" do - get "/content_type/charset/set_on_response_obj" - - assert_body "Hello world!" - assert_header "Content-Type", "text/html; charset=utf-16" - end - - test "setting the charset of the response as nil directly on the response object" do - get "/content_type/charset/set_as_nil_on_response_obj" - - assert_body "Hello world!" - assert_header "Content-Type", "text/html; charset=utf-8" - end - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/etag_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/etag_test.rb deleted file mode 100644 index 847b9feb0..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/etag_test.rb +++ /dev/null @@ -1,46 +0,0 @@ -require 'abstract_unit' - -module Etags - class BasicController < ActionController::Base - self.view_paths = [ActionView::FixtureResolver.new( - "etags/basic/base.html.erb" => "Hello from without_layout.html.erb", - "layouts/etags.html.erb" => "teh <%= yield %> tagz" - )] - - def without_layout - render :action => "base" - end - - def with_layout - render :action => "base", :layout => "etags" - end - end - - class EtagTest < Rack::TestCase - describe "Rendering without any special etag options returns an etag that is an MD5 hash of its text" - - test "an action without a layout" do - get "/etags/basic/without_layout" - - body = "Hello from without_layout.html.erb" - assert_body body - assert_header "Etag", etag_for(body) - assert_status 200 - end - - test "an action with a layout" do - get "/etags/basic/with_layout" - - body = "teh Hello from without_layout.html.erb tagz" - assert_body body - assert_header "Etag", etag_for(body) - assert_status 200 - end - - private - - def etag_for(text) - %("#{Digest::MD5.hexdigest(text)}") - end - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/metal_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/metal_test.rb deleted file mode 100644 index fbf5bb64f..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/metal_test.rb +++ /dev/null @@ -1,45 +0,0 @@ -require 'abstract_unit' - -module MetalTest - class MetalMiddleware < ActionController::Middleware - def call(env) - if env["PATH_INFO"] =~ /authed/ - app.call(env) - else - [401, headers, "Not authed!"] - end - end - end - - class Endpoint - def call(env) - [200, {}, "Hello World"] - end - end - - class TestMiddleware < ActiveSupport::TestCase - include RackTestUtils - - def setup - @app = Rack::Builder.new do - use MetalTest::MetalMiddleware - run MetalTest::Endpoint.new - end.to_app - end - - test "it can call the next app by using @app" do - env = Rack::MockRequest.env_for("/authed") - response = @app.call(env) - - assert_equal "Hello World", body_to_string(response[2]) - end - - test "it can return a response using the normal AC::Metal techniques" do - env = Rack::MockRequest.env_for("/") - response = @app.call(env) - - assert_equal "Not authed!", body_to_string(response[2]) - assert_equal 401, response[0] - end - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/middleware_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/middleware_test.rb deleted file mode 100644 index 8561ab3e4..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/middleware_test.rb +++ /dev/null @@ -1,88 +0,0 @@ -require 'abstract_unit' - -module MiddlewareTest - class MyMiddleware - def initialize(app) - @app = app - end - - def call(env) - result = @app.call(env) - result[1]["Middleware-Test"] = "Success" - result[1]["Middleware-Order"] = "First" - result - end - end - - class ExclaimerMiddleware - def initialize(app) - @app = app - end - - def call(env) - result = @app.call(env) - result[1]["Middleware-Order"] << "!" - result - end - end - - class MyController < ActionController::Metal - use MyMiddleware - middleware.insert_before MyMiddleware, ExclaimerMiddleware - - def index - self.response_body = "Hello World" - end - end - - class InheritedController < MyController - end - - class ActionsController < ActionController::Metal - use MyMiddleware, :only => :show - middleware.insert_before MyMiddleware, ExclaimerMiddleware, :except => :index - - def index - self.response_body = "index" - end - - def show - self.response_body = "show" - end - end - - class TestMiddleware < ActiveSupport::TestCase - def setup - @app = MyController.action(:index) - end - - test "middleware that is 'use'd is called as part of the Rack application" do - result = @app.call(env_for("/")) - assert_equal "Hello World", RackTestUtils.body_to_string(result[2]) - assert_equal "Success", result[1]["Middleware-Test"] - end - - test "the middleware stack is exposed as 'middleware' in the controller" do - result = @app.call(env_for("/")) - assert_equal "First!", result[1]["Middleware-Order"] - end - - test "middleware stack accepts only and except as options" do - result = ActionsController.action(:show).call(env_for("/")) - assert_equal "First!", result[1]["Middleware-Order"] - - result = ActionsController.action(:index).call(env_for("/")) - assert_nil result[1]["Middleware-Order"] - end - - def env_for(url) - Rack::MockRequest.env_for(url) - end - end - - class TestInheritedMiddleware < TestMiddleware - def setup - @app = InheritedController.action(:index) - end - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/render_action_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/render_action_test.rb deleted file mode 100644 index efeb6d6d2..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/render_action_test.rb +++ /dev/null @@ -1,320 +0,0 @@ -require 'abstract_unit' - -module RenderAction - # This has no layout and it works - class BasicController < ActionController::Base - self.view_paths = [ActionView::FixtureResolver.new( - "render_action/basic/hello_world.html.erb" => "Hello world!" - )] - - def hello_world - render :action => "hello_world" - end - - def hello_world_as_string - render "hello_world" - end - - def hello_world_as_string_with_options - render "hello_world", :status => 404 - end - - def hello_world_as_symbol - render :hello_world - end - - def hello_world_with_symbol - render :action => :hello_world - end - - def hello_world_with_layout - render :action => "hello_world", :layout => true - end - - def hello_world_with_layout_false - render :action => "hello_world", :layout => false - end - - def hello_world_with_layout_nil - render :action => "hello_world", :layout => nil - end - - def hello_world_with_custom_layout - render :action => "hello_world", :layout => "greetings" - end - - end - - class RenderActionTest < Rack::TestCase - test "rendering an action using :action => " do - get "/render_action/basic/hello_world" - - assert_body "Hello world!" - assert_status 200 - end - - test "rendering an action using ''" do - get "/render_action/basic/hello_world_as_string" - - assert_body "Hello world!" - assert_status 200 - end - - test "rendering an action using '' and options" do - get "/render_action/basic/hello_world_as_string_with_options" - - assert_body "Hello world!" - assert_status 404 - end - - test "rendering an action using :action" do - get "/render_action/basic/hello_world_as_symbol" - - assert_body "Hello world!" - assert_status 200 - end - - test "rendering an action using :action => :hello_world" do - get "/render_action/basic/hello_world_with_symbol" - - assert_body "Hello world!" - assert_status 200 - end - end - - class RenderLayoutTest < Rack::TestCase - describe "Both .html.erb and application.html.erb are missing" - - test "rendering with layout => true" do - assert_raise(ArgumentError) do - get "/render_action/basic/hello_world_with_layout", {}, "action_dispatch.show_exceptions" => false - end - end - - test "rendering with layout => false" do - get "/render_action/basic/hello_world_with_layout_false" - - assert_body "Hello world!" - assert_status 200 - end - - test "rendering with layout => :nil" do - get "/render_action/basic/hello_world_with_layout_nil" - - assert_body "Hello world!" - assert_status 200 - end - - test "rendering with layout => 'greetings'" do - assert_raise(ActionView::MissingTemplate) do - get "/render_action/basic/hello_world_with_custom_layout", {}, "action_dispatch.show_exceptions" => false - end - end - end -end - -module RenderActionWithApplicationLayout - # # ==== Render actions with layouts ==== - class BasicController < ::ApplicationController - # Set the view path to an application view structure with layouts - self.view_paths = [ActionView::FixtureResolver.new( - "render_action_with_application_layout/basic/hello_world.html.erb" => "Hello World!", - "render_action_with_application_layout/basic/hello.html.builder" => "xml.p 'Hello'", - "layouts/application.html.erb" => "Hi <%= yield %> OK, Bye", - "layouts/greetings.html.erb" => "Greetings <%= yield %> Bye", - "layouts/builder.html.builder" => "xml.html do\n xml << yield\nend" - )] - - def hello_world - render :action => "hello_world" - end - - def hello_world_with_layout - render :action => "hello_world", :layout => true - end - - def hello_world_with_layout_false - render :action => "hello_world", :layout => false - end - - def hello_world_with_layout_nil - render :action => "hello_world", :layout => nil - end - - def hello_world_with_custom_layout - render :action => "hello_world", :layout => "greetings" - end - - def with_builder_and_layout - render :action => "hello", :layout => "builder" - end - end - - class LayoutTest < Rack::TestCase - describe "Only application.html.erb is present and .html.erb is missing" - - test "rendering implicit application.html.erb as layout" do - get "/render_action_with_application_layout/basic/hello_world" - - assert_body "Hi Hello World! OK, Bye" - assert_status 200 - end - - test "rendering with layout => true" do - get "/render_action_with_application_layout/basic/hello_world_with_layout" - - assert_body "Hi Hello World! OK, Bye" - assert_status 200 - end - - test "rendering with layout => false" do - get "/render_action_with_application_layout/basic/hello_world_with_layout_false" - - assert_body "Hello World!" - assert_status 200 - end - - test "rendering with layout => :nil" do - get "/render_action_with_application_layout/basic/hello_world_with_layout_nil" - - assert_body "Hello World!" - assert_status 200 - end - - test "rendering with layout => 'greetings'" do - get "/render_action_with_application_layout/basic/hello_world_with_custom_layout" - - assert_body "Greetings Hello World! Bye" - assert_status 200 - end - end - - class TestLayout < Rack::TestCase - testing BasicController - - test "builder works with layouts" do - get :with_builder_and_layout - assert_response "\n

Hello

\n\n" - end - end - -end - -module RenderActionWithControllerLayout - class BasicController < ActionController::Base - self.view_paths = [ActionView::FixtureResolver.new( - "render_action_with_controller_layout/basic/hello_world.html.erb" => "Hello World!", - "layouts/render_action_with_controller_layout/basic.html.erb" => "With Controller Layout! <%= yield %> Bye" - )] - - def hello_world - render :action => "hello_world" - end - - def hello_world_with_layout - render :action => "hello_world", :layout => true - end - - def hello_world_with_layout_false - render :action => "hello_world", :layout => false - end - - def hello_world_with_layout_nil - render :action => "hello_world", :layout => nil - end - - def hello_world_with_custom_layout - render :action => "hello_world", :layout => "greetings" - end - end - - class ControllerLayoutTest < Rack::TestCase - describe "Only .html.erb is present and application.html.erb is missing" - - test "render hello_world and implicitly use .html.erb as a layout." do - get "/render_action_with_controller_layout/basic/hello_world" - - assert_body "With Controller Layout! Hello World! Bye" - assert_status 200 - end - - test "rendering with layout => true" do - get "/render_action_with_controller_layout/basic/hello_world_with_layout" - - assert_body "With Controller Layout! Hello World! Bye" - assert_status 200 - end - - test "rendering with layout => false" do - get "/render_action_with_controller_layout/basic/hello_world_with_layout_false" - - assert_body "Hello World!" - assert_status 200 - end - - test "rendering with layout => :nil" do - get "/render_action_with_controller_layout/basic/hello_world_with_layout_nil" - - assert_body "Hello World!" - assert_status 200 - end - end -end - -module RenderActionWithBothLayouts - class BasicController < ActionController::Base - self.view_paths = [ActionView::FixtureResolver.new({ - "render_action_with_both_layouts/basic/hello_world.html.erb" => "Hello World!", - "layouts/application.html.erb" => "Oh Hi <%= yield %> Bye", - "layouts/render_action_with_both_layouts/basic.html.erb" => "With Controller Layout! <%= yield %> Bye" - })] - - def hello_world - render :action => "hello_world" - end - - def hello_world_with_layout - render :action => "hello_world", :layout => true - end - - def hello_world_with_layout_false - render :action => "hello_world", :layout => false - end - - def hello_world_with_layout_nil - render :action => "hello_world", :layout => nil - end - end - - class ControllerLayoutTest < Rack::TestCase - describe "Both .html.erb and application.html.erb are present" - - test "rendering implicitly use .html.erb over application.html.erb as a layout" do - get "/render_action_with_both_layouts/basic/hello_world" - - assert_body "With Controller Layout! Hello World! Bye" - assert_status 200 - end - - test "rendering with layout => true" do - get "/render_action_with_both_layouts/basic/hello_world_with_layout" - - assert_body "With Controller Layout! Hello World! Bye" - assert_status 200 - end - - test "rendering with layout => false" do - get "/render_action_with_both_layouts/basic/hello_world_with_layout_false" - - assert_body "Hello World!" - assert_status 200 - end - - test "rendering with layout => :nil" do - get "/render_action_with_both_layouts/basic/hello_world_with_layout_nil" - - assert_body "Hello World!" - assert_status 200 - end - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/render_file_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/render_file_test.rb deleted file mode 100644 index fce10210c..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/render_file_test.rb +++ /dev/null @@ -1,99 +0,0 @@ -require 'abstract_unit' - -module RenderFile - class BasicController < ActionController::Base - self.view_paths = File.dirname(__FILE__) - - def index - render :file => File.join(File.dirname(__FILE__), *%w[.. .. fixtures test hello_world]) - end - - def with_instance_variables - @secret = 'in the sauce' - render :file => File.join(File.dirname(__FILE__), '../../fixtures/test/render_file_with_ivar.erb') - end - - def without_file_key - render File.join(File.dirname(__FILE__), *%w[.. .. fixtures test hello_world]) - end - - def without_file_key_with_instance_variable - @secret = 'in the sauce' - render File.join(File.dirname(__FILE__), '../../fixtures/test/render_file_with_ivar.erb') - end - - def relative_path - @secret = 'in the sauce' - render :file => '../../fixtures/test/render_file_with_ivar' - end - - def relative_path_with_dot - @secret = 'in the sauce' - render :file => '../../fixtures/test/dot.directory/render_file_with_ivar' - end - - def pathname - @secret = 'in the sauce' - render :file => Pathname.new(File.dirname(__FILE__)).join(*%w[.. .. fixtures test dot.directory render_file_with_ivar.erb]) - end - - def with_locals - path = File.join(File.dirname(__FILE__), '../../fixtures/test/render_file_with_locals.erb') - render :file => path, :locals => {:secret => 'in the sauce'} - end - - def without_file_key_with_locals - path = FIXTURES.join('test/render_file_with_locals.erb').to_s - render path, :locals => {:secret => 'in the sauce'} - end - end - - class TestBasic < Rack::TestCase - testing RenderFile::BasicController - - test "rendering simple template" do - get :index - assert_response "Hello world!" - end - - test "rendering template with ivar" do - get :with_instance_variables - assert_response "The secret is in the sauce\n" - end - - test "rendering path without specifying the :file key" do - get :without_file_key - assert_response "Hello world!" - end - - test "rendering path without specifying the :file key with ivar" do - get :without_file_key_with_instance_variable - assert_response "The secret is in the sauce\n" - end - - test "rendering a relative path" do - get :relative_path - assert_response "The secret is in the sauce\n" - end - - test "rendering a relative path with dot" do - get :relative_path_with_dot - assert_response "The secret is in the sauce\n" - end - - test "rendering a Pathname" do - get :pathname - assert_response "The secret is in the sauce\n" - end - - test "rendering file with locals" do - get :with_locals - assert_response "The secret is in the sauce\n" - end - - test "rendering path without specifying the :file key with locals" do - get :without_file_key_with_locals - assert_response "The secret is in the sauce\n" - end - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/render_implicit_action_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/render_implicit_action_test.rb deleted file mode 100644 index 67a690fab..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/render_implicit_action_test.rb +++ /dev/null @@ -1,28 +0,0 @@ -require 'abstract_unit' - -module RenderImplicitAction - class SimpleController < ::ApplicationController - self.view_paths = [ActionView::FixtureResolver.new( - "render_implicit_action/simple/hello_world.html.erb" => "Hello world!", - "render_implicit_action/simple/hyphen-ated.html.erb" => "Hello hyphen-ated!" - )] - - def hello_world() end - end - - class RenderImplicitActionTest < Rack::TestCase - test "render a simple action with new explicit call to render" do - get "/render_implicit_action/simple/hello_world" - - assert_body "Hello world!" - assert_status 200 - end - - test "render an action with a missing method and has special characters" do - get "/render_implicit_action/simple/hyphen-ated" - - assert_body "Hello hyphen-ated!" - assert_status 200 - end - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/render_layout_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/render_layout_test.rb deleted file mode 100644 index a5b9d69f3..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/render_layout_test.rb +++ /dev/null @@ -1,101 +0,0 @@ -require 'abstract_unit' - -module ControllerLayouts - class ImplicitController < ::ApplicationController - self.view_paths = [ActionView::FixtureResolver.new( - "layouts/application.html.erb" => "Main <%= yield %> Layout", - "layouts/override.html.erb" => "Override! <%= yield %>", - "basic.html.erb" => "Hello world!", - "controller_layouts/implicit/layout_false.html.erb" => "hi(layout_false.html.erb)" - )] - - def index - render :template => "basic" - end - - def override - render :template => "basic", :layout => "override" - end - - def layout_false - render :layout => false - end - - def builder_override - end - end - - class ImplicitNameController < ::ApplicationController - self.view_paths = [ActionView::FixtureResolver.new( - "layouts/controller_layouts/implicit_name.html.erb" => "Implicit <%= yield %> Layout", - "basic.html.erb" => "Hello world!" - )] - - def index - render :template => "basic" - end - end - - class RenderLayoutTest < Rack::TestCase - test "rendering a normal template, but using the implicit layout" do - get "/controller_layouts/implicit/index" - - assert_body "Main Hello world! Layout" - assert_status 200 - end - - test "rendering a normal template, but using an implicit NAMED layout" do - get "/controller_layouts/implicit_name/index" - - assert_body "Implicit Hello world! Layout" - assert_status 200 - end - - test "overriding an implicit layout with render :layout option" do - get "/controller_layouts/implicit/override" - assert_body "Override! Hello world!" - end - - end - - class LayoutOptionsTest < Rack::TestCase - testing ControllerLayouts::ImplicitController - - test "rendering with :layout => false leaves out the implicit layout" do - get :layout_false - assert_response "hi(layout_false.html.erb)" - end - end - - class MismatchFormatController < ::ApplicationController - self.view_paths = [ActionView::FixtureResolver.new( - "layouts/application.html.erb" => "<%= yield %>", - "controller_layouts/mismatch_format/index.js.rjs" => "page[:test].ext", - "controller_layouts/mismatch_format/implicit.rjs" => "page[:test].ext" - )] - - def explicit - render :layout => "application" - end - end - - class MismatchFormatTest < Rack::TestCase - testing ControllerLayouts::MismatchFormatController - - test "if JS is selected, an HTML template is not also selected" do - get :index, "format" => "js" - assert_response "$(\"test\").ext();" - end - - test "if JS is implicitly selected, an HTML template is not also selected" do - get :implicit - assert_response "$(\"test\").ext();" - end - - test "if an HTML template is explicitly provides for a JS template, an error is raised" do - assert_raises ActionView::MissingTemplate do - get :explicit, {}, "action_dispatch.show_exceptions" => false - end - end - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/render_partial_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/render_partial_test.rb deleted file mode 100644 index 53b76248f..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/render_partial_test.rb +++ /dev/null @@ -1,27 +0,0 @@ -require 'abstract_unit' - -module RenderPartial - - class BasicController < ActionController::Base - - self.view_paths = [ActionView::FixtureResolver.new( - "render_partial/basic/_basic.html.erb" => "BasicPartial!", - "render_partial/basic/basic.html.erb" => "<%= @test_unchanged = 'goodbye' %><%= render :partial => 'basic' %><%= @test_unchanged %>" - )] - - def changing - @test_unchanged = 'hello' - render :action => "basic" - end - end - - class TestPartial < Rack::TestCase - testing BasicController - - test "rendering a partial in ActionView doesn't pull the ivars again from the controller" do - get :changing - assert_response("goodbyeBasicPartial!goodbye") - end - end - -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/render_rjs_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/render_rjs_test.rb deleted file mode 100644 index a6f195a0a..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/render_rjs_test.rb +++ /dev/null @@ -1,71 +0,0 @@ -require 'abstract_unit' - -module RenderRjs - class BasicController < ActionController::Base - layout "application", :only => :index_respond_to - - self.view_paths = [ActionView::FixtureResolver.new( - "layouts/application.html.erb" => "", - "render_rjs/basic/index.js.rjs" => "page[:customer].replace_html render(:partial => 'customer')", - "render_rjs/basic/index_html.js.rjs" => "page[:customer].replace_html :partial => 'customer'", - "render_rjs/basic/index_no_js.js.erb" => "<%= render(:partial => 'developer') %>", - "render_rjs/basic/_customer.js.erb" => "JS Partial", - "render_rjs/basic/_customer.html.erb" => "HTML Partial", - "render_rjs/basic/_developer.html.erb" => "HTML Partial", - "render_rjs/basic/index_locale.js.rjs" => "page[:customer].replace_html :partial => 'customer'", - "render_rjs/basic/_customer.da.html.erb" => "Danish HTML Partial", - "render_rjs/basic/_customer.da.js.erb" => "Danish JS Partial" - )] - - def index - render - end - - def index_respond_to - respond_to do |format| - format.js { render :action => "index_no_js" } - end - end - - def index_locale - self.locale = :da - end - end - - class TestBasic < Rack::TestCase - testing BasicController - - def setup - @old_locale = I18n.locale - end - - def teardown - I18n.locale = @old_locale - end - - test "rendering a partial in an RJS template should pick the JS template over the HTML one" do - get :index, "format" => "js" - assert_response("$(\"customer\").update(\"JS Partial\");") - end - - test "rendering a partial in an RJS template should pick the HTML one if no JS is available" do - get :index_no_js, "format" => "js" - assert_response("HTML Partial") - end - - test "rendering a partial in an RJS template should pick the HTML one if no JS is available on respond_to" do - get :index_respond_to, "format" => "js" - assert_response("HTML Partial") - end - - test "replacing an element with a partial in an RJS template should pick the HTML template over the JS one" do - get :index_html, "format" => "js" - assert_response("$(\"customer\").update(\"HTML Partial\");") - end - - test "replacing an element with a partial in an RJS template with a locale should pick the localed HTML template" do - get :index_locale, "format" => "js" - assert_response("$(\"customer\").update(\"Danish HTML Partial\");") - end - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/render_template_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/render_template_test.rb deleted file mode 100644 index db7aba669..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/render_template_test.rb +++ /dev/null @@ -1,182 +0,0 @@ -require 'abstract_unit' - -module RenderTemplate - class WithoutLayoutController < ActionController::Base - - self.view_paths = [ActionView::FixtureResolver.new( - "test/basic.html.erb" => "Hello from basic.html.erb", - "shared.html.erb" => "Elastica", - "locals.html.erb" => "The secret is <%= secret %>", - "xml_template.xml.builder" => "xml.html do\n xml.p 'Hello'\nend", - "with_raw.html.erb" => "Hello <%=raw 'this is raw' %>" - )] - - def index - render :template => "test/basic" - end - - def index_without_key - render "test/basic" - end - - def in_top_directory - render :template => 'shared' - end - - def in_top_directory_with_slash - render :template => '/shared' - end - - def in_top_directory_with_slash_without_key - render '/shared' - end - - def with_locals - render :template => "locals", :locals => { :secret => 'area51' } - end - - def builder_template - render :template => "xml_template" - end - - def with_raw - render :template => "with_raw" - end - end - - class TestWithoutLayout < Rack::TestCase - testing RenderTemplate::WithoutLayoutController - - test "rendering a normal template with full path without layout" do - get :index - assert_response "Hello from basic.html.erb" - end - - test "rendering a normal template with full path without layout without key" do - get :index_without_key - assert_response "Hello from basic.html.erb" - end - - test "rendering a template not in a subdirectory" do - get :in_top_directory - assert_response "Elastica" - end - - test "rendering a template not in a subdirectory with a leading slash" do - get :in_top_directory_with_slash - assert_response "Elastica" - end - - test "rendering a template not in a subdirectory with a leading slash without key" do - get :in_top_directory_with_slash_without_key - assert_response "Elastica" - end - - test "rendering a template with local variables" do - get :with_locals - assert_response "The secret is area51" - end - - test "rendering a builder template" do - get :builder_template, "format" => "xml" - assert_response "\n

Hello

\n\n" - end - - test "rendering a template with <%=raw stuff %>" do - get :with_raw - - assert_body "Hello this is raw" - assert_status 200 - end - end - - class WithLayoutController < ::ApplicationController - self.view_paths = [ActionView::FixtureResolver.new( - "test/basic.html.erb" => "Hello from basic.html.erb", - "shared.html.erb" => "Elastica", - "layouts/application.html.erb" => "<%= yield %>, I'm here!", - "layouts/greetings.html.erb" => "<%= yield %>, I wish thee well." - )] - - def index - render :template => "test/basic" - end - - def with_layout - render :template => "test/basic", :layout => true - end - - def with_layout_false - render :template => "test/basic", :layout => false - end - - def with_layout_nil - render :template => "test/basic", :layout => nil - end - - def with_custom_layout - render :template => "test/basic", :layout => "greetings" - end - end - - class TestWithLayout < Rack::TestCase - describe "Rendering with :template using implicit or explicit layout" - - test "rendering with implicit layout" do - get "/render_template/with_layout" - - assert_body "Hello from basic.html.erb, I'm here!" - assert_status 200 - end - - test "rendering with layout => :true" do - get "/render_template/with_layout/with_layout" - - assert_body "Hello from basic.html.erb, I'm here!" - assert_status 200 - end - - test "rendering with layout => :false" do - get "/render_template/with_layout/with_layout_false" - - assert_body "Hello from basic.html.erb" - assert_status 200 - end - - test "rendering with layout => :nil" do - get "/render_template/with_layout/with_layout_nil" - - assert_body "Hello from basic.html.erb" - assert_status 200 - end - - test "rendering layout => 'greetings'" do - get "/render_template/with_layout/with_custom_layout" - - assert_body "Hello from basic.html.erb, I wish thee well." - assert_status 200 - end - end - - module Compatibility - class WithoutLayoutController < ActionController::Base - self.view_paths = [ActionView::FixtureResolver.new( - "test/basic.html.erb" => "Hello from basic.html.erb", - "shared.html.erb" => "Elastica" - )] - - def with_forward_slash - render :template => "/test/basic" - end - end - - class TestTemplateRenderWithForwardSlash < Rack::TestCase - test "rendering a normal template with full path starting with a leading slash" do - get "/render_template/compatibility/without_layout/with_forward_slash" - - assert_body "Hello from basic.html.erb" - assert_status 200 - end - end - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/render_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/render_test.rb deleted file mode 100644 index 717cd5e92..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/render_test.rb +++ /dev/null @@ -1,85 +0,0 @@ -require 'abstract_unit' - -module Render - class BlankRenderController < ActionController::Base - self.view_paths = [ActionView::FixtureResolver.new( - "render/blank_render/index.html.erb" => "Hello world!", - "render/blank_render/access_request.html.erb" => "The request: <%= request.method.to_s.upcase %>", - "render/blank_render/access_action_name.html.erb" => "Action Name: <%= action_name %>", - "render/blank_render/access_controller_name.html.erb" => "Controller Name: <%= controller_name %>" - )] - - def index - render - end - - def access_request - render :action => "access_request" - end - - def render_action_name - render :action => "access_action_name" - end - - private - - def secretz - render :text => "FAIL WHALE!" - end - end - - class DoubleRenderController < ActionController::Base - def index - render :text => "hello" - render :text => "world" - end - end - - class RenderTest < Rack::TestCase - test "render with blank" do - get "/render/blank_render" - - assert_body "Hello world!" - assert_status 200 - end - - test "rendering more than once raises an exception" do - assert_raises(AbstractController::DoubleRenderError) do - get "/render/double_render", {}, "action_dispatch.show_exceptions" => false - end - end - end - - class TestOnlyRenderPublicActions < Rack::TestCase - describe "Only public methods on actual controllers are callable actions" - - test "raises an exception when a method of Object is called" do - assert_raises(AbstractController::ActionNotFound) do - get "/render/blank_render/clone", {}, "action_dispatch.show_exceptions" => false - end - end - - test "raises an exception when a private method is called" do - assert_raises(AbstractController::ActionNotFound) do - get "/render/blank_render/secretz", {}, "action_dispatch.show_exceptions" => false - end - end - end - - class TestVariousObjectsAvailableInView < Rack::TestCase - test "The request object is accessible in the view" do - get "/render/blank_render/access_request" - assert_body "The request: GET" - end - - test "The action_name is accessible in the view" do - get "/render/blank_render/render_action_name" - assert_body "Action Name: render_action_name" - end - - test "The controller_name is accessible in the view" do - get "/render/blank_render/access_controller_name" - assert_body "Controller Name: blank_render" - end - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/render_text_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/render_text_test.rb deleted file mode 100644 index 11c3f1193..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/render_text_test.rb +++ /dev/null @@ -1,137 +0,0 @@ -require 'abstract_unit' - -module RenderText - class SimpleController < ActionController::Base - self.view_paths = [ActionView::FixtureResolver.new] - - def index - render :text => "hello david" - end - end - - class WithLayoutController < ::ApplicationController - self.view_paths = [ActionView::FixtureResolver.new( - "layouts/application.html.erb" => "<%= yield %>, I'm here!", - "layouts/greetings.html.erb" => "<%= yield %>, I wish thee well.", - "layouts/ivar.html.erb" => "<%= yield %>, <%= @ivar %>" - )] - - def index - render :text => "hello david" - end - - def custom_code - render :text => "hello world", :status => 404 - end - - def with_custom_code_as_string - render :text => "hello world", :status => "404 Not Found" - end - - def with_nil - render :text => nil - end - - def with_nil_and_status - render :text => nil, :status => 403 - end - - def with_false - render :text => false - end - - def with_layout_true - render :text => "hello world", :layout => true - end - - def with_layout_false - render :text => "hello world", :layout => false - end - - def with_layout_nil - render :text => "hello world", :layout => nil - end - - def with_custom_layout - render :text => "hello world", :layout => "greetings" - end - - def with_ivar_in_layout - @ivar = "hello world" - render :text => "hello world", :layout => "ivar" - end - end - - class RenderTextTest < Rack::TestCase - describe "Rendering text using render :text" - - test "rendering text from a action with default options renders the text with the layout" do - get "/render_text/simple" - assert_body "hello david" - assert_status 200 - end - - test "rendering text from a action with default options renders the text without the layout" do - get "/render_text/with_layout" - - assert_body "hello david" - assert_status 200 - end - - test "rendering text, while also providing a custom status code" do - get "/render_text/with_layout/custom_code" - - assert_body "hello world" - assert_status 404 - end - - test "rendering text with nil returns an empty body padded for Safari" do - get "/render_text/with_layout/with_nil" - - assert_body " " - assert_status 200 - end - - test "Rendering text with nil and custom status code returns an empty body padded for Safari and the status" do - get "/render_text/with_layout/with_nil_and_status" - - assert_body " " - assert_status 403 - end - - test "rendering text with false returns the string 'false'" do - get "/render_text/with_layout/with_false" - - assert_body "false" - assert_status 200 - end - - test "rendering text with :layout => true" do - get "/render_text/with_layout/with_layout_true" - - assert_body "hello world, I'm here!" - assert_status 200 - end - - test "rendering text with :layout => 'greetings'" do - get "/render_text/with_layout/with_custom_layout" - - assert_body "hello world, I wish thee well." - assert_status 200 - end - - test "rendering text with :layout => false" do - get "/render_text/with_layout/with_layout_false" - - assert_body "hello world" - assert_status 200 - end - - test "rendering text with :layout => nil" do - get "/render_text/with_layout/with_layout_nil" - - assert_body "hello world" - assert_status 200 - end - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/render_xml_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/render_xml_test.rb deleted file mode 100644 index 130936730..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/new_base/render_xml_test.rb +++ /dev/null @@ -1,11 +0,0 @@ -require 'abstract_unit' - -module RenderXml - - # This has no layout and it works - class BasicController < ActionController::Base - self.view_paths = [ActionView::FixtureResolver.new( - "render_xml/basic/with_render_erb" => "Hello world!" - )] - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/output_escaping_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/output_escaping_test.rb deleted file mode 100644 index 1d78d31ff..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/output_escaping_test.rb +++ /dev/null @@ -1,19 +0,0 @@ -require 'abstract_unit' - -class OutputEscapingTest < ActiveSupport::TestCase - - test "escape_html shouldn't die when passed nil" do - assert_blank ERB::Util.h(nil) - end - - test "escapeHTML should escape strings" do - assert_equal "<>"", ERB::Util.h("<>\"") - end - - test "escapeHTML shouldn't touch explicitly safe strings" do - # TODO this seems easier to compose and reason about, but - # this should be verified - assert_equal "<", ERB::Util.h("<".html_safe) - end - -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/record_identifier_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/record_identifier_test.rb deleted file mode 100644 index 88a58bde5..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/record_identifier_test.rb +++ /dev/null @@ -1,65 +0,0 @@ -require 'abstract_unit' - -class Comment - extend ActiveModel::Naming - include ActiveModel::Conversion - - attr_reader :id - def to_key; id ? [id] : nil end - def save; @id = 1 end - def new_record?; @id.nil? end - def name - @id.nil? ? 'new comment' : "comment ##{@id}" - end -end - -class Sheep - extend ActiveModel::Naming - include ActiveModel::Conversion - - attr_reader :id - def to_key; id ? [id] : nil end - def save; @id = 1 end - def new_record?; @id.nil? end - def name - @id.nil? ? 'new sheep' : "sheep ##{@id}" - end -end - -class RecordIdentifierTest < Test::Unit::TestCase - include ActionController::RecordIdentifier - - def setup - @klass = Comment - @record = @klass.new - @singular = 'comment' - @plural = 'comments' - @uncountable = Sheep - end - - def test_dom_id_with_new_record - assert_equal "new_#{@singular}", dom_id(@record) - end - - def test_dom_id_with_new_record_and_prefix - assert_equal "custom_prefix_#{@singular}", dom_id(@record, :custom_prefix) - end - - def test_dom_id_with_saved_record - @record.save - assert_equal "#{@singular}_1", dom_id(@record) - end - - def test_dom_id_with_prefix - @record.save - assert_equal "edit_#{@singular}_1", dom_id(@record, :edit) - end - - def test_dom_class - assert_equal @singular, dom_class(@record) - end - - def test_dom_class_with_prefix - assert_equal "custom_prefix_#{@singular}", dom_class(@record, :custom_prefix) - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/redirect_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/redirect_test.rb deleted file mode 100644 index 429b3baa1..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/redirect_test.rb +++ /dev/null @@ -1,291 +0,0 @@ -require 'abstract_unit' - -class WorkshopsController < ActionController::Base -end - -class Workshop - extend ActiveModel::Naming - include ActiveModel::Conversion - attr_accessor :id - - def initialize(id) - @id = id - end - - def persisted? - id.present? - end - - def to_s - id.to_s - end -end - -class RedirectController < ActionController::Base - def simple_redirect - redirect_to :action => "hello_world" - end - - def redirect_with_status - redirect_to({:action => "hello_world", :status => 301}) - end - - def redirect_with_status_hash - redirect_to({:action => "hello_world"}, {:status => 301}) - end - - def redirect_with_protocol - redirect_to :action => "hello_world", :protocol => "https" - end - - def url_redirect_with_status - redirect_to("http://www.example.com", :status => :moved_permanently) - end - - def url_redirect_with_status_hash - redirect_to("http://www.example.com", {:status => 301}) - end - - def relative_url_redirect_with_status - redirect_to("/things/stuff", :status => :found) - end - - def relative_url_redirect_with_status_hash - redirect_to("/things/stuff", {:status => 301}) - end - - def redirect_to_back_with_status - redirect_to :back, :status => 307 - end - - def host_redirect - redirect_to :action => "other_host", :only_path => false, :host => 'other.test.host' - end - - def module_redirect - redirect_to :controller => 'module_test/module_redirect', :action => "hello_world" - end - - def redirect_with_assigns - @hello = "world" - redirect_to :action => "hello_world" - end - - def redirect_to_url - redirect_to "http://www.rubyonrails.org/" - end - - def redirect_to_url_with_unescaped_query_string - redirect_to "http://dev.rubyonrails.org/query?status=new" - end - - def redirect_to_url_with_complex_scheme - redirect_to "x-test+scheme.complex:redirect" - end - - def redirect_to_back - redirect_to :back - end - - def redirect_to_existing_record - redirect_to Workshop.new(5) - end - - def redirect_to_new_record - redirect_to Workshop.new(nil) - end - - def redirect_to_nil - redirect_to nil - end - - def rescue_errors(e) raise e end - - def rescue_action(e) raise end - - protected - def dashbord_url(id, message) - url_for :action => "dashboard", :params => { "id" => id, "message" => message } - end -end - -class RedirectTest < ActionController::TestCase - tests RedirectController - - def test_simple_redirect - get :simple_redirect - assert_response :redirect - assert_equal "http://test.host/redirect/hello_world", redirect_to_url - end - - def test_redirect_with_no_status - get :simple_redirect - assert_response 302 - assert_equal "http://test.host/redirect/hello_world", redirect_to_url - end - - def test_redirect_with_status - get :redirect_with_status - assert_response 301 - assert_equal "http://test.host/redirect/hello_world", redirect_to_url - end - - def test_redirect_with_status_hash - get :redirect_with_status_hash - assert_response 301 - assert_equal "http://test.host/redirect/hello_world", redirect_to_url - end - - def test_redirect_with_protocol - get :redirect_with_protocol - assert_response 302 - assert_equal "https://test.host/redirect/hello_world", redirect_to_url - end - - def test_url_redirect_with_status - get :url_redirect_with_status - assert_response 301 - assert_equal "http://www.example.com", redirect_to_url - end - - def test_url_redirect_with_status_hash - get :url_redirect_with_status_hash - assert_response 301 - assert_equal "http://www.example.com", redirect_to_url - end - - - def test_relative_url_redirect_with_status - get :relative_url_redirect_with_status - assert_response 302 - assert_equal "http://test.host/things/stuff", redirect_to_url - end - - def test_relative_url_redirect_with_status_hash - get :relative_url_redirect_with_status_hash - assert_response 301 - assert_equal "http://test.host/things/stuff", redirect_to_url - end - - def test_redirect_to_back_with_status - @request.env["HTTP_REFERER"] = "http://www.example.com/coming/from" - get :redirect_to_back_with_status - assert_response 307 - assert_equal "http://www.example.com/coming/from", redirect_to_url - end - - def test_simple_redirect_using_options - get :host_redirect - assert_response :redirect - assert_redirected_to :action => "other_host", :only_path => false, :host => 'other.test.host' - end - - def test_module_redirect - get :module_redirect - assert_response :redirect - assert_redirected_to "http://test.host/module_test/module_redirect/hello_world" - end - - def test_module_redirect_using_options - get :module_redirect - assert_response :redirect - assert_redirected_to :controller => 'module_test/module_redirect', :action => 'hello_world' - end - - def test_redirect_with_assigns - get :redirect_with_assigns - assert_response :redirect - assert_equal "world", assigns["hello"] - end - - def test_redirect_to_url - get :redirect_to_url - assert_response :redirect - assert_redirected_to "http://www.rubyonrails.org/" - end - - def test_redirect_to_url_with_unescaped_query_string - get :redirect_to_url_with_unescaped_query_string - assert_response :redirect - assert_redirected_to "http://dev.rubyonrails.org/query?status=new" - end - - def test_redirect_to_url_with_complex_scheme - get :redirect_to_url_with_complex_scheme - assert_response :redirect - assert_equal "x-test+scheme.complex:redirect", redirect_to_url - end - - def test_redirect_to_back - @request.env["HTTP_REFERER"] = "http://www.example.com/coming/from" - get :redirect_to_back - assert_response :redirect - assert_equal "http://www.example.com/coming/from", redirect_to_url - end - - def test_redirect_to_back_with_no_referer - assert_raise(ActionController::RedirectBackError) { - @request.env["HTTP_REFERER"] = nil - get :redirect_to_back - } - end - - def test_redirect_to_record - with_routing do |set| - set.draw do |map| - resources :workshops - match ':controller/:action' - end - - get :redirect_to_existing_record - assert_equal "http://test.host/workshops/5", redirect_to_url - assert_redirected_to Workshop.new(5) - - get :redirect_to_new_record - assert_equal "http://test.host/workshops", redirect_to_url - assert_redirected_to Workshop.new(nil) - end - end - - def test_redirect_to_nil - assert_raise(ActionController::ActionControllerError) do - get :redirect_to_nil - end - end -end - -module ModuleTest - class ModuleRedirectController < ::RedirectController - def module_redirect - redirect_to :controller => '/redirect', :action => "hello_world" - end - end - - class ModuleRedirectTest < ActionController::TestCase - tests ModuleRedirectController - - def test_simple_redirect - get :simple_redirect - assert_response :redirect - assert_equal "http://test.host/module_test/module_redirect/hello_world", redirect_to_url - end - - def test_simple_redirect_using_options - get :host_redirect - assert_response :redirect - assert_redirected_to :action => "other_host", :only_path => false, :host => 'other.test.host' - end - - def test_module_redirect - get :module_redirect - assert_response :redirect - assert_equal "http://test.host/redirect/hello_world", redirect_to_url - end - - def test_module_redirect_using_options - get :module_redirect - assert_response :redirect - assert_redirected_to :controller => '/redirect', :action => "hello_world" - end - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/render_js_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/render_js_test.rb deleted file mode 100644 index 636701b98..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/render_js_test.rb +++ /dev/null @@ -1,43 +0,0 @@ -require 'abstract_unit' -require 'controller/fake_models' -require 'pathname' - -class RenderJSTest < ActionController::TestCase - class TestController < ActionController::Base - protect_from_forgery - - def self.controller_path - 'test' - end - - def render_vanilla_js_hello - render :js => "alert('hello')" - end - - def greeting - # let's just rely on the template - end - - def show_partial - render :partial => 'partial' - end - end - - tests TestController - - def test_render_vanilla_js - get :render_vanilla_js_hello - assert_equal "alert('hello')", @response.body - assert_equal "text/javascript", @response.content_type - end - - def test_render_with_default_from_accept_header - xhr :get, :greeting - assert_equal "$(\"body\").visualEffect(\"highlight\");", @response.body - end - - def test_should_render_js_partial - xhr :get, :show_partial, :format => 'js' - assert_equal 'partial js', @response.body - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/render_json_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/render_json_test.rb deleted file mode 100644 index 4cedec732..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/render_json_test.rb +++ /dev/null @@ -1,112 +0,0 @@ -require 'abstract_unit' -require 'controller/fake_models' -require 'pathname' - -class RenderJsonTest < ActionController::TestCase - class JsonRenderable - def as_json(options={}) - hash = { :a => :b, :c => :d, :e => :f } - hash.except!(*options[:except]) if options[:except] - hash - end - end - - class TestController < ActionController::Base - protect_from_forgery - - def self.controller_path - 'test' - end - - def render_json_nil - render :json => nil - end - - def render_json_hello_world - render :json => ActiveSupport::JSON.encode(:hello => 'world') - end - - def render_json_hello_world_with_status - render :json => ActiveSupport::JSON.encode(:hello => 'world'), :status => 401 - end - - def render_json_hello_world_with_callback - render :json => ActiveSupport::JSON.encode(:hello => 'world'), :callback => 'alert' - end - - def render_json_with_custom_content_type - render :json => ActiveSupport::JSON.encode(:hello => 'world'), :content_type => 'text/javascript' - end - - def render_symbol_json - render :json => ActiveSupport::JSON.encode(:hello => 'world') - end - - def render_json_with_render_to_string - render :json => {:hello => render_to_string(:partial => 'partial')} - end - - def render_json_with_extra_options - render :json => JsonRenderable.new, :except => [:c, :e] - end - end - - tests TestController - - def setup - # enable a logger so that (e.g.) the benchmarking stuff runs, so we can get - # a more accurate simulation of what happens in "real life". - super - @controller.logger = Logger.new(nil) - - @request.host = "www.nextangle.com" - end - - def test_render_json_nil - get :render_json_nil - assert_equal 'null', @response.body - assert_equal 'application/json', @response.content_type - end - - def test_render_json - get :render_json_hello_world - assert_equal '{"hello":"world"}', @response.body - assert_equal 'application/json', @response.content_type - end - - def test_render_json_with_status - get :render_json_hello_world_with_status - assert_equal '{"hello":"world"}', @response.body - assert_equal 401, @response.status - end - - def test_render_json_with_callback - get :render_json_hello_world_with_callback - assert_equal 'alert({"hello":"world"})', @response.body - assert_equal 'application/json', @response.content_type - end - - def test_render_json_with_custom_content_type - get :render_json_with_custom_content_type - assert_equal '{"hello":"world"}', @response.body - assert_equal 'text/javascript', @response.content_type - end - - def test_render_symbol_json - get :render_symbol_json - assert_equal '{"hello":"world"}', @response.body - assert_equal 'application/json', @response.content_type - end - - def test_render_json_with_render_to_string - get :render_json_with_render_to_string - assert_equal '{"hello":"partial html"}', @response.body - assert_equal 'application/json', @response.content_type - end - - def test_render_json_forwards_extra_options - get :render_json_with_extra_options - assert_equal '{"a":"b"}', @response.body - assert_equal 'application/json', @response.content_type - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/render_other_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/render_other_test.rb deleted file mode 100644 index f36fa7dc3..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/render_other_test.rb +++ /dev/null @@ -1,257 +0,0 @@ -require 'abstract_unit' -require 'controller/fake_models' -require 'pathname' - -ActionController.add_renderer :simon do |says, options| - self.content_type = Mime::TEXT - self.response_body = "Simon says: #{says}" -end - -class RenderOtherTest < ActionController::TestCase - class TestController < ActionController::Base - protect_from_forgery - - def self.controller_path - 'test' - end - - layout :determine_layout - - module RenderTestHelper - def rjs_helper_method_from_module - page.visual_effect :highlight - end - end - - helper RenderTestHelper - helper do - def rjs_helper_method(value) - page.visual_effect :highlight, value - end - end - - def enum_rjs_test - render :update do |page| - page.select('.product').each do |value| - page.rjs_helper_method_from_module - page.rjs_helper_method(value) - page.sortable(value, :url => { :action => "order" }) - page.draggable(value) - end - end - end - - def render_explicit_html_template - end - - def render_custom_code_rjs - render :update, :status => 404 do |page| - page.replace :foo, :partial => 'partial' - end - end - - def render_implicit_html_template - end - - def render_js_with_explicit_template - @project_id = 4 - render :template => 'test/delete_with_js' - end - - def render_js_with_explicit_action_template - @project_id = 4 - render :action => 'delete_with_js' - end - - def delete_with_js - @project_id = 4 - end - - def update_page - render :update do |page| - page.replace_html 'balance', '$37,000,000.00' - page.visual_effect :highlight, 'balance' - end - end - - def update_page_with_instance_variables - @money = '$37,000,000.00' - @div_id = 'balance' - render :update do |page| - page.replace_html @div_id, @money - page.visual_effect :highlight, @div_id - end - end - - def update_page_with_view_method - render :update do |page| - page.replace_html 'person', pluralize(2, 'person') - end - end - - def partial_as_rjs - render :update do |page| - page.replace :foo, :partial => 'partial' - end - end - - def respond_to_partial_as_rjs - respond_to do |format| - format.js do - render :update do |page| - page.replace :foo, :partial => 'partial' - end - end - end - end - - def render_alternate_default - # For this test, the method "default_render" is overridden: - @alternate_default_render = lambda do - render :update do |page| - page.replace :foo, :partial => 'partial' - end - end - end - - def render_simon_says - render :simon => "foo" - end - - private - def default_render - if @alternate_default_render - @alternate_default_render.call - else - super - end - end - - def determine_layout - case action_name - when "hello_world", "layout_test", "rendering_without_layout", - "rendering_nothing_on_layout", "render_text_hello_world", - "render_text_hello_world_with_layout", - "hello_world_with_layout_false", - "partial_only", "partial_only_with_layout", - "accessing_params_in_template", - "accessing_params_in_template_with_layout", - "render_with_explicit_template", - "render_with_explicit_string_template", - "update_page", "update_page_with_instance_variables" - - "layouts/standard" - when "action_talk_to_layout", "layout_overriding_layout" - "layouts/talk_from_action" - when "render_implicit_html_template_from_xhr_request" - (request.xhr? ? 'layouts/xhr' : 'layouts/standard') - end - end - end - - tests TestController - - def setup - # enable a logger so that (e.g.) the benchmarking stuff runs, so we can get - # a more accurate simulation of what happens in "real life". - super - @controller.logger = Logger.new(nil) - - @request.host = "www.nextangle.com" - end - - def test_enum_rjs_test - ActiveSupport::SecureRandom.stubs(:base64).returns("asdf") - get :enum_rjs_test - body = %{ - $$(".product").each(function(value, index) { - new Effect.Highlight(element,{}); - new Effect.Highlight(value,{}); - Sortable.create(value, {onUpdate:function(){new Ajax.Request('/render_other_test/test/order', {asynchronous:true, evalScripts:true, parameters:Sortable.serialize(value) + '&authenticity_token=' + encodeURIComponent('asdf')})}}); - new Draggable(value, {}); - }); - }.gsub(/^ /, '').strip - assert_equal body, @response.body - end - - def test_explicitly_rendering_an_html_template_with_implicit_html_template_renders_should_be_possible_from_an_rjs_template - [:js, "js"].each do |format| - assert_nothing_raised do - get :render_explicit_html_template, :format => format - assert_equal %(document.write("Hello world\\n");), @response.body - end - end - end - - def test_render_custom_code_rjs - get :render_custom_code_rjs - assert_response 404 - assert_equal %(Element.replace("foo", "partial html");), @response.body - end - - def test_render_in_an_rjs_template_should_pick_html_templates_when_available - [:js, "js"].each do |format| - assert_nothing_raised do - get :render_implicit_html_template, :format => format - assert_equal %(document.write("Hello world\\n");), @response.body - end - end - end - - def test_render_rjs_template_explicitly - get :render_js_with_explicit_template - assert_equal %!Element.remove("person");\nnew Effect.Highlight(\"project-4\",{});!, @response.body - end - - def test_rendering_rjs_action_explicitly - get :render_js_with_explicit_action_template - assert_equal %!Element.remove("person");\nnew Effect.Highlight(\"project-4\",{});!, @response.body - end - - def test_render_rjs_with_default - get :delete_with_js - assert_equal %!Element.remove("person");\nnew Effect.Highlight(\"project-4\",{});!, @response.body - end - - def test_update_page - get :update_page - assert_template nil - assert_equal 'text/javascript; charset=utf-8', @response.headers['Content-Type'] - assert_equal 2, @response.body.split($/).length - end - - def test_update_page_with_instance_variables - get :update_page_with_instance_variables - assert_template nil - assert_equal 'text/javascript; charset=utf-8', @response.headers["Content-Type"] - assert_match /balance/, @response.body - assert_match /\$37/, @response.body - end - - def test_update_page_with_view_method - get :update_page_with_view_method - assert_template nil - assert_equal 'text/javascript; charset=utf-8', @response.headers["Content-Type"] - assert_match /2 people/, @response.body - end - - def test_should_render_html_formatted_partial_with_rjs - xhr :get, :partial_as_rjs - assert_equal %(Element.replace("foo", "partial html");), @response.body - end - - def test_should_render_html_formatted_partial_with_rjs_and_js_format - xhr :get, :respond_to_partial_as_rjs - assert_equal %(Element.replace("foo", "partial html");), @response.body - end - - def test_should_render_with_alternate_default_render - xhr :get, :render_alternate_default - assert_equal %(Element.replace("foo", "partial html");), @response.body - end - - def test_using_custom_render_option - get :render_simon_says - assert_equal "Simon says: foo", @response.body - end -end diff --git a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/render_test.rb b/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/render_test.rb deleted file mode 100644 index a718b3c79..000000000 --- a/Tests/Libraries/Rails-3.0.0/actionpack/test/controller/render_test.rb +++ /dev/null @@ -1,1538 +0,0 @@ -require 'abstract_unit' -require 'controller/fake_models' -require 'pathname' - -module Fun - class GamesController < ActionController::Base - # :ported: - def hello_world - end - - def nested_partial_with_form_builder - render :partial => ActionView::Helpers::FormBuilder.new(:post, nil, view_context, {}, Proc.new {}) - end - end -end - -class TestController < ActionController::Base - protect_from_forgery - - class LabellingFormBuilder < ActionView::Helpers::FormBuilder - end - - layout :determine_layout - - def name - nil - end - - private :name - helper_method :name - - def hello_world - end - - def hello_world_file - render :file => File.expand_path("../../fixtures/hello.html", __FILE__) - end - - def conditional_hello - if stale?(:last_modified => Time.now.utc.beginning_of_day, :etag => [:foo, 123]) - render :action => 'hello_world' - end - end - - def conditional_hello_with_public_header - if stale?(:last_modified => Time.now.utc.beginning_of_day, :etag => [:foo, 123], :public => true) - render :action => 'hello_world' - end - end - - def conditional_hello_with_public_header_and_expires_at - expires_in 1.minute - if stale?(:last_modified => Time.now.utc.beginning_of_day, :etag => [:foo, 123], :public => true) - render :action => 'hello_world' - end - end - - def conditional_hello_with_expires_in - expires_in 60.1.seconds - render :action => 'hello_world' - end - - def conditional_hello_with_expires_in_with_public - expires_in 1.minute, :public => true - render :action => 'hello_world' - end - - def conditional_hello_with_expires_in_with_public_with_more_keys - expires_in 1.minute, :public => true, 'max-stale' => 5.hours - render :action => 'hello_world' - end - - def conditional_hello_with_expires_in_with_public_with_more_keys_old_syntax - expires_in 1.minute, :public => true, :private => nil, 'max-stale' => 5.hours - render :action => 'hello_world' - end - - def conditional_hello_with_expires_now - expires_now - render :action => 'hello_world' - end - - def conditional_hello_with_bangs - render :action => 'hello_world' - end - before_filter :handle_last_modified_and_etags, :only=>:conditional_hello_with_bangs - - def handle_last_modified_and_etags - fresh_when(:last_modified => Time.now.utc.beginning_of_day, :etag => [ :foo, 123 ]) - end - - # :ported: - def render_hello_world - render :template => "test/hello_world" - end - - def render_hello_world_with_last_modified_set - response.last_modified = Date.new(2008, 10, 10).to_time - render :template => "test/hello_world" - end - - def render_hello_world_with_etag_set - response.etag = "hello_world" - render :template => "test/hello_world" - end - - # :ported: compatibility - def render_hello_world_with_forward_slash - render :template => "/test/hello_world" - end - - # :ported: - def render_template_in_top_directory - render :template => 'shared' - end - - # :deprecated: - def render_template_in_top_directory_with_slash - render :template => '/shared' - end - - # :ported: - def render_hello_world_from_variable - @person = "david" - render :text => "hello #{@person}" - end - - # :ported: - def render_action_hello_world - render :action => "hello_world" - end - - def render_action_hello_world_as_string - render "hello_world" - end - - def render_action_hello_world_with_symbol - render :action => :hello_world - end - - # :ported: - def render_text_hello_world - render :text => "hello world" - end - - # :ported: - def render_text_hello_world_with_layout - @variable_for_layout = ", I'm here!" - render :text => "hello world", :layout => true - end - - def hello_world_with_layout_false - render :layout => false - end - - # :ported: - def render_file_with_instance_variables - @secret = 'in the sauce' - path = File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar.erb') - render :file => path - end - - # :ported: - def render_file_as_string_with_instance_variables - @secret = 'in the sauce' - path = File.expand_path(File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar.erb')) - render path - end - - # :ported: - def render_file_not_using_full_path - @secret = 'in the sauce' - render :file => 'test/render_file_with_ivar' - end - - def render_file_not_using_full_path_with_dot_in_path - @secret = 'in the sauce' - render :file => 'test/dot.directory/render_file_with_ivar' - end - - def render_file_using_pathname - @secret = 'in the sauce' - render :file => Pathname.new(File.dirname(__FILE__)).join('..', 'fixtures', 'test', 'dot.directory', 'render_file_with_ivar.erb') - end - - def render_file_from_template - @secret = 'in the sauce' - @path = File.expand_path(File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar.erb')) - end - - def render_file_with_locals - path = File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_locals.erb') - render :file => path, :locals => {:secret => 'in the sauce'} - end - - def render_file_as_string_with_locals - path = File.expand_path(File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_locals.erb')) - render path, :locals => {:secret => 'in the sauce'} - end - - def accessing_request_in_template - render :inline => "Hello: <%= request.host %>" - end - - def accessing_logger_in_template - render :inline => "<%= logger.class %>" - end - - def accessing_action_name_in_template - render :inline => "<%= action_name %>" - end - - def accessing_controller_name_in_template - render :inline => "<%= controller_name %>" - end - - # :ported: - def render_custom_code - render :text => "hello world", :status => 404 - end - - # :ported: - def render_text_with_nil - render :text => nil - end - - # :ported: - def render_text_with_false - render :text => false - end - - def render_text_with_resource - render :text => Customer.new("David") - end - - # :ported: - def render_nothing_with_appendix - render :text => "appended" - end - - # This test is testing 3 things: - # render :file in AV :ported: - # render :template in AC :ported: - # setting content type - def render_xml_hello - @name = "David" - render :template => "test/hello" - end - - def render_xml_hello_as_string_template - @name = "David" - render "test/hello" - end - - def render_line_offset - render :inline => '<% raise %>', :locals => {:foo => 'bar'} - end - - def heading - head :ok - end - - def greeting - # let's just rely on the template - end - - # :ported: - def blank_response - render :text => ' ' - end - - # :ported: - def layout_test - render :action => "hello_world" - end - - # :ported: - def builder_layout_test - render :action => "hello", :layout => "layouts/builder" - end - - # :move: test this in Action View - def builder_partial_test - render :action => "hello_world_container" - end - - # :ported: - def partials_list - @test_unchanged = 'hello' - @customers = [ Customer.new("david"), Customer.new("mary") ] - render :action => "list" - end - - def partial_only - render :partial => true - end - - def hello_in_a_string - @customers = [ Customer.new("david"), Customer.new("mary") ] - render :text => "How's there? " + render_to_string(:template => "test/list") - end - - def accessing_params_in_template - render :inline => "Hello: <%= params[:name] %>" - end - - def accessing_local_assigns_in_inline_template - name = params[:local_name] - render :inline => "<%= 'Goodbye, ' + local_name %>", - :locals => { :local_name => name } - end - - def render_implicit_html_template_from_xhr_request - end - - def render_implicit_js_template_without_layout - end - - def formatted_html_erb - end - - def formatted_xml_erb - end - - def render_to_string_test - @foo = render_to_string :inline => "this is a test" - end - - def default_render - if @alternate_default_render - @alternate_default_render.call - else - super - end - end - - def render_action_hello_world_as_symbol - render :action => :hello_world - end - - def layout_test_with_different_layout - render :action => "hello_world", :layout => "standard" - end - - def layout_test_with_different_layout_and_string_action - render "hello_world", :layout => "standard" - end - - def layout_test_with_different_layout_and_symbol_action - render :hello_world, :layout => "standard" - end - - def rendering_without_layout - render :action => "hello_world", :layout => false - end - - def layout_overriding_layout - render :action => "hello_world", :layout => "standard" - end - - def rendering_nothing_on_layout - render :nothing => true - end - - def render_to_string_with_assigns - @before = "i'm before the render" - render_to_string :text => "foo" - @after = "i'm after the render" - render :template => "test/hello_world" - end - - def render_to_string_with_exception - render_to_string :file => "exception that will not be caught - this will certainly not work" - end - - def render_to_string_with_caught_exception - @before = "i'm before the render" - begin - render_to_string :file => "exception that will be caught- hope my future instance vars still work!" - rescue - end - @after = "i'm after the render" - render :template => "test/hello_world" - end - - def accessing_params_in_template_with_layout - render :layout => true, :inline => "Hello: <%= params[:name] %>" - end - - # :ported: - def render_with_explicit_template - render :template => "test/hello_world" - end - - def render_with_explicit_string_template - render "test/hello_world" - end - - # :ported: - def render_with_explicit_template_with_locals - render :template => "test/render_file_with_locals", :locals => { :secret => 'area51' } - end - - # :ported: - def double_render - render :text => "hello" - render :text => "world" - end - - def double_redirect - redirect_to :action => "double_render" - redirect_to :action => "double_render" - end - - def render_and_redirect - render :text => "hello" - redirect_to :action => "double_render" - end - - def render_to_string_and_render - @stuff = render_to_string :text => "here is some cached stuff" - render :text => "Hi web users! #{@stuff}" - end - - def render_to_string_with_inline_and_render - render_to_string :inline => "<%= 'dlrow olleh'.reverse %>" - render :template => "test/hello_world" - end - - def rendering_with_conflicting_local_vars - @name = "David" - render :action => "potential_conflicts" - end - - # :deprecated: - # Tests being able to pick a .builder template over a .erb - # For instance, being able to have hello.xml.builder and hello.xml.erb - # and select one via "hello.builder" or "hello.erb" - def hello_world_from_rxml_using_action - render :action => "hello_world_from_rxml.builder" - end - - # :deprecated: - def hello_world_from_rxml_using_template - render :template => "test/hello_world_from_rxml.builder" - end - - def action_talk_to_layout - # Action template sets variable that's picked up by layout - end - - # :addressed: - def render_text_with_assigns - @hello = "world" - render :text => "foo" - end - - def yield_content_for - render :action => "content_for", :layout => "yield" - end - - def render_content_type_from_body - response.content_type = Mime::RSS - render :text => "hello world!" - end - - def head_with_location_header - head :location => "/foo" - end - - def head_with_location_object - head :location => Customer.new("david", 1) - end - - def head_with_symbolic_status - head :status => params[:status].intern - end - - def head_with_integer_status - head :status => params[:status].to_i - end - - def head_with_string_status - head :status => params[:status] - end - - def head_with_custom_header - head :x_custom_header => "something" - end - - def head_with_status_code_first - head :forbidden, :x_custom_header => "something" - end - - def render_using_layout_around_block - render :action => "using_layout_around_block" - end - - def render_using_layout_around_block_in_main_layout_and_within_content_for_layout - render :action => "using_layout_around_block", :layout => "layouts/block_with_layout" - end - - def partial_dot_html - render :partial => 'partial.html.erb' - end - - def partial - render :partial => 'partial' - end - - def render_alternate_default - # For this test, the method "default_render" is overridden: - @alternate_default_render = lambda do - render :update do |page| - page.replace :foo, :partial => 'partial' - end - end - end - - def render_to_string_with_partial - @partial_only = render_to_string :partial => "partial_only" - @partial_with_locals = render_to_string :partial => "customer", :locals => { :customer => Customer.new("david") } - render :template => "test/hello_world" - end - - def partial_with_counter - render :partial => "counter", :locals => { :counter_counter => 5 } - end - - def partial_with_locals - render :partial => "customer", :locals => { :customer => Customer.new("david") } - end - - def partial_with_form_builder - render :partial => ActionView::Helpers::FormBuilder.new(:post, nil, view_context, {}, Proc.new {}) - end - - def partial_with_form_builder_subclass - render :partial => LabellingFormBuilder.new(:post, nil, view_context, {}, Proc.new {}) - end - - def partial_collection - render :partial => "customer", :collection => [ Customer.new("david"), Customer.new("mary") ] - end - - def partial_collection_with_as - render :partial => "customer_with_var", :collection => [ Customer.new("david"), Customer.new("mary") ], :as => :customer - end - - def partial_collection_with_counter - render :partial => "customer_counter", :collection => [ Customer.new("david"), Customer.new("mary") ] - end - - def partial_collection_with_as_and_counter - render :partial => "customer_counter_with_as", :collection => [ Customer.new("david"), Customer.new("mary") ], :as => :client - end - - def partial_collection_with_locals - render :partial => "customer_greeting", :collection => [ Customer.new("david"), Customer.new("mary") ], :locals => { :greeting => "Bonjour" } - end - - def partial_collection_with_spacer - render :partial => "customer", :spacer_template => "partial_only", :collection => [ Customer.new("david"), Customer.new("mary") ] - end - - def partial_collection_shorthand_with_locals - render :partial => [ Customer.new("david"), Customer.new("mary") ], :locals => { :greeting => "Bonjour" } - end - - def partial_collection_shorthand_with_different_types_of_records - render :partial => [ - BadCustomer.new("mark"), - GoodCustomer.new("craig"), - BadCustomer.new("john"), - GoodCustomer.new("zach"), - GoodCustomer.new("brandon"), - BadCustomer.new("dan") ], - :locals => { :greeting => "Bonjour" } - end - - def empty_partial_collection - render :partial => "customer", :collection => [] - end - - def partial_collection_shorthand_with_different_types_of_records_with_counter - partial_collection_shorthand_with_different_types_of_records - end - - def missing_partial - render :partial => 'thisFileIsntHere' - end - - def partial_with_hash_object - render :partial => "hash_object", :object => {:first_name => "Sam"} - end - - def partial_with_nested_object - render :partial => "quiz/questions/question", :object => Quiz::Question.new("first") - end - - def partial_with_nested_object_shorthand - render Quiz::Question.new("first") - end - - def partial_hash_collection - render :partial => "hash_object", :collection => [ {:first_name => "Pratik"}, {:first_name => "Amy"} ] - end - - def partial_hash_collection_with_locals - render :partial => "hash_greeting", :collection => [ {:first_name => "Pratik"}, {:first_name => "Amy"} ], :locals => { :greeting => "Hola" } - end - - def partial_with_implicit_local_assignment - @customer = Customer.new("Marcel") - render :partial => "customer" - end - - def render_call_to_partial_with_layout - render :action => "calling_partial_with_layout" - end - - def render_call_to_partial_with_layout_in_main_layout_and_within_content_for_layout - render :action => "calling_partial_with_layout", :layout => "layouts/partial_with_layout" - end - - def rescue_action(e) - raise - end - - before_filter :only => :render_with_filters do - request.format = :xml - end - - # Ensure that the before filter is executed *before* self.formats is set. - def render_with_filters - render :action => :formatted_xml_erb - end - - private - - def determine_layout - case action_name - when "hello_world", "layout_test", "rendering_without_layout", - "rendering_nothing_on_layout", "render_text_hello_world", - "render_text_hello_world_with_layout", - "hello_world_with_layout_false", - "partial_only", "accessing_params_in_template", - "accessing_params_in_template_with_layout", - "render_with_explicit_template", - "render_with_explicit_string_template", - "update_page", "update_page_with_instance_variables" - - "layouts/standard" - when "action_talk_to_layout", "layout_overriding_layout" - "layouts/talk_from_action" - when "render_implicit_html_template_from_xhr_request" - (request.xhr? ? 'layouts/xhr' : 'layouts/standard') - end - end -end - -class RenderTest < ActionController::TestCase - tests TestController - - def setup - # enable a logger so that (e.g.) the benchmarking stuff runs, so we can get - # a more accurate simulation of what happens in "real life". - super - @controller.logger = Logger.new(nil) - - @request.host = "www.nextangle.com" - end - - # :ported: - def test_simple_show - get :hello_world - assert_response 200 - assert_response :success - assert_template "test/hello_world" - assert_equal "Hello world!", @response.body - end - - # :ported: - def test_renders_default_template_for_missing_action - get :'hyphen-ated' - assert_template 'test/hyphen-ated' - end - - # :ported: - def test_render - get :render_hello_world - assert_template "test/hello_world" - end - - def test_line_offset - begin - get :render_line_offset - flunk "the action should have raised an exception" - rescue StandardError => exc - line = exc.backtrace.first - assert(line =~ %r{:(\d+):}) - assert_equal "1", $1, - "The line offset is wrong, perhaps the wrong exception has been raised, exception was: #{exc.inspect}" - end - end - - # :ported: compatibility - def test_render_with_forward_slash - get :render_hello_world_with_forward_slash - assert_template "test/hello_world" - end - - # :ported: - def test_render_in_top_directory - get :render_template_in_top_directory - assert_template "shared" - assert_equal "Elastica", @response.body - end - - # :ported: - def test_render_in_top_directory_with_slash - get :render_template_in_top_directory_with_slash - assert_template "shared" - assert_equal "Elastica", @response.body - end - - # :ported: - def test_render_from_variable - get :render_hello_world_from_variable - assert_equal "hello david", @response.body - end - - # :ported: - def test_render_action - get :render_action_hello_world - assert_template "test/hello_world" - end - - # :ported: - def test_render_action_hello_world_as_string - get :render_action_hello_world_as_string - assert_equal "Hello world!", @response.body - assert_template "test/hello_world" - end - - # :ported: - def test_render_action_with_symbol - get :render_action_hello_world_with_symbol - assert_template "test/hello_world" - end - - # :ported: - def test_render_text - get :render_text_hello_world - assert_equal "hello world", @response.body - end - - # :ported: - def test_do_with_render_text_and_layout - get :render_text_hello_world_with_layout - assert_equal "hello world, I'm here!", @response.body - end - - # :ported: - def test_do_with_render_action_and_layout_false - get :hello_world_with_layout_false - assert_equal 'Hello world!', @response.body - end - - # :ported: - def test_render_file_with_instance_variables - get :render_file_with_instance_variables - assert_equal "The secret is in the sauce\n", @response.body - end - - def test_render_file - get :hello_world_file - assert_equal "Hello world!", @response.body - end - - # :ported: - def test_render_file_as_string_with_instance_variables - get :render_file_as_string_with_instance_variables - assert_equal "The secret is in the sauce\n", @response.body - end - - # :ported: - def test_render_file_not_using_full_path - get :render_file_not_using_full_path - assert_equal "The secret is in the sauce\n", @response.body - end - - # :ported: - def test_render_file_not_using_full_path_with_dot_in_path - get :render_file_not_using_full_path_with_dot_in_path - assert_equal "The secret is in the sauce\n", @response.body - end - - # :ported: - def test_render_file_using_pathname - get :render_file_using_pathname - assert_equal "The secret is in the sauce\n", @response.body - end - - # :ported: - def test_render_file_with_locals - get :render_file_with_locals - assert_equal "The secret is in the sauce\n", @response.body - end - - # :ported: - def test_render_file_as_string_with_locals - get :render_file_as_string_with_locals - assert_equal "The secret is in the sauce\n", @response.body - end - - # :assessed: - def test_render_file_from_template - get :render_file_from_template - assert_equal "The secret is in the sauce\n", @response.body - end - - # :ported: - def test_render_custom_code - get :render_custom_code - assert_response 404 - assert_response :missing - assert_equal 'hello world', @response.body - end - - # :ported: - def test_render_text_with_nil - get :render_text_with_nil - assert_response 200 - assert_equal ' ', @response.body - end - - # :ported: - def test_render_text_with_false - get :render_text_with_false - assert_equal 'false', @response.body - end - - # :ported: - def test_render_nothing_with_appendix - get :render_nothing_with_appendix - assert_response 200 - assert_equal 'appended', @response.body - end - - def test_render_text_with_resource - get :render_text_with_resource - assert_equal 'name: "David"', @response.body - end - - # :ported: - def test_attempt_to_access_object_method - assert_raise(ActionController::UnknownAction, "No action responded to [clone]") { get :clone } - end - - # :ported: - def test_private_methods - assert_raise(ActionController::UnknownAction, "No action responded to [determine_layout]") { get :determine_layout } - end - - # :ported: - def test_access_to_request_in_view - get :accessing_request_in_template - assert_equal "Hello: www.nextangle.com", @response.body - end - - def test_access_to_logger_in_view - get :accessing_logger_in_template - assert_equal "Logger", @response.body - end - - # :ported: - def test_access_to_action_name_in_view - get :accessing_action_name_in_template - assert_equal "accessing_action_name_in_template", @response.body - end - - # :ported: - def test_access_to_controller_name_in_view - get :accessing_controller_name_in_template - assert_equal "test", @response.body # name is explicitly set in the controller. - end - - # :ported: - def test_render_xml - get :render_xml_hello - assert_equal "\n

Hello David

\n

This is grand!

\n\n", @response.body - assert_equal "application/xml", @response.content_type - end - - # :ported: - def test_render_xml_as_string_template - get :render_xml_hello_as_string_template - assert_equal "\n

Hello David

\n

This is grand!

\n\n", @response.body - assert_equal "application/xml", @response.content_type - end - - # :ported: - def test_render_xml_with_default - get :greeting - assert_equal "

This is grand!

\n", @response.body - end - - # :move: test in AV - def test_render_xml_with_partial - get :builder_partial_test - assert_equal "\n \n\n", @response.body - end - - # :ported: - def test_layout_rendering - get :layout_test - assert_equal "Hello world!", @response.body - end - - def test_render_xml_with_layouts - get :builder_layout_test - assert_equal "\n\n

Hello

\n

This is grand!

\n\n
\n", @response.body - end - - def test_partials_list - get :partials_list - assert_equal "goodbyeHello: davidHello: marygoodbye\n", @response.body - end - - def test_render_to_string - get :hello_in_a_string - assert_equal "How's there? goodbyeHello: davidHello: marygoodbye\n", @response.body - end - - def test_render_to_string_resets_assigns - get :render_to_string_test - assert_equal "The value of foo is: ::this is a test::\n", @response.body - end - - def test_render_to_string_inline - get :render_to_string_with_inline_and_render - assert_template "test/hello_world" - end - - # :ported: - def test_nested_rendering - @controller = Fun::GamesController.new - get :hello_world - assert_equal "Living in a nested world", @response.body - end - - def test_accessing_params_in_template - get :accessing_params_in_template, :name => "David" - assert_equal "Hello: David", @response.body - end - - def test_accessing_local_assigns_in_inline_template - get :accessing_local_assigns_in_inline_template, :local_name => "Local David" - assert_equal "Goodbye, Local David", @response.body - end - - def test_should_implicitly_render_html_template_from_xhr_request - xhr :get, :render_implicit_html_template_from_xhr_request - assert_equal "XHR!\nHello HTML!", @response.body - end - - def test_should_implicitly_render_js_template_without_layout - get :render_implicit_js_template_without_layout, :format => :js - assert_no_match %r{}, @response.body - end - - def test_should_render_formatted_template - get :formatted_html_erb - assert_equal 'formatted html erb', @response.body - end - - def test_should_render_formatted_html_erb_template - get :formatted_xml_erb - assert_equal 'passed formatted html erb', @response.body - end - - def test_should_render_formatted_html_erb_template_with_faulty_accepts_header - @request.accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, appliction/x-shockwave-flash, */*" - get :formatted_xml_erb - assert_equal 'passed formatted html erb', @response.body - end - - def test_layout_test_with_different_layout - get :layout_test_with_different_layout - assert_equal "Hello world!", @response.body - end - - def test_layout_test_with_different_layout_and_string_action - get :layout_test_with_different_layout_and_string_action - assert_equal "Hello world!", @response.body - end - - def test_layout_test_with_different_layout_and_symbol_action - get :layout_test_with_different_layout_and_symbol_action - assert_equal "Hello world!", @response.body - end - - def test_rendering_without_layout - get :rendering_without_layout - assert_equal "Hello world!", @response.body - end - - def test_layout_overriding_layout - get :layout_overriding_layout - assert_no_match %r{}, @response.body - end - - def test_rendering_nothing_on_layout - get :rendering_nothing_on_layout - assert_equal " ", @response.body - end - - def test_render_to_string - assert_not_deprecated { get :hello_in_a_string } - assert_equal "How's there? goodbyeHello: davidHello: marygoodbye\n", @response.body - end - - def test_render_to_string_doesnt_break_assigns - get :render_to_string_with_assigns - assert_equal "i'm before the render", assigns(:before) - assert_equal "i'm after the render", assigns(:after) - end - - def test_bad_render_to_string_still_throws_exception - assert_raise(ActionView::MissingTemplate) { get :render_to_string_with_exception } - end - - def test_render_to_string_that_throws_caught_exception_doesnt_break_assigns - assert_nothing_raised { get :render_to_string_with_caught_exception } - assert_equal "i'm before the render", assigns(:before) - assert_equal "i'm after the render", assigns(:after) - end - - def test_accessing_params_in_template_with_layout - get :accessing_params_in_template_with_layout, :name => "David" - assert_equal "<html>Hello: David</html>", @response.body - end - - def test_render_with_explicit_template - get :render_with_explicit_template - assert_response :success - end - - def test_render_with_explicit_string_template - get :render_with_explicit_string_template - assert_equal "<html>Hello world!</html>", @response.body - end - - def test_render_with_filters - get :render_with_filters - assert_equal "<test>passed formatted xml erb</test>", @response.body - end - - # :ported: - def test_double_render - assert_raise(ActionController::DoubleRenderError) { get :double_render } - end - - def test_double_redirect - assert_raise(ActionController::DoubleRenderError) { get :double_redirect } - end - - def test_render_and_redirect - assert_raise(ActionController::DoubleRenderError) { get :render_and_redirect } - end - - # specify the one exception to double render rule - render_to_string followed by render - def test_render_to_string_and_render - get :render_to_string_and_render - assert_equal("Hi web users! here is some cached stuff", @response.body) - end - - def test_rendering_with_conflicting_local_vars - get :rendering_with_conflicting_local_vars - assert_equal("First: David\nSecond: Stephan\nThird: David\nFourth: David\nFifth: ", @response.body) - end - - def test_action_talk_to_layout - get :action_talk_to_layout - assert_equal "<title>Talking to the layout\nAction was here!", @response.body - end - - # :addressed: - def test_render_text_with_assigns - get :render_text_with_assigns - assert_equal "world", assigns["hello"] - end - - # :ported: - def test_template_with_locals - get :render_with_explicit_template_with_locals - assert_equal "The secret is area51\n", @response.body - end - - def test_yield_content_for - assert_not_deprecated { get :yield_content_for } - assert_equal "Putting stuff in the title!\nGreat stuff!\n", @response.body - end - - def test_overwritting_rendering_relative_file_with_extension - get :hello_world_from_rxml_using_template - assert_equal "\n

Hello

\n\n", @response.body - - get :hello_world_from_rxml_using_action - assert_equal "\n

Hello

\n\n", @response.body - end - - def test_head_with_location_header - get :head_with_location_header - assert_blank @response.body - assert_equal "/foo", @response.headers["Location"] - assert_response :ok - end - - def test_head_with_location_object - with_routing do |set| - set.draw do |map| - resources :customers - match ':controller/:action' - end - - get :head_with_location_object - assert_blank @response.body - assert_equal "http://www.nextangle.com/customers/1", @response.headers["Location"] - assert_response :ok - end - end - - def test_head_with_custom_header - get :head_with_custom_header - assert_blank @response.body - assert_equal "something", @response.headers["X-Custom-Header"] - assert_response :ok - end - - def test_head_with_symbolic_status - get :head_with_symbolic_status, :status => "ok" - assert_equal 200, @response.status - assert_response :ok - - get :head_with_symbolic_status, :status => "not_found" - assert_equal 404, @response.status - assert_response :not_found - - get :head_with_symbolic_status, :status => "no_content" - assert_equal 204, @response.status - assert !@response.headers.include?('Content-Length') - assert_response :no_content - - Rack::Utils::SYMBOL_TO_STATUS_CODE.each do |status, code| - get :head_with_symbolic_status, :status => status.to_s - assert_equal code, @response.response_code - assert_response status - end - end - - def test_head_with_integer_status - Rack::Utils::HTTP_STATUS_CODES.each do |code, message| - get :head_with_integer_status, :status => code.to_s - assert_equal message, @response.message - end - end - - def test_head_with_string_status - get :head_with_string_status, :status => "404 Eat Dirt" - assert_equal 404, @response.response_code - assert_equal "Not Found", @response.message - assert_response :not_found - end - - def test_head_with_status_code_first - get :head_with_status_code_first - assert_equal 403, @response.response_code - assert_equal "Forbidden", @response.message - assert_equal "something", @response.headers["X-Custom-Header"] - assert_response :forbidden - end - - def test_using_layout_around_block - get :render_using_layout_around_block - assert_equal "Before (David)\nInside from block\nAfter", @response.body - end - - def test_using_layout_around_block_in_main_layout_and_within_content_for_layout - get :render_using_layout_around_block_in_main_layout_and_within_content_for_layout - assert_equal "Before (Anthony)\nInside from first block in layout\nAfter\nBefore (David)\nInside from block\nAfter\nBefore (Ramm)\nInside from second block in layout\nAfter\n", @response.body - end - - def test_partial_only - get :partial_only - assert_equal "only partial", @response.body - end - - def test_should_render_html_formatted_partial - get :partial - assert_equal 'partial html', @response.body - end - - def test_should_render_html_partial_with_dot - get :partial_dot_html - assert_equal 'partial html', @response.body - end - - def test_render_to_string_partial - get :render_to_string_with_partial - assert_equal "only partial", assigns(:partial_only) - assert_equal "Hello: david", assigns(:partial_with_locals) - end - - def test_partial_with_counter - get :partial_with_counter - assert_equal "5", @response.body - end - - def test_partial_with_locals - get :partial_with_locals - assert_equal "Hello: david", @response.body - end - - def test_partial_with_form_builder - get :partial_with_form_builder - assert_match(/