diff options
Diffstat (limited to 'activesupport')
48 files changed, 192 insertions, 803 deletions
diff --git a/activesupport/MIT-LICENSE b/activesupport/MIT-LICENSE index 5e8b7a9450..c2bcf1d3e7 100644 --- a/activesupport/MIT-LICENSE +++ b/activesupport/MIT-LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2005-2011 David Heinemeier Hansson +Copyright (c) 2005-2012 David Heinemeier Hansson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the diff --git a/activesupport/lib/active_support.rb b/activesupport/lib/active_support.rb index 9fdc7a3b83..dbf0c25c5c 100644 --- a/activesupport/lib/active_support.rb +++ b/activesupport/lib/active_support.rb @@ -1,5 +1,5 @@ #-- -# Copyright (c) 2005-2011 David Heinemeier Hansson +# Copyright (c) 2005-2012 David Heinemeier Hansson # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -52,7 +52,6 @@ module ActiveSupport # TODO: Narrow this list down eager_autoload do autoload :BacktraceCleaner - autoload :Base64 autoload :BasicObject autoload :Benchmarkable autoload :Cache diff --git a/activesupport/lib/active_support/base64.rb b/activesupport/lib/active_support/base64.rb deleted file mode 100644 index b43d2ce9a3..0000000000 --- a/activesupport/lib/active_support/base64.rb +++ /dev/null @@ -1,14 +0,0 @@ -require 'base64' - -module ActiveSupport - Base64 = ::Base64 - - # Encodes the value as base64 without the newline breaks. This makes the base64 encoding readily usable as URL parameters - # or memcache keys without further processing. - # - # ActiveSupport::Base64.encode64s("Original unencoded string") - # # => "T3JpZ2luYWwgdW5lbmNvZGVkIHN0cmluZw==" - def Base64.encode64s(value) - encode64(value).gsub(/\n/, '') - end -end diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb index 2ebafa28dd..0495741c15 100644 --- a/activesupport/lib/active_support/callbacks.rb +++ b/activesupport/lib/active_support/callbacks.rb @@ -378,9 +378,6 @@ module ActiveSupport module ClassMethods # Generate the internal runner method called by +run_callbacks+. def __define_runner(symbol) #:nodoc: - name = __callback_runner_name(nil, symbol) - undef_method(name) if method_defined?(name) - runner_method = "_run_#{symbol}_callbacks" unless private_method_defined?(runner_method) class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1 @@ -408,6 +405,11 @@ module ActiveSupport object.send(name, &blk) end + def __reset_runner(symbol) + name = __callback_runner_name(nil, symbol) + undef_method(name) if method_defined?(name) + end + def __callback_runner_name(key, kind) "_run__#{self.name.hash.abs}__#{kind}__#{key.hash.abs}__callbacks" end @@ -423,7 +425,7 @@ module ActiveSupport ([self] + ActiveSupport::DescendantsTracker.descendants(self)).reverse.each do |target| chain = target.send("_#{name}_callbacks") yield target, chain.dup, type, filters, options - target.__define_runner(name) + target.__reset_runner(name) end end @@ -537,12 +539,12 @@ module ActiveSupport chain = target.send("_#{symbol}_callbacks").dup callbacks.each { |c| chain.delete(c) } target.send("_#{symbol}_callbacks=", chain) - target.__define_runner(symbol) + target.__reset_runner(symbol) end self.send("_#{symbol}_callbacks=", callbacks.dup.clear) - __define_runner(symbol) + __reset_runner(symbol) end # Define sets of events in the object lifecycle that support callbacks. diff --git a/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb b/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb index 391bdc925d..3ec7e576c8 100644 --- a/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb +++ b/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb @@ -1,29 +1,9 @@ require 'bigdecimal' - -begin - require 'psych' -rescue LoadError -end - require 'yaml' class BigDecimal - YAML_TAG = 'tag:yaml.org,2002:float' YAML_MAPPING = { 'Infinity' => '.Inf', '-Infinity' => '-.Inf', 'NaN' => '.NaN' } - # This emits the number without any scientific notation. - # This is better than self.to_f.to_s since it doesn't lose precision. - # - # Note that reconstituting YAML floats to native floats may lose precision. - def to_yaml(opts = {}) - return super if defined?(YAML::ENGINE) && !YAML::ENGINE.syck? - - YAML.quick_emit(nil, opts) do |out| - string = to_s - out.scalar(YAML_TAG, YAML_MAPPING[string] || string, :plain) - end - end - def encode_with(coder) string = to_s coder.represent_scalar(nil, YAML_MAPPING[string] || string) diff --git a/activesupport/lib/active_support/core_ext/class/attribute.rb b/activesupport/lib/active_support/core_ext/class/attribute.rb index 45bec264ff..305ed4964b 100644 --- a/activesupport/lib/active_support/core_ext/class/attribute.rb +++ b/activesupport/lib/active_support/core_ext/class/attribute.rb @@ -110,6 +110,6 @@ class Class private def singleton_class? - !name || '' == name + ancestors.first != self end end diff --git a/activesupport/lib/active_support/core_ext/class/subclasses.rb b/activesupport/lib/active_support/core_ext/class/subclasses.rb index 46e9daaa8f..74ea047c24 100644 --- a/activesupport/lib/active_support/core_ext/class/subclasses.rb +++ b/activesupport/lib/active_support/core_ext/class/subclasses.rb @@ -7,7 +7,7 @@ class Class #:nodoc: def descendants descendants = [] - ObjectSpace.each_object(class << self; self; end) do |k| + ObjectSpace.each_object(singleton_class) do |k| descendants.unshift k unless k == self end descendants diff --git a/activesupport/lib/active_support/core_ext/date_time/conversions.rb b/activesupport/lib/active_support/core_ext/date_time/conversions.rb index 851012e3bf..d7b3ad7d8d 100644 --- a/activesupport/lib/active_support/core_ext/date_time/conversions.rb +++ b/activesupport/lib/active_support/core_ext/date_time/conversions.rb @@ -6,7 +6,7 @@ require 'active_support/values/time_zone' class DateTime # Ruby 1.9 has DateTime#to_time which internally relies on Time. We define our own #to_time which allows # DateTimes outside the range of what can be created with Time. - remove_method :to_time if instance_methods.include?(:to_time) + remove_method :to_time # Convert to a formatted string. See Time::DATE_FORMATS for predefined formats. # diff --git a/activesupport/lib/active_support/core_ext/kernel/debugger.rb b/activesupport/lib/active_support/core_ext/kernel/debugger.rb index 7516f41e0b..d5b590e9f0 100644 --- a/activesupport/lib/active_support/core_ext/kernel/debugger.rb +++ b/activesupport/lib/active_support/core_ext/kernel/debugger.rb @@ -2,7 +2,7 @@ module Kernel unless respond_to?(:debugger) # Starts a debugging session if ruby-debug has been loaded (call rails server --debugger to do load it). def debugger - message = "\n***** Debugger requested, but was not available (ensure ruby-debug is listed in Gemfile/installed as gem): Start server with --debugger to enable *****\n" + message = "\n***** Debugger requested, but was not available (ensure ruby-debug19 is listed in Gemfile/installed as gem): Start server with --debugger to enable *****\n" defined?(Rails) ? Rails.logger.info(message) : $stderr.puts(message) end alias breakpoint debugger unless respond_to?(:breakpoint) diff --git a/activesupport/lib/active_support/core_ext/range/include_range.rb b/activesupport/lib/active_support/core_ext/range/include_range.rb index 0246627467..684b7cbc4a 100644 --- a/activesupport/lib/active_support/core_ext/range/include_range.rb +++ b/activesupport/lib/active_support/core_ext/range/include_range.rb @@ -9,9 +9,9 @@ class Range # (5..9).include?(11) # => false def include_with_range?(value) if value.is_a?(::Range) - operator = exclude_end? ? :< : :<= - end_value = value.exclude_end? ? last.succ : last - include_without_range?(value.first) && (value.last <=> end_value).send(operator, 0) + # 1...10 includes 1..9 but it does not include 1..10. + operator = exclude_end? && !value.exclude_end? ? :< : :<= + include_without_range?(value.first) && value.last.send(operator, last) else include_without_range?(value) end diff --git a/activesupport/lib/active_support/core_ext/rexml.rb b/activesupport/lib/active_support/core_ext/rexml.rb deleted file mode 100644 index 0419ebc84b..0000000000 --- a/activesupport/lib/active_support/core_ext/rexml.rb +++ /dev/null @@ -1,46 +0,0 @@ -require 'active_support/core_ext/kernel/reporting' - -# Fixes the rexml vulnerability disclosed at: -# http://www.ruby-lang.org/en/news/2008/08/23/dos-vulnerability-in-rexml/ -# This fix is identical to rexml-expansion-fix version 1.0.1. -# -# We still need to distribute this fix because albeit the REXML -# in recent 1.8.7s is patched, it wasn't in early patchlevels. -require 'rexml/rexml' - -# Earlier versions of rexml defined REXML::Version, newer ones REXML::VERSION -unless (defined?(REXML::VERSION) ? REXML::VERSION : REXML::Version) > "3.1.7.2" - silence_warnings { require 'rexml/document' } - - # REXML in 1.8.7 has the patch but early patchlevels didn't update Version from 3.1.7.2. - unless REXML::Document.respond_to?(:entity_expansion_limit=) - silence_warnings { require 'rexml/entity' } - - module REXML #:nodoc: - class Entity < Child #:nodoc: - undef_method :unnormalized - def unnormalized - document.record_entity_expansion! if document - v = value() - return nil if v.nil? - @unnormalized = Text::unnormalize(v, parent) - @unnormalized - end - end - class Document < Element #:nodoc: - @@entity_expansion_limit = 10_000 - def self.entity_expansion_limit= val - @@entity_expansion_limit = val - end - - def record_entity_expansion! - @number_of_expansions ||= 0 - @number_of_expansions += 1 - if @number_of_expansions > @@entity_expansion_limit - raise "Number of entity expansions exceeded, processing aborted." - end - end - end - end - end -end diff --git a/activesupport/lib/active_support/core_ext/string/filters.rb b/activesupport/lib/active_support/core_ext/string/filters.rb index d478ee0ef6..1a34e88a87 100644 --- a/activesupport/lib/active_support/core_ext/string/filters.rb +++ b/activesupport/lib/active_support/core_ext/string/filters.rb @@ -36,14 +36,13 @@ class String # "And they found that many people were sleeping better.".truncate(25, :omission => "... (continued)") # # => "And they f... (continued)" def truncate(length, options = {}) - text = self.dup - options[:omission] ||= "..." + return self.dup unless self.length > length - length_with_room_for_omission = length - options[:omission].mb_chars.length - chars = text.mb_chars + options[:omission] ||= "..." + length_with_room_for_omission = length - options[:omission].length stop = options[:separator] ? - (chars.rindex(options[:separator].mb_chars, length_with_room_for_omission) || length_with_room_for_omission) : length_with_room_for_omission + (rindex(options[:separator], length_with_room_for_omission) || length_with_room_for_omission) : length_with_room_for_omission - (chars.length > length ? chars[0...stop] + options[:omission] : text).to_s + self[0...stop] + options[:omission] end end diff --git a/activesupport/lib/active_support/core_ext/string/output_safety.rb b/activesupport/lib/active_support/core_ext/string/output_safety.rb index 6cb2ea68b3..73aa7dd89a 100644 --- a/activesupport/lib/active_support/core_ext/string/output_safety.rb +++ b/activesupport/lib/active_support/core_ext/string/output_safety.rb @@ -136,11 +136,6 @@ module ActiveSupport #:nodoc: coder.represent_scalar nil, to_str end - def to_yaml(*args) - return super() if defined?(YAML::ENGINE) && !YAML::ENGINE.syck? - to_str.to_yaml(*args) - end - UNSAFE_STRING_METHODS.each do |unsafe_method| if 'String'.respond_to?(unsafe_method) class_eval <<-EOT, __FILE__, __LINE__ + 1 diff --git a/activesupport/lib/active_support/core_ext/time/calculations.rb b/activesupport/lib/active_support/core_ext/time/calculations.rb index f3235d11bb..5e433f5dd9 100644 --- a/activesupport/lib/active_support/core_ext/time/calculations.rb +++ b/activesupport/lib/active_support/core_ext/time/calculations.rb @@ -78,7 +78,7 @@ class Time options[:hour] || hour, options[:min] || (options[:hour] ? 0 : min), options[:sec] || ((options[:hour] || options[:min]) ? 0 : sec), - options[:usec] || ((options[:hour] || options[:min] || options[:sec]) ? 0 : usec) + options[:usec] || ((options[:hour] || options[:min] || options[:sec]) ? 0 : Rational(nsec, 1000)) ) end diff --git a/activesupport/lib/active_support/deprecation/behaviors.rb b/activesupport/lib/active_support/deprecation/behaviors.rb index f9505a247c..80dcaf5613 100644 --- a/activesupport/lib/active_support/deprecation/behaviors.rb +++ b/activesupport/lib/active_support/deprecation/behaviors.rb @@ -34,8 +34,8 @@ module ActiveSupport if defined?(Rails) && Rails.logger Rails.logger else - require 'logger' - Logger.new($stderr) + require 'active_support/logger' + ActiveSupport::Logger.new($stderr) end logger.warn message logger.debug callstack.join("\n ") if debug diff --git a/activesupport/lib/active_support/duration.rb b/activesupport/lib/active_support/duration.rb index 89b0923882..00c67a470d 100644 --- a/activesupport/lib/active_support/duration.rb +++ b/activesupport/lib/active_support/duration.rb @@ -10,7 +10,6 @@ module ActiveSupport # 1.month.ago # equivalent to Time.now.advance(:months => -1) class Duration < BasicObject attr_accessor :value, :parts - delegate :duplicable?, :to => :value # required when using ActiveSupport's BasicObject on 1.8 def initialize(value, parts) #:nodoc: @value, @parts = value, parts diff --git a/activesupport/lib/active_support/inflector/methods.rb b/activesupport/lib/active_support/inflector/methods.rb index 144cdd3c8f..7f325aee94 100644 --- a/activesupport/lib/active_support/inflector/methods.rb +++ b/activesupport/lib/active_support/inflector/methods.rb @@ -186,47 +186,32 @@ module ActiveSupport underscore(demodulize(class_name)) + (separate_class_name_and_id_with_underscore ? "_id" : "id") end - # Ruby 1.9 introduces an inherit argument for Module#const_get and - # #const_defined? and changes their default behavior. - if Module.method(:const_get).arity == 1 - # Tries to find a constant with the name specified in the argument string: - # - # "Module".constantize # => Module - # "Test::Unit".constantize # => Test::Unit - # - # The name is assumed to be the one of a top-level constant, no matter whether - # it starts with "::" or not. No lexical context is taken into account: - # - # C = 'outside' - # module M - # C = 'inside' - # C # => 'inside' - # "C".constantize # => 'outside', same as ::C - # end - # - # NameError is raised when the name is not in CamelCase or the constant is - # unknown. - def constantize(camel_cased_word) - names = camel_cased_word.split('::') - names.shift if names.empty? || names.first.empty? - - constant = Object - names.each do |name| - constant = constant.const_defined?(name) ? constant.const_get(name) : constant.const_missing(name) - end - constant - end - else - def constantize(camel_cased_word) #:nodoc: - names = camel_cased_word.split('::') - names.shift if names.empty? || names.first.empty? + # Tries to find a constant with the name specified in the argument string: + # + # "Module".constantize # => Module + # "Test::Unit".constantize # => Test::Unit + # + # The name is assumed to be the one of a top-level constant, no matter whether + # it starts with "::" or not. No lexical context is taken into account: + # + # C = 'outside' + # module M + # C = 'inside' + # C # => 'inside' + # "C".constantize # => 'outside', same as ::C + # end + # + # NameError is raised when the name is not in CamelCase or the constant is + # unknown. + def constantize(camel_cased_word) #:nodoc: + names = camel_cased_word.split('::') + names.shift if names.empty? || names.first.empty? - constant = Object - names.each do |name| - constant = constant.const_defined?(name, false) ? constant.const_get(name) : constant.const_missing(name) - end - constant + constant = Object + names.each do |name| + constant = constant.const_defined?(name, false) ? constant.const_get(name) : constant.const_missing(name) end + constant end # Tries to find a constant with the name specified in the argument string: diff --git a/activesupport/lib/active_support/json/encoding.rb b/activesupport/lib/active_support/json/encoding.rb index d7181035d3..07b6a940c6 100644 --- a/activesupport/lib/active_support/json/encoding.rb +++ b/activesupport/lib/active_support/json/encoding.rb @@ -206,6 +206,10 @@ module Enumerable end end +class Range + def as_json(options = nil) to_s end #:nodoc: +end + class Array def as_json(options = nil) #:nodoc: # use encoder as a proxy to call as_json on all elements, to protect from circular references diff --git a/activesupport/lib/active_support/message_encryptor.rb b/activesupport/lib/active_support/message_encryptor.rb index 7d8a7fb687..6ec5a04933 100644 --- a/activesupport/lib/active_support/message_encryptor.rb +++ b/activesupport/lib/active_support/message_encryptor.rb @@ -1,5 +1,5 @@ require 'openssl' -require 'active_support/base64' +require 'base64' module ActiveSupport # MessageEncryptor is a simple way to encrypt values which get stored somewhere @@ -56,12 +56,12 @@ module ActiveSupport encrypted_data = cipher.update(@serializer.dump(value)) encrypted_data << cipher.final - [encrypted_data, iv].map {|v| ActiveSupport::Base64.encode64s(v)}.join("--") + [encrypted_data, iv].map {|v| ::Base64.strict_encode64(v)}.join("--") end def _decrypt(encrypted_message) cipher = new_cipher - encrypted_data, iv = encrypted_message.split("--").map {|v| ActiveSupport::Base64.decode64(v)} + encrypted_data, iv = encrypted_message.split("--").map {|v| ::Base64.decode64(v)} cipher.decrypt cipher.key = @secret diff --git a/activesupport/lib/active_support/message_verifier.rb b/activesupport/lib/active_support/message_verifier.rb index 30ac44f6fa..3b27089fa0 100644 --- a/activesupport/lib/active_support/message_verifier.rb +++ b/activesupport/lib/active_support/message_verifier.rb @@ -1,4 +1,4 @@ -require 'active_support/base64' +require 'base64' require 'active_support/core_ext/object/blank' module ActiveSupport @@ -18,7 +18,7 @@ module ActiveSupport # self.current_user = User.find(id) # end # - # By default it uses Marshal to serialize the message. If you want to use another + # By default it uses Marshal to serialize the message. If you want to use another # serialization method, you can set the serializer attribute to something that responds # to dump and load, e.g.: # @@ -37,14 +37,14 @@ module ActiveSupport data, digest = signed_message.split("--") if data.present? && digest.present? && secure_compare(digest, generate_digest(data)) - @serializer.load(ActiveSupport::Base64.decode64(data)) + @serializer.load(::Base64.decode64(data)) else raise InvalidSignature end end def generate(value) - data = ActiveSupport::Base64.encode64s(@serializer.dump(value)) + data = ::Base64.strict_encode64(@serializer.dump(value)) "#{data}--#{generate_digest(data)}" end diff --git a/activesupport/lib/active_support/multibyte.rb b/activesupport/lib/active_support/multibyte.rb index 57e8e24bf4..5efe13c537 100644 --- a/activesupport/lib/active_support/multibyte.rb +++ b/activesupport/lib/active_support/multibyte.rb @@ -1,9 +1,5 @@ -# encoding: utf-8 -require 'active_support/core_ext/module/attribute_accessors' - module ActiveSupport #:nodoc: module Multibyte - autoload :EncodingError, 'active_support/multibyte/exceptions' autoload :Chars, 'active_support/multibyte/chars' autoload :Unicode, 'active_support/multibyte/unicode' @@ -21,24 +17,5 @@ module ActiveSupport #:nodoc: def self.proxy_class @proxy_class ||= ActiveSupport::Multibyte::Chars end - - # Regular expressions that describe valid byte sequences for a character - VALID_CHARACTER = { - # Borrowed from the Kconv library by Shinji KONO - (also as seen on the W3C site) - 'UTF-8' => /\A(?: - [\x00-\x7f] | - [\xc2-\xdf] [\x80-\xbf] | - \xe0 [\xa0-\xbf] [\x80-\xbf] | - [\xe1-\xef] [\x80-\xbf] [\x80-\xbf] | - \xf0 [\x90-\xbf] [\x80-\xbf] [\x80-\xbf] | - [\xf1-\xf3] [\x80-\xbf] [\x80-\xbf] [\x80-\xbf] | - \xf4 [\x80-\x8f] [\x80-\xbf] [\x80-\xbf])\z /xn, - # Quick check for valid Shift-JIS characters, disregards the odd-even pairing - 'Shift_JIS' => /\A(?: - [\x00-\x7e\xa1-\xdf] | - [\x81-\x9f\xe0-\xef] [\x40-\x7e\x80-\x9e\x9f-\xfc])\z /xn - } end -end - -require 'active_support/multibyte/utils'
\ No newline at end of file +end
\ No newline at end of file diff --git a/activesupport/lib/active_support/multibyte/chars.rb b/activesupport/lib/active_support/multibyte/chars.rb index dcc176e93f..99b974e4a7 100644 --- a/activesupport/lib/active_support/multibyte/chars.rb +++ b/activesupport/lib/active_support/multibyte/chars.rb @@ -1,6 +1,7 @@ # encoding: utf-8 require 'active_support/core_ext/string/access' require 'active_support/core_ext/string/behavior' +require 'active_support/core_ext/module/delegation' module ActiveSupport #:nodoc: module Multibyte #:nodoc: @@ -34,10 +35,13 @@ module ActiveSupport #:nodoc: # # ActiveSupport::Multibyte.proxy_class = CharsForUTF32 class Chars + include Comparable attr_reader :wrapped_string alias to_s wrapped_string alias to_str wrapped_string + delegate :<=>, :=~, :acts_like_string?, :to => :wrapped_string + # Creates a new Chars instance by wrapping _string_. def initialize(string) @wrapped_string = string @@ -47,8 +51,8 @@ module ActiveSupport #:nodoc: # Forward all undefined methods to the wrapped string. def method_missing(method, *args, &block) if method.to_s =~ /!$/ - @wrapped_string.__send__(method, *args, &block) - self + result = @wrapped_string.__send__(method, *args, &block) + self if result else result = @wrapped_string.__send__(method, *args, &block) result.kind_of?(String) ? chars(result) : result @@ -61,35 +65,9 @@ module ActiveSupport #:nodoc: super || @wrapped_string.respond_to?(method, include_private) end - # Enable more predictable duck-typing on String-like classes. See Object#acts_like?. - def acts_like_string? - true - end - # Returns +true+ when the proxy class can handle the string. Returns +false+ otherwise. def self.consumes?(string) - # Unpack is a little bit faster than regular expressions. - string.unpack('U*') - true - rescue ArgumentError - false - end - - include Comparable - - # Returns -1, 0, or 1, depending on whether the Chars object is to be sorted before, - # equal or after the object on the right side of the operation. It accepts any object - # that implements +to_s+: - # - # 'é'.mb_chars <=> 'ü'.mb_chars # => -1 - # - # See <tt>String#<=></tt> for more details. - def <=>(other) - @wrapped_string <=> other.to_s - end - - def =~(other) - @wrapped_string =~ other + string.encoding == Encoding::UTF_8 end # Works just like <tt>String#split</tt>, with the exception that the items in the resulting list are Chars @@ -101,45 +79,10 @@ module ActiveSupport #:nodoc: @wrapped_string.split(*args).map { |i| i.mb_chars } end - # Like <tt>String#[]=</tt>, except instead of byte offsets you specify character offsets. - # - # Example: - # - # s = "Müller" - # s.mb_chars[2] = "e" # Replace character with offset 2 - # s - # # => "Müeler" - # - # s = "Müller" - # s.mb_chars[1, 2] = "ö" # Replace 2 characters at character offset 1 - # s - # # => "Möler" - def []=(*args) - replace_by = args.pop - # Indexed replace with regular expressions already works - if args.first.is_a?(Regexp) - @wrapped_string[*args] = replace_by - else - result = Unicode.u_unpack(@wrapped_string) - case args.first - when Fixnum - raise IndexError, "index #{args[0]} out of string" if args[0] >= result.length - min = args[0] - max = args[1].nil? ? min : (min + args[1] - 1) - range = Range.new(min, max) - replace_by = [replace_by].pack('U') if replace_by.is_a?(Fixnum) - when Range - raise RangeError, "#{args[0]} out of range" if args[0].min >= result.length - range = args[0] - else - needle = args[0].to_s - min = index(needle) - max = min + Unicode.u_unpack(needle).length - 1 - range = Range.new(min, max) - end - result[range] = Unicode.u_unpack(replace_by) - @wrapped_string.replace(result.pack('U*')) - end + # Works like like <tt>String#slice!</tt>, but returns an instance of Chars, or nil if the string was not + # modified. + def slice!(*args) + chars(@wrapped_string.slice!(*args)) end # Reverses all characters in the string. @@ -147,36 +90,8 @@ module ActiveSupport #:nodoc: # Example: # 'Café'.mb_chars.reverse.to_s # => 'éfaC' def reverse - chars(Unicode.g_unpack(@wrapped_string).reverse.flatten.pack('U*')) - end - - # Implements Unicode-aware slice with codepoints. Slicing on one point returns the codepoints for that - # character. - # - # Example: - # 'こんにちは'.mb_chars.slice(2..3).to_s # => "にち" - def slice(*args) - if args.size > 2 - raise ArgumentError, "wrong number of arguments (#{args.size} for 1)" # Do as if we were native - elsif (args.size == 2 && !(args.first.is_a?(Numeric) || args.first.is_a?(Regexp))) - raise TypeError, "cannot convert #{args.first.class} into Integer" # Do as if we were native - elsif (args.size == 2 && !args[1].is_a?(Numeric)) - raise TypeError, "cannot convert #{args[1].class} into Integer" # Do as if we were native - elsif args[0].kind_of? Range - cps = Unicode.u_unpack(@wrapped_string).slice(*args) - result = cps.nil? ? nil : cps.pack('U*') - elsif args[0].kind_of? Regexp - result = @wrapped_string.slice(*args) - elsif args.size == 1 && args[0].kind_of?(Numeric) - character = Unicode.u_unpack(@wrapped_string)[args[0]] - result = character && [character].pack('U') - else - cps = Unicode.u_unpack(@wrapped_string).slice(*args) - result = cps && cps.pack('U*') - end - result && chars(result) + chars(Unicode.unpack_graphemes(@wrapped_string).reverse.flatten.pack('U*')) end - alias_method :[], :slice # Limit the byte size of the string to a number of bytes without breaking characters. Usable # when the storage for a string is limited for some reason. @@ -192,7 +107,7 @@ module ActiveSupport #:nodoc: # Example: # 'Laurent, où sont les tests ?'.mb_chars.upcase.to_s # => "LAURENT, OÙ SONT LES TESTS ?" def upcase - chars(Unicode.apply_mapping @wrapped_string, :uppercase_mapping) + chars Unicode.upcase(@wrapped_string) end # Convert characters in the string to lowercase. @@ -200,7 +115,7 @@ module ActiveSupport #:nodoc: # Example: # 'VĚDA A VÝZKUM'.mb_chars.downcase.to_s # => "věda a výzkum" def downcase - chars(Unicode.apply_mapping @wrapped_string, :lowercase_mapping) + chars Unicode.downcase(@wrapped_string) end # Converts the first character to uppercase and the remainder to lowercase. @@ -217,7 +132,7 @@ module ActiveSupport #:nodoc: # "ÉL QUE SE ENTERÓ".mb_chars.titleize # => "Él Que Se Enteró" # "日本語".mb_chars.titleize # => "日本語" def titleize - chars(downcase.to_s.gsub(/\b('?[\S])/u) { Unicode.apply_mapping $1, :uppercase_mapping }) + chars(downcase.to_s.gsub(/\b('?[\S])/u) { Unicode.upcase($1)}) end alias_method :titlecase, :titleize @@ -237,7 +152,7 @@ module ActiveSupport #:nodoc: # 'é'.length # => 2 # 'é'.mb_chars.decompose.to_s.length # => 3 def decompose - chars(Unicode.decompose_codepoints(:canonical, Unicode.u_unpack(@wrapped_string)).pack('U*')) + chars(Unicode.decompose(:canonical, @wrapped_string.codepoints.to_a).pack('U*')) end # Performs composition on all the characters. @@ -246,16 +161,16 @@ module ActiveSupport #:nodoc: # 'é'.length # => 3 # 'é'.mb_chars.compose.to_s.length # => 2 def compose - chars(Unicode.compose_codepoints(Unicode.u_unpack(@wrapped_string)).pack('U*')) + chars(Unicode.compose(@wrapped_string.codepoints.to_a).pack('U*')) end # Returns the number of grapheme clusters in the string. # # Example: # 'क्षि'.mb_chars.length # => 4 - # 'क्षि'.mb_chars.g_length # => 3 - def g_length - Unicode.g_unpack(@wrapped_string).length + # 'क्षि'.mb_chars.grapheme_length # => 3 + def grapheme_length + Unicode.unpack_graphemes(@wrapped_string).length end # Replaces all ISO-8859-1 or CP1252 characters by their UTF-8 equivalent resulting in a valid UTF-8 string. @@ -265,14 +180,10 @@ module ActiveSupport #:nodoc: chars(Unicode.tidy_bytes(@wrapped_string, force)) end - %w(capitalize downcase lstrip reverse rstrip slice strip tidy_bytes upcase).each do |method| - # Only define a corresponding bang method for methods defined in the proxy; On 1.9 the proxy will - # exclude lstrip!, rstrip! and strip! because they are already work as expected on multibyte strings. - if public_method_defined?(method) - define_method("#{method}!") do |*args| - @wrapped_string = send(args.nil? ? method : method, *args).to_s - self - end + %w(capitalize downcase reverse tidy_bytes upcase).each do |method| + define_method("#{method}!") do |*args| + @wrapped_string = send(method, *args).to_s + self end end @@ -282,41 +193,14 @@ module ActiveSupport #:nodoc: return nil if byte_offset.nil? return 0 if @wrapped_string == '' - @wrapped_string = @wrapped_string.dup.force_encoding(Encoding::ASCII_8BIT) - begin - @wrapped_string[0...byte_offset].unpack('U*').length + @wrapped_string.byteslice(0...byte_offset).unpack('U*').length rescue ArgumentError byte_offset -= 1 retry end end - def justify(integer, way, padstr=' ') #:nodoc: - raise ArgumentError, "zero width padding" if padstr.length == 0 - padsize = integer - size - padsize = padsize > 0 ? padsize : 0 - case way - when :right - result = @wrapped_string.dup.insert(0, padding(padsize, padstr)) - when :left - result = @wrapped_string.dup.insert(-1, padding(padsize, padstr)) - when :center - lpad = padding((padsize / 2.0).floor, padstr) - rpad = padding((padsize / 2.0).ceil, padstr) - result = @wrapped_string.dup.insert(0, lpad).insert(-1, rpad) - end - chars(result) - end - - def padding(padsize, padstr=' ') #:nodoc: - if padsize != 0 - chars(padstr * ((padsize / Unicode.u_unpack(padstr).size) + 1)).slice(0, padsize) - else - '' - end - end - def chars(string) #:nodoc: self.class.new(string) end diff --git a/activesupport/lib/active_support/multibyte/exceptions.rb b/activesupport/lib/active_support/multibyte/exceptions.rb deleted file mode 100644 index 62066e3c71..0000000000 --- a/activesupport/lib/active_support/multibyte/exceptions.rb +++ /dev/null @@ -1,8 +0,0 @@ -# encoding: utf-8 - -module ActiveSupport #:nodoc: - module Multibyte #:nodoc: - # Raised when a problem with the encoding was found. - class EncodingError < StandardError; end - end -end
\ No newline at end of file diff --git a/activesupport/lib/active_support/multibyte/unicode.rb b/activesupport/lib/active_support/multibyte/unicode.rb index 754ca9290b..94fb0a48aa 100644 --- a/activesupport/lib/active_support/multibyte/unicode.rb +++ b/activesupport/lib/active_support/multibyte/unicode.rb @@ -10,7 +10,7 @@ module ActiveSupport NORMALIZATION_FORMS = [:c, :kc, :d, :kd] # The Unicode version that is supported by the implementation - UNICODE_VERSION = '5.2.0' + UNICODE_VERSION = '6.0.0' # The default normalization used for operations that require normalization. It can be set to any of the # normalizations in NORMALIZATION_FORMS. @@ -61,19 +61,6 @@ module ActiveSupport TRAILERS_PAT = /(#{codepoints_to_pattern(LEADERS_AND_TRAILERS)})+\Z/u LEADERS_PAT = /\A(#{codepoints_to_pattern(LEADERS_AND_TRAILERS)})+/u - # Unpack the string at codepoints boundaries. Raises an EncodingError when the encoding of the string isn't - # valid UTF-8. - # - # Example: - # Unicode.u_unpack('Café') # => [67, 97, 102, 233] - def u_unpack(string) - begin - string.unpack 'U*' - rescue ArgumentError - raise EncodingError, 'malformed UTF-8 character' - end - end - # Detect whether the codepoint is in a certain character class. Returns +true+ when it's in the specified # character class and +false+ otherwise. Valid character classes are: <tt>:cr</tt>, <tt>:lf</tt>, <tt>:l</tt>, # <tt>:v</tt>, <tt>:lv</tt>, <tt>:lvt</tt> and <tt>:t</tt>. @@ -86,10 +73,10 @@ module ActiveSupport # Unpack the string at grapheme boundaries. Returns a list of character lists. # # Example: - # Unicode.g_unpack('क्षि') # => [[2325, 2381], [2359], [2367]] - # Unicode.g_unpack('Café') # => [[67], [97], [102], [233]] - def g_unpack(string) - codepoints = u_unpack(string) + # Unicode.unpack_graphemes('क्षि') # => [[2325, 2381], [2359], [2367]] + # Unicode.unpack_graphemes('Café') # => [[67], [97], [102], [233]] + def unpack_graphemes(string) + codepoints = string.codepoints.to_a unpacked = [] pos = 0 marker = 0 @@ -118,12 +105,12 @@ module ActiveSupport unpacked end - # Reverse operation of g_unpack. + # Reverse operation of unpack_graphemes. # # Example: - # Unicode.g_pack(Unicode.g_unpack('क्षि')) # => 'क्षि' - def g_pack(unpacked) - (unpacked.flatten).pack('U*') + # Unicode.pack_graphemes(Unicode.unpack_graphemes('क्षि')) # => 'क्षि' + def pack_graphemes(unpacked) + unpacked.flatten.pack('U*') end # Re-order codepoints so the string becomes canonical. @@ -143,7 +130,7 @@ module ActiveSupport end # Decompose composed characters to the decomposed form. - def decompose_codepoints(type, codepoints) + def decompose(type, codepoints) codepoints.inject([]) do |decomposed, cp| # if it's a hangul syllable starter character if HANGUL_SBASE <= cp and cp < HANGUL_SLAST @@ -156,7 +143,7 @@ module ActiveSupport decomposed.concat ncp # if the codepoint is decomposable in with the current decomposition type elsif (ncp = database.codepoints[cp].decomp_mapping) and (!database.codepoints[cp].decomp_type || type == :compatability) - decomposed.concat decompose_codepoints(type, ncp.dup) + decomposed.concat decompose(type, ncp.dup) else decomposed << cp end @@ -164,7 +151,7 @@ module ActiveSupport end # Compose decomposed characters to the composed form. - def compose_codepoints(codepoints) + def compose(codepoints) pos = 0 eoa = codepoints.length - 1 starter_pos = 0 @@ -283,30 +270,27 @@ module ActiveSupport def normalize(string, form=nil) form ||= @default_normalization_form # See http://www.unicode.org/reports/tr15, Table 1 - codepoints = u_unpack(string) + codepoints = string.codepoints.to_a case form when :d - reorder_characters(decompose_codepoints(:canonical, codepoints)) + reorder_characters(decompose(:canonical, codepoints)) when :c - compose_codepoints(reorder_characters(decompose_codepoints(:canonical, codepoints))) + compose(reorder_characters(decompose(:canonical, codepoints))) when :kd - reorder_characters(decompose_codepoints(:compatability, codepoints)) + reorder_characters(decompose(:compatability, codepoints)) when :kc - compose_codepoints(reorder_characters(decompose_codepoints(:compatability, codepoints))) + compose(reorder_characters(decompose(:compatability, codepoints))) else raise ArgumentError, "#{form} is not a valid normalization variant", caller end.pack('U*') end - def apply_mapping(string, mapping) #:nodoc: - u_unpack(string).map do |codepoint| - cp = database.codepoints[codepoint] - if cp and (ncp = cp.send(mapping)) and ncp > 0 - ncp - else - codepoint - end - end.pack('U*') + def downcase(string) + apply_mapping string, :lowercase_mapping + end + + def upcase(string) + apply_mapping string, :uppercase_mapping end # Holds data about a codepoint in the Unicode database @@ -374,6 +358,17 @@ module ActiveSupport private + def apply_mapping(string, mapping) #:nodoc: + string.each_codepoint.map do |codepoint| + cp = database.codepoints[codepoint] + if cp and (ncp = cp.send(mapping)) and ncp > 0 + ncp + else + codepoint + end + end.pack('U*') + end + def tidy_byte(byte) if byte < 160 [database.cp1252[byte] || byte].pack("U").unpack("C*") diff --git a/activesupport/lib/active_support/multibyte/utils.rb b/activesupport/lib/active_support/multibyte/utils.rb deleted file mode 100644 index bd6d4bad41..0000000000 --- a/activesupport/lib/active_support/multibyte/utils.rb +++ /dev/null @@ -1,27 +0,0 @@ -# encoding: utf-8 - -module ActiveSupport #:nodoc: - module Multibyte #:nodoc: - # Returns a regular expression that matches valid characters in the current encoding - def self.valid_character - VALID_CHARACTER[Encoding.default_external.to_s] - end - - # Verifies the encoding of a string - def self.verify(string) - string.valid_encoding? - end - - # Verifies the encoding of the string and raises an exception when it's not valid - def self.verify!(string) - raise EncodingError.new("Found characters with invalid encoding") unless verify(string) - end - - # Removes all invalid characters from the string. - # - # Note: this method is a no-op in Ruby 1.9 - def self.clean(string) - string - end - end -end diff --git a/activesupport/lib/active_support/ordered_hash.rb b/activesupport/lib/active_support/ordered_hash.rb index d4f309fbd7..8edd3960c7 100644 --- a/activesupport/lib/active_support/ordered_hash.rb +++ b/activesupport/lib/active_support/ordered_hash.rb @@ -1,8 +1,3 @@ -begin - require 'psych' -rescue LoadError -end - require 'yaml' YAML.add_builtin_type("omap") do |type, val| @@ -29,20 +24,6 @@ module ActiveSupport coder.represent_seq '!omap', map { |k,v| { k => v } } end - def to_yaml(opts = {}) - if YAML.const_defined?(:ENGINE) && !YAML::ENGINE.syck? - return super - end - - YAML.quick_emit(self, opts) do |out| - out.seq(taguri) do |seq| - each do |k, v| - seq.add(k => v) - end - end - end - end - def nested_under_indifferent_access self end diff --git a/activesupport/lib/active_support/ruby/shim.rb b/activesupport/lib/active_support/ruby/shim.rb index 9652eb4028..41fd866481 100644 --- a/activesupport/lib/active_support/ruby/shim.rb +++ b/activesupport/lib/active_support/ruby/shim.rb @@ -4,7 +4,6 @@ # Date next_year, next_month # DateTime to_date, to_datetime, xmlschema # Enumerable group_by, none? -# REXML security fix # String ord # Time to_date, to_time, to_datetime require 'active_support' @@ -14,5 +13,4 @@ require 'active_support/core_ext/enumerable' require 'active_support/core_ext/string/conversions' require 'active_support/core_ext/string/interpolation' require 'active_support/core_ext/string/encoding' -require 'active_support/core_ext/rexml' require 'active_support/core_ext/time/conversions' diff --git a/activesupport/lib/active_support/test_case.rb b/activesupport/lib/active_support/test_case.rb index 8d6c27e381..707544e594 100644 --- a/activesupport/lib/active_support/test_case.rb +++ b/activesupport/lib/active_support/test_case.rb @@ -10,15 +10,9 @@ require 'active_support/core_ext/kernel/reporting' module ActiveSupport class TestCase < ::Test::Unit::TestCase - if defined? MiniTest - Assertion = MiniTest::Assertion - alias_method :method_name, :name if method_defined? :name - alias_method :method_name, :__name__ if method_defined? :__name__ - else - Assertion = Test::Unit::AssertionFailedError - - undef :default_test - end + Assertion = MiniTest::Assertion + alias_method :method_name, :name if method_defined? :name + alias_method :method_name, :__name__ if method_defined? :__name__ $tags = {} def self.for_tag(tag) diff --git a/activesupport/lib/active_support/testing/isolation.rb b/activesupport/lib/active_support/testing/isolation.rb index 6b29ba4c10..c896b955fb 100644 --- a/activesupport/lib/active_support/testing/isolation.rb +++ b/activesupport/lib/active_support/testing/isolation.rb @@ -38,11 +38,7 @@ module ActiveSupport end def self.included(base) - if defined?(::MiniTest) && base < ::MiniTest::Unit::TestCase - base.send :include, MiniTest - elsif defined?(Test::Unit) - base.send :include, TestUnit - end + base.send :include, MiniTest end def _run_class_setup # class setup method should only happen in parent @@ -52,30 +48,6 @@ module ActiveSupport end end - module TestUnit - def run(result) - _run_class_setup - - yield(Test::Unit::TestCase::STARTED, name) - - @_result = result - - serialized = run_in_isolation do |proxy| - begin - super(proxy) { } - rescue Exception => e - proxy.add_error(Test::Unit::Error.new(name, e)) - end - end - - retval, proxy = Marshal.load(serialized) - proxy.__replay__(@_result) - - yield(Test::Unit::TestCase::FINISHED, name) - retval - end - end - module MiniTest def run(runner) _run_class_setup diff --git a/activesupport/lib/active_support/testing/pending.rb b/activesupport/lib/active_support/testing/pending.rb index feac7bc347..510f80f32c 100644 --- a/activesupport/lib/active_support/testing/pending.rb +++ b/activesupport/lib/active_support/testing/pending.rb @@ -11,39 +11,7 @@ module ActiveSupport @@at_exit = false def pending(description = "", &block) - if defined?(::MiniTest) - skip(description.blank? ? nil : description) - else - if description.is_a?(Symbol) - is_pending = $tags[description] - return block.call unless is_pending - end - - if block_given? - failed = false - - begin - block.call - rescue Exception - failed = true - end - - flunk("<#{description}> did not fail.") unless failed - end - - caller[0] =~ (/(.*):(.*):in `(.*)'/) - @@pending_cases << "#{$3} at #{$1}, line #{$2}" - print "P" - - @@at_exit ||= begin - at_exit do - puts "\nPending Cases:" - @@pending_cases.each do |test_case| - puts test_case - end - end - end - end + skip(description.blank? ? nil : description) end end diff --git a/activesupport/lib/active_support/testing/performance.rb b/activesupport/lib/active_support/testing/performance.rb index dd23f8d82d..209bfac19f 100644 --- a/activesupport/lib/active_support/testing/performance.rb +++ b/activesupport/lib/active_support/testing/performance.rb @@ -13,12 +13,7 @@ module ActiveSupport included do superclass_delegating_accessor :profile_options self.profile_options = {} - - if defined?(MiniTest::Assertions) && TestCase < MiniTest::Assertions - include ForMiniTest - else - include ForClassicTestUnit - end + include ForMiniTest end # each implementation should define metrics and freeze the defaults @@ -77,48 +72,6 @@ module ActiveSupport end end - module ForClassicTestUnit - def run(result) - return if method_name =~ /^default_test$/ - - yield(self.class::STARTED, name) - @_result = result - - run_warmup - if full_profile_options && metrics = full_profile_options[:metrics] - metrics.each do |metric_name| - if klass = Metrics[metric_name.to_sym] - run_profile(klass.new) - result.add_run - else - puts '%20s: unsupported' % metric_name - end - end - end - - yield(self.class::FINISHED, name) - end - - def run_test(metric, mode) - run_callbacks :setup - setup - metric.send(mode) { __send__ @method_name } - rescue ::Test::Unit::AssertionFailedError => e - add_failure(e.message, e.backtrace) - rescue StandardError, ScriptError => e - add_error(e) - ensure - begin - teardown - run_callbacks :teardown, :enumerator => :reverse_each - rescue ::Test::Unit::AssertionFailedError => e - add_failure(e.message, e.backtrace) - rescue StandardError, ScriptError => e - add_error(e) - end - end - end - protected # overridden by each implementation def run_gc; end @@ -208,8 +161,7 @@ module ActiveSupport end end - ruby = defined?(RUBY_ENGINE) ? RUBY_ENGINE : 'ruby' - ruby += "-#{RUBY_VERSION}.#{RUBY_PATCHLEVEL}" + ruby = "#{RUBY_ENGINE}-#{RUBY_VERSION}.#{RUBY_PATCHLEVEL}" @env = [app, rails, ruby, RUBY_PLATFORM] * ',' end @@ -306,7 +258,6 @@ module ActiveSupport end end -RUBY_ENGINE = 'ruby' unless defined?(RUBY_ENGINE) # mri 1.8 case RUBY_ENGINE when 'ruby' then require 'active_support/testing/performance/ruby' when 'rbx' then require 'active_support/testing/performance/rubinius' diff --git a/activesupport/lib/active_support/testing/performance/ruby/yarv.rb b/activesupport/lib/active_support/testing/performance/ruby/yarv.rb index 7873262331..c34d31bf10 100644 --- a/activesupport/lib/active_support/testing/performance/ruby/yarv.rb +++ b/activesupport/lib/active_support/testing/performance/ruby/yarv.rb @@ -4,15 +4,12 @@ module ActiveSupport module Metrics class Base protected - # Ruby 1.9 with GC::Profiler - if defined?(GC::Profiler) - def with_gc_stats - GC::Profiler.enable - GC.start - yield - ensure - GC::Profiler.disable - end + def with_gc_stats + GC::Profiler.enable + GC.start + yield + ensure + GC::Profiler.disable end end @@ -35,20 +32,14 @@ module ActiveSupport end class GcRuns < Amount - # Ruby 1.9 - if GC.respond_to?(:count) - def measure - GC.count - end + def measure + GC.count end end class GcTime < Time - # Ruby 1.9 with GC::Profiler - if defined?(GC::Profiler) && GC::Profiler.respond_to?(:total_time) - def measure - GC::Profiler.total_time - end + def measure + GC::Profiler.total_time end end end diff --git a/activesupport/lib/active_support/testing/setup_and_teardown.rb b/activesupport/lib/active_support/testing/setup_and_teardown.rb index 22e41fa905..40b781485e 100644 --- a/activesupport/lib/active_support/testing/setup_and_teardown.rb +++ b/activesupport/lib/active_support/testing/setup_and_teardown.rb @@ -10,11 +10,7 @@ module ActiveSupport include ActiveSupport::Callbacks define_callbacks :setup, :teardown - if defined?(MiniTest::Assertions) && TestCase < MiniTest::Assertions - include ForMiniTest - else - include ForClassicTestUnit - end + include ForMiniTest end module ClassMethods @@ -47,65 +43,6 @@ module ActiveSupport end end - module ForClassicTestUnit - # For compatibility with Ruby < 1.8.6 - PASSTHROUGH_EXCEPTIONS = Test::Unit::TestCase::PASSTHROUGH_EXCEPTIONS rescue [NoMemoryError, SignalException, Interrupt, SystemExit] - - # This redefinition is unfortunate but test/unit shows us no alternative. - # Doubly unfortunate: hax to support Mocha's hax. - def run(result) - return if @method_name.to_s == "default_test" - - mocha_counter = retrieve_mocha_counter(result) - yield(Test::Unit::TestCase::STARTED, name) - @_result = result - - begin - begin - run_callbacks :setup do - setup - __send__(@method_name) - mocha_verify(mocha_counter) if mocha_counter - end - rescue Mocha::ExpectationError => e - add_failure(e.message, e.backtrace) - rescue Test::Unit::AssertionFailedError => e - add_failure(e.message, e.backtrace) - rescue Exception => e - raise if PASSTHROUGH_EXCEPTIONS.include?(e.class) - add_error(e) - ensure - begin - teardown - run_callbacks :teardown - rescue Test::Unit::AssertionFailedError => e - add_failure(e.message, e.backtrace) - rescue Exception => e - raise if PASSTHROUGH_EXCEPTIONS.include?(e.class) - add_error(e) - end - end - ensure - mocha_teardown if mocha_counter - end - - result.add_run - yield(Test::Unit::TestCase::FINISHED, name) - end - - protected - - def retrieve_mocha_counter(result) #:nodoc: - if respond_to?(:mocha_verify) # using mocha - if defined?(Mocha::TestCaseAdapter::AssertionCounter) - Mocha::TestCaseAdapter::AssertionCounter.new(result) - else - Mocha::Integration::TestUnit::AssertionCounter.new(result) - end - end - end - end - end end end diff --git a/activesupport/lib/active_support/time_with_zone.rb b/activesupport/lib/active_support/time_with_zone.rb index d3adf671a0..1cb71012ef 100644 --- a/activesupport/lib/active_support/time_with_zone.rb +++ b/activesupport/lib/active_support/time_with_zone.rb @@ -1,4 +1,4 @@ -require "active_support/values/time_zone" +require 'active_support/values/time_zone' require 'active_support/core_ext/object/acts_like' require 'active_support/core_ext/object/inclusion' @@ -146,12 +146,6 @@ module ActiveSupport end end - def to_yaml(options = {}) - return super if defined?(YAML::ENGINE) && !YAML::ENGINE.syck? - - utc.to_yaml(options) - end - def httpdate utc.httpdate end diff --git a/activesupport/lib/active_support/values/unicode_tables.dat b/activesupport/lib/active_support/values/unicode_tables.dat Binary files differindex 4fe0268cca..7edc4663e8 100644 --- a/activesupport/lib/active_support/values/unicode_tables.dat +++ b/activesupport/lib/active_support/values/unicode_tables.dat diff --git a/activesupport/lib/active_support/xml_mini.rb b/activesupport/lib/active_support/xml_mini.rb index 1ea9a9d7e1..677e9910bb 100644 --- a/activesupport/lib/active_support/xml_mini.rb +++ b/activesupport/lib/active_support/xml_mini.rb @@ -1,4 +1,5 @@ require 'time' +require 'base64' require 'active_support/core_ext/module/delegation' require 'active_support/core_ext/string/inflections' @@ -48,7 +49,7 @@ module ActiveSupport "symbol" => Proc.new { |symbol| symbol.to_s }, "date" => Proc.new { |date| date.to_s(:db) }, "datetime" => Proc.new { |time| time.xmlschema }, - "binary" => Proc.new { |binary| ActiveSupport::Base64.encode64(binary) }, + "binary" => Proc.new { |binary| ::Base64.encode64(binary) }, "yaml" => Proc.new { |yaml| yaml.to_yaml } } unless defined?(FORMATTING) @@ -64,7 +65,7 @@ module ActiveSupport "boolean" => Proc.new { |boolean| %w(1 true).include?(boolean.strip) }, "string" => Proc.new { |string| string.to_s }, "yaml" => Proc.new { |yaml| YAML::load(yaml) rescue yaml }, - "base64Binary" => Proc.new { |bin| ActiveSupport::Base64.decode64(bin) }, + "base64Binary" => Proc.new { |bin| ::Base64.decode64(bin) }, "binary" => Proc.new { |bin, entity| _parse_binary(bin, entity) }, "file" => Proc.new { |file, entity| _parse_file(file, entity) } } @@ -148,14 +149,14 @@ module ActiveSupport def _parse_binary(bin, entity) #:nodoc: case entity['encoding'] when 'base64' - ActiveSupport::Base64.decode64(bin) + ::Base64.decode64(bin) else bin end end def _parse_file(file, entity) - f = StringIO.new(ActiveSupport::Base64.decode64(file)) + f = StringIO.new(::Base64.decode64(file)) f.extend(FileLike) f.original_filename = entity['name'] f.content_type = entity['content_type'] diff --git a/activesupport/test/buffered_logger_test.rb b/activesupport/test/buffered_logger_test.rb index b9891c74c8..4ed425732a 100644 --- a/activesupport/test/buffered_logger_test.rb +++ b/activesupport/test/buffered_logger_test.rb @@ -3,7 +3,6 @@ require 'multibyte_test_helpers' require 'stringio' require 'fileutils' require 'tempfile' -require 'active_support/buffered_logger' require 'active_support/testing/deprecation' class BufferedLoggerTest < Test::Unit::TestCase diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb index aa6fb14e7b..3454c378d3 100644 --- a/activesupport/test/caching_test.rb +++ b/activesupport/test/caching_test.rb @@ -681,7 +681,7 @@ uses_memcached 'memcached backed store' do @data = @cache.instance_variable_get(:@data) @cache.clear @cache.silence! - @cache.logger = Logger.new("/dev/null") + @cache.logger = ActiveSupport::Logger.new("/dev/null") end include CacheStoreBehavior @@ -786,7 +786,7 @@ class CacheStoreLoggerTest < ActiveSupport::TestCase @cache = ActiveSupport::Cache.lookup_store(:memory_store) @buffer = StringIO.new - @cache.logger = Logger.new(@buffer) + @cache.logger = ActiveSupport::Logger.new(@buffer) end def test_logging diff --git a/activesupport/test/core_ext/base64_ext_test.rb b/activesupport/test/core_ext/base64_ext_test.rb deleted file mode 100644 index bd0e9f843d..0000000000 --- a/activesupport/test/core_ext/base64_ext_test.rb +++ /dev/null @@ -1,8 +0,0 @@ -require 'abstract_unit' - -class Base64Test < Test::Unit::TestCase - def test_no_newline_in_encoded_value - assert_match(/\n/, ActiveSupport::Base64.encode64("oneverylongstringthatwouldnormallybesplitupbynewlinesbytheregularbase64")) - assert_no_match(/\n/, ActiveSupport::Base64.encode64s("oneverylongstringthatwouldnormallybesplitupbynewlinesbytheregularbase64")) - end -end diff --git a/activesupport/test/core_ext/range_ext_test.rb b/activesupport/test/core_ext/range_ext_test.rb index f4b773e5fb..e50b6c132a 100644 --- a/activesupport/test/core_ext/range_ext_test.rb +++ b/activesupport/test/core_ext/range_ext_test.rb @@ -53,6 +53,10 @@ class RangeTest < Test::Unit::TestCase assert !(2..8).include?(5..9) end + def test_should_include_identical_exclusive_with_floats + assert((1.0...10.0).include?(1.0...10.0)) + end + def test_blockless_step assert_equal [1,3,5,7,9], (1..10).step(2) end diff --git a/activesupport/test/core_ext/time_ext_test.rb b/activesupport/test/core_ext/time_ext_test.rb index 6cc63851e9..1c22a79d75 100644 --- a/activesupport/test/core_ext/time_ext_test.rb +++ b/activesupport/test/core_ext/time_ext_test.rb @@ -491,6 +491,11 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase assert_equal Time.utc(2013,10,17,20,22,19), Time.utc(2005,2,28,15,15,10).advance(:years => 7, :months => 19, :weeks => 2, :days => 5, :hours => 5, :minutes => 7, :seconds => 9) end + def test_advance_with_nsec + t = Time.at(0, Rational(108635108, 1000)) + assert_equal t, t.advance(:months => 0) + end + def test_prev_week with_env_tz 'US/Eastern' do assert_equal Time.local(2005,2,21), Time.local(2005,3,1,15,15,10).prev_week diff --git a/activesupport/test/isolation_test.rb b/activesupport/test/isolation_test.rb index 2c2986ea28..c1932d73d9 100644 --- a/activesupport/test/isolation_test.rb +++ b/activesupport/test/isolation_test.rb @@ -80,26 +80,6 @@ else ENV.delete("CHILD") def setup - defined?(::MiniTest) ? parse_minitest : parse_testunit - end - - def parse_testunit - @results = {} - OUTPUT[/Started\n\s*(.*)\s*\nFinished/mi, 1].to_s.split(/\s*\n\s*/).each do |result| - result =~ %r'^(\w+)\(\w+\):\s*(\.|E|F)$' - @results[$1] = { 'E' => :error, '.' => :success, 'F' => :failure }[$2] - end - - # Extract the backtraces - @backtraces = {} - OUTPUT.scan(/^\s*\d+\).*?\n\n/m).each do |backtrace| - # \n 1) Error:\ntest_captures_errors(ChildIsolationTest): - backtrace =~ %r'\s*\d+\)\s*(Error|Failure):\n(\w+)'i - @backtraces[$2] = { :type => $1, :output => backtrace } - end - end - - def parse_minitest @results = {} OUTPUT[/Started\n\s*(.*)\s*\nFinished/mi, 1].to_s.split(/\s*\n\s*/).each do |result| result =~ %r'^\w+#(\w+):.*:\s*(.*Assertion.*|.*RuntimeError.*|\.\s*)$' @@ -115,7 +95,7 @@ else OUTPUT.scan(/^\s*\d+\).*?\n\n/m).each do |backtrace| # \n 1) Error:\ntest_captures_errors(ChildIsolationTest): backtrace =~ %r'\s*\d+\)\s*(Error|Failure):\n(\w+)'i - @backtraces[$2] = { :type => $1, :output => backtrace } + @backtraces[$2] = {:type => $1, :output => backtrace} end end diff --git a/activesupport/test/json/encoding_test.rb b/activesupport/test/json/encoding_test.rb index a6435a763a..bebad18e99 100644 --- a/activesupport/test/json/encoding_test.rb +++ b/activesupport/test/json/encoding_test.rb @@ -38,6 +38,10 @@ class TestJSONEncoding < Test::Unit::TestCase ArrayTests = [[ ['a', 'b', 'c'], %([\"a\",\"b\",\"c\"]) ], [ [1, 'a', :b, nil, false], %([1,\"a\",\"b\",null,false]) ]] + RangeTests = [[ 1..2, %("1..2")], + [ 1...2, %("1...2")], + [ 1.5..2.5, %("1.5..2.5")]] + SymbolTests = [[ :a, %("a") ], [ :this, %("this") ], [ :"a b", %("a b") ]] diff --git a/activesupport/test/message_encryptor_test.rb b/activesupport/test/message_encryptor_test.rb index db97c1b80b..b544742300 100644 --- a/activesupport/test/message_encryptor_test.rb +++ b/activesupport/test/message_encryptor_test.rb @@ -76,10 +76,10 @@ class MessageEncryptorTest < ActiveSupport::TestCase end def munge(base64_string) - bits = ActiveSupport::Base64.decode64(base64_string) + bits = ::Base64.decode64(base64_string) bits.reverse! - ActiveSupport::Base64.encode64s(bits) + ::Base64.strict_encode64(bits) end end -end
\ No newline at end of file +end diff --git a/activesupport/test/multibyte_chars_test.rb b/activesupport/test/multibyte_chars_test.rb index 20e56e2c81..e36bd22081 100644 --- a/activesupport/test/multibyte_chars_test.rb +++ b/activesupport/test/multibyte_chars_test.rb @@ -7,6 +7,7 @@ class String def __method_for_multibyte_testing_with_integer_result; 1; end def __method_for_multibyte_testing; 'result'; end def __method_for_multibyte_testing!; 'result'; end + def __method_for_multibyte_testing_that_returns_nil!; end end class MultibyteCharsTest < Test::Unit::TestCase @@ -36,11 +37,15 @@ class MultibyteCharsTest < Test::Unit::TestCase assert_not_equal @chars.object_id, @chars.__method_for_multibyte_testing.object_id end - def test_forwarded_bang_method_calls_should_return_the_original_chars_instance + def test_forwarded_bang_method_calls_should_return_the_original_chars_instance_when_result_is_not_nil assert_kind_of @proxy_class, @chars.__method_for_multibyte_testing! assert_equal @chars.object_id, @chars.__method_for_multibyte_testing!.object_id end + def test_forwarded_bang_method_calls_should_return_nil_when_result_is_nil + assert_nil @chars.__method_for_multibyte_testing_that_returns_nil! + end + def test_methods_are_forwarded_to_wrapped_string_for_byte_strings assert_equal BYTE_STRING.class, BYTE_STRING.mb_chars.class end @@ -67,17 +72,6 @@ class MultibyteCharsTest < Test::Unit::TestCase assert !@proxy_class.consumes?(BYTE_STRING) end - def test_unpack_utf8_strings - assert_equal 4, ActiveSupport::Multibyte::Unicode.u_unpack(UNICODE_STRING).length - assert_equal 5, ActiveSupport::Multibyte::Unicode.u_unpack(ASCII_STRING).length - end - - def test_unpack_raises_encoding_error_on_broken_strings - assert_raise(ActiveSupport::Multibyte::EncodingError) do - ActiveSupport::Multibyte::Unicode.u_unpack(BYTE_STRING) - end - end - def test_concatenation_should_return_a_proxy_class_instance assert_equal ActiveSupport::Multibyte.proxy_class, ('a'.mb_chars + 'b').class assert_equal ActiveSupport::Multibyte.proxy_class, ('a'.mb_chars << 'b').class @@ -112,15 +106,11 @@ class MultibyteCharsUTF8BehaviourTest < Test::Unit::TestCase end end - def test_indexed_insert_accepts_fixnums - @chars[2] = 32 - assert_equal 'こに わ', @chars - end - - %w{capitalize downcase lstrip reverse rstrip strip upcase}.each do |method| + %w{capitalize downcase lstrip reverse rstrip upcase}.each do |method| class_eval(<<-EOTESTS) - def test_#{method}_bang_should_return_self - assert_equal @chars.object_id, @chars.send("#{method}!").object_id + def test_#{method}_bang_should_return_self_when_modifying_wrapped_string + chars = ' él piDió Un bUen café ' + assert_equal chars.object_id, chars.send("#{method}!").object_id end def test_#{method}_bang_should_change_wrapped_string @@ -419,7 +409,7 @@ class MultibyteCharsUTF8BehaviourTest < Test::Unit::TestCase def test_slice_bang_removes_the_slice_from_the_receiver chars = 'úüù'.mb_chars chars.slice!(0,2) - assert_equal 'úü', chars + assert_equal 'ù', chars end def test_slice_should_throw_exceptions_on_invalid_arguments @@ -506,7 +496,7 @@ class MultibyteCharsExtrasTest < Test::Unit::TestCase def test_limit_should_work_on_a_multibyte_string example = chars(UNICODE_STRING) - bytesize = UNICODE_STRING.respond_to?(:bytesize) ? UNICODE_STRING.bytesize : UNICODE_STRING.size + bytesize = UNICODE_STRING.bytesize assert_equal UNICODE_STRING, example.limit(bytesize) assert_equal '', example.limit(0) @@ -605,7 +595,7 @@ class MultibyteCharsExtrasTest < Test::Unit::TestCase else str = input end - assert_equal expected_length, chars(str).g_length + assert_equal expected_length, chars(str).grapheme_length end end diff --git a/activesupport/test/multibyte_utils_test.rb b/activesupport/test/multibyte_utils_test.rb deleted file mode 100644 index f807492be0..0000000000 --- a/activesupport/test/multibyte_utils_test.rb +++ /dev/null @@ -1,93 +0,0 @@ -# encoding: utf-8 - -require 'abstract_unit' -require 'multibyte_test_helpers' - -class MultibyteUtilsTest < ActiveSupport::TestCase - include MultibyteTestHelpers - - test "valid_character returns an expression for the current encoding" do - with_encoding('None') do - assert_nil ActiveSupport::Multibyte.valid_character - end - with_encoding('UTF8') do - assert_equal ActiveSupport::Multibyte::VALID_CHARACTER['UTF-8'], ActiveSupport::Multibyte.valid_character - end - with_encoding('SJIS') do - assert_equal ActiveSupport::Multibyte::VALID_CHARACTER['Shift_JIS'], ActiveSupport::Multibyte.valid_character - end - end - - test "verify verifies ASCII strings are properly encoded" do - with_encoding('None') do - examples.each do |example| - assert ActiveSupport::Multibyte.verify(example) - end - end - end - - test "verify verifies UTF-8 strings are properly encoded" do - with_encoding('UTF8') do - assert ActiveSupport::Multibyte.verify(example('valid UTF-8')) - assert !ActiveSupport::Multibyte.verify(example('invalid UTF-8')) - end - end - - test "verify verifies Shift-JIS strings are properly encoded" do - with_encoding('SJIS') do - assert ActiveSupport::Multibyte.verify(example('valid Shift-JIS')) - assert !ActiveSupport::Multibyte.verify(example('invalid Shift-JIS')) - end - end - - test "verify! raises an exception when it finds an invalid character" do - with_encoding('UTF8') do - assert_raises(ActiveSupport::Multibyte::EncodingError) do - ActiveSupport::Multibyte.verify!(example('invalid UTF-8')) - end - end - end - - test "verify! doesn't raise an exception when the encoding is valid" do - with_encoding('UTF8') do - assert_nothing_raised do - ActiveSupport::Multibyte.verify!(example('valid UTF-8')) - end - end - end - - test "clean is a no-op" do - with_encoding('UTF8') do - assert_equal example('invalid Shift-JIS'), ActiveSupport::Multibyte.clean(example('invalid Shift-JIS')) - end - end - - private - - STRINGS = { - 'valid ASCII' => [65, 83, 67, 73, 73].pack('C*'), - 'invalid ASCII' => [128].pack('C*'), - 'valid UTF-8' => [227, 129, 147, 227, 129, 171, 227, 129, 161, 227, 130, 143].pack('C*'), - 'invalid UTF-8' => [184, 158, 8, 136, 165].pack('C*'), - 'valid Shift-JIS' => [131, 122, 129, 91, 131, 128].pack('C*'), - 'invalid Shift-JIS' => [184, 158, 8, 0, 255, 136, 165].pack('C*') - } - - def example(key) - STRINGS[key].force_encoding(Encoding.default_external) - end - - def examples - STRINGS.values.map { |s| s.force_encoding(Encoding.default_external) } - end - - KCODE_TO_ENCODING = Hash.new(Encoding::BINARY). - update('UTF8' => Encoding::UTF_8, 'SJIS' => Encoding::Shift_JIS) - - def with_encoding(enc) - before = Encoding.default_external - silence_warnings { Encoding.default_external = KCODE_TO_ENCODING[enc] } - yield - silence_warnings { Encoding.default_external = before } - end -end diff --git a/activesupport/test/ordered_hash_test.rb b/activesupport/test/ordered_hash_test.rb index 8119b36491..78de7fb6ab 100644 --- a/activesupport/test/ordered_hash_test.rb +++ b/activesupport/test/ordered_hash_test.rb @@ -291,21 +291,16 @@ class OrderedHashTest < Test::Unit::TestCase assert_equal @ordered_hash.values, @deserialized_ordered_hash.values end - begin - require 'psych' + def test_psych_serialize + @deserialized_ordered_hash = Psych.load(Psych.dump(@ordered_hash)) - def test_psych_serialize - @deserialized_ordered_hash = Psych.load(Psych.dump(@ordered_hash)) - - values = @deserialized_ordered_hash.map { |_, value| value } - assert_equal @values, values - end + values = @deserialized_ordered_hash.map { |_, value| value } + assert_equal @values, values + end - def test_psych_serialize_tag - yaml = Psych.dump(@ordered_hash) - assert_match '!omap', yaml - end - rescue LoadError + def test_psych_serialize_tag + yaml = Psych.dump(@ordered_hash) + assert_match '!omap', yaml end def test_has_yaml_tag diff --git a/activesupport/test/safe_buffer_test.rb b/activesupport/test/safe_buffer_test.rb index 8f77999d25..2fde07995b 100644 --- a/activesupport/test/safe_buffer_test.rb +++ b/activesupport/test/safe_buffer_test.rb @@ -1,9 +1,4 @@ require 'abstract_unit' -begin - require 'psych' -rescue LoadError -end - require 'active_support/core_ext/string/inflections' require 'yaml' @@ -96,13 +91,20 @@ class SafeBufferTest < ActiveSupport::TestCase assert !@buffer.dup.html_safe? end + test "Should return safe buffer when added with another safe buffer" do + clean = "<script>".html_safe + result_buffer = @buffer + clean + assert result_buffer.html_safe? + assert_equal "<script>", result_buffer + end + test "Should raise an error when safe_concat is called on dirty buffers" do @buffer.gsub!('', '<>') assert_raise ActiveSupport::SafeBuffer::SafeConcatError do @buffer.safe_concat "BUSTED" end end - + test "should not fail if the returned object is not a string" do assert_kind_of NilClass, @buffer.slice("chipchop") end |