aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport
diff options
context:
space:
mode:
Diffstat (limited to 'activesupport')
-rw-r--r--activesupport/CHANGELOG.md195
-rw-r--r--activesupport/Rakefile10
-rwxr-xr-xactivesupport/bin/generate_tables6
-rw-r--r--activesupport/lib/active_support.rb1
-rw-r--r--activesupport/lib/active_support/all.rb1
-rw-r--r--activesupport/lib/active_support/backtrace_cleaner.rb16
-rw-r--r--activesupport/lib/active_support/basic_object.rb11
-rw-r--r--activesupport/lib/active_support/benchmarkable.rb10
-rw-r--r--activesupport/lib/active_support/buffered_logger.rb21
-rw-r--r--activesupport/lib/active_support/cache.rb6
-rw-r--r--activesupport/lib/active_support/cache/file_store.rb11
-rw-r--r--activesupport/lib/active_support/cache/memory_store.rb17
-rw-r--r--activesupport/lib/active_support/callbacks.rb56
-rw-r--r--activesupport/lib/active_support/concern.rb12
-rw-r--r--activesupport/lib/active_support/core_ext.rb1
-rw-r--r--activesupport/lib/active_support/core_ext/array.rb1
-rw-r--r--activesupport/lib/active_support/core_ext/array/conversions.rb19
-rw-r--r--activesupport/lib/active_support/core_ext/array/grouping.rb30
-rw-r--r--activesupport/lib/active_support/core_ext/array/uniq_by.rb19
-rw-r--r--activesupport/lib/active_support/core_ext/class/attribute.rb1
-rw-r--r--activesupport/lib/active_support/core_ext/date/calculations.rb21
-rw-r--r--activesupport/lib/active_support/core_ext/date/conversions.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/date/zones.rb35
-rw-r--r--activesupport/lib/active_support/core_ext/date_and_time/calculations.rb20
-rw-r--r--activesupport/lib/active_support/core_ext/date_and_time/zones.rb41
-rw-r--r--activesupport/lib/active_support/core_ext/date_time/acts_like.rb1
-rw-r--r--activesupport/lib/active_support/core_ext/date_time/calculations.rb28
-rw-r--r--activesupport/lib/active_support/core_ext/date_time/conversions.rb11
-rw-r--r--activesupport/lib/active_support/core_ext/date_time/zones.rb23
-rw-r--r--activesupport/lib/active_support/core_ext/hash.rb1
-rw-r--r--activesupport/lib/active_support/core_ext/hash/diff.rb16
-rw-r--r--activesupport/lib/active_support/core_ext/kernel/reporting.rb1
-rw-r--r--activesupport/lib/active_support/core_ext/logger.rb67
-rw-r--r--activesupport/lib/active_support/core_ext/module/delegation.rb33
-rw-r--r--activesupport/lib/active_support/core_ext/module/introspection.rb16
-rw-r--r--activesupport/lib/active_support/core_ext/module/method_transplanting.rb11
-rw-r--r--activesupport/lib/active_support/core_ext/object/try.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/proc.rb17
-rw-r--r--activesupport/lib/active_support/core_ext/range.rb1
-rw-r--r--activesupport/lib/active_support/core_ext/range/each.rb24
-rw-r--r--activesupport/lib/active_support/core_ext/string/access.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/string/encoding.rb8
-rw-r--r--activesupport/lib/active_support/core_ext/string/filters.rb16
-rw-r--r--activesupport/lib/active_support/core_ext/string/zones.rb1
-rw-r--r--activesupport/lib/active_support/core_ext/thread.rb21
-rw-r--r--activesupport/lib/active_support/core_ext/time/calculations.rb61
-rw-r--r--activesupport/lib/active_support/core_ext/time/conversions.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/time/zones.rb22
-rw-r--r--activesupport/lib/active_support/dependencies.rb8
-rw-r--r--activesupport/lib/active_support/deprecation.rb8
-rw-r--r--activesupport/lib/active_support/deprecation/behaviors.rb23
-rw-r--r--activesupport/lib/active_support/duration.rb12
-rw-r--r--activesupport/lib/active_support/file_update_checker.rb2
-rw-r--r--activesupport/lib/active_support/hash_with_indifferent_access.rb24
-rw-r--r--activesupport/lib/active_support/inflections.rb1
-rw-r--r--activesupport/lib/active_support/inflector/methods.rb26
-rw-r--r--activesupport/lib/active_support/json/decoding.rb4
-rw-r--r--activesupport/lib/active_support/json/encoding.rb1
-rw-r--r--activesupport/lib/active_support/json/variable.rb18
-rw-r--r--activesupport/lib/active_support/log_subscriber/test_helper.rb2
-rw-r--r--activesupport/lib/active_support/multibyte/chars.rb3
-rw-r--r--activesupport/lib/active_support/multibyte/unicode.rb13
-rw-r--r--activesupport/lib/active_support/notifications.rb4
-rw-r--r--activesupport/lib/active_support/notifications/instrumenter.rb3
-rw-r--r--activesupport/lib/active_support/number_helper.rb18
-rw-r--r--activesupport/lib/active_support/ordered_options.rb2
-rw-r--r--activesupport/lib/active_support/rescuable.rb1
-rw-r--r--activesupport/lib/active_support/subscriber.rb27
-rw-r--r--activesupport/lib/active_support/test_case.rb2
-rw-r--r--activesupport/lib/active_support/testing/assertions.rb30
-rw-r--r--activesupport/lib/active_support/testing/declarative.rb9
-rw-r--r--activesupport/lib/active_support/testing/isolation.rb52
-rw-r--r--activesupport/lib/active_support/testing/pending.rb14
-rw-r--r--activesupport/lib/active_support/testing/setup_and_teardown.rb19
-rw-r--r--activesupport/lib/active_support/time_with_zone.rb6
-rw-r--r--activesupport/test/abstract_unit.rb11
-rw-r--r--activesupport/test/autoloading_fixtures/html/some_class.rb4
-rw-r--r--activesupport/test/caching_test.rb44
-rw-r--r--activesupport/test/clean_backtrace_test.rb21
-rw-r--r--activesupport/test/concern_test.rb10
-rw-r--r--activesupport/test/constantize_test_cases.rb8
-rw-r--r--activesupport/test/core_ext/array_ext_test.rb34
-rw-r--r--activesupport/test/core_ext/bigdecimal_test.rb1
-rw-r--r--activesupport/test/core_ext/date_ext_test.rb16
-rw-r--r--activesupport/test/core_ext/date_time_ext_test.rb20
-rw-r--r--activesupport/test/core_ext/duration_test.rb3
-rw-r--r--activesupport/test/core_ext/hash_ext_test.rb49
-rw-r--r--activesupport/test/core_ext/module_test.rb35
-rw-r--r--activesupport/test/core_ext/numeric_ext_test.rb2
-rw-r--r--activesupport/test/core_ext/proc_test.rb14
-rw-r--r--activesupport/test/core_ext/range_ext_test.rb24
-rw-r--r--activesupport/test/core_ext/string_ext_test.rb18
-rw-r--r--activesupport/test/core_ext/thread_test.rb11
-rw-r--r--activesupport/test/core_ext/time_ext_test.rb146
-rw-r--r--activesupport/test/core_ext/time_with_zone_test.rb24
-rw-r--r--activesupport/test/dependencies/raises_exception_without_blame_file.rb5
-rw-r--r--activesupport/test/dependencies_test.rb16
-rw-r--r--activesupport/test/deprecation/basic_object_test.rb12
-rw-r--r--activesupport/test/deprecation/buffered_logger_test.rb22
-rw-r--r--activesupport/test/deprecation_test.rb16
-rw-r--r--activesupport/test/inflector_test.rb58
-rw-r--r--activesupport/test/inflector_test_cases.rb1
-rw-r--r--activesupport/test/json/decoding_test.rb34
-rw-r--r--activesupport/test/json/encoding_test.rb9
-rw-r--r--activesupport/test/load_paths_test.rb4
-rw-r--r--activesupport/test/rescuable_test.rb2
-rw-r--r--activesupport/test/subscriber_test.rb40
-rw-r--r--activesupport/test/test_case_test.rb11
-rw-r--r--activesupport/test/test_test.rb48
-rw-r--r--activesupport/test/transliterate_test.rb6
-rw-r--r--activesupport/test/ts_isolated.rb16
-rw-r--r--activesupport/test/xml_mini/jdom_engine_test.rb2
-rw-r--r--activesupport/test/xml_mini/libxml_engine_test.rb3
-rw-r--r--activesupport/test/xml_mini/libxmlsax_engine_test.rb3
-rw-r--r--activesupport/test/xml_mini/nokogiri_engine_test.rb3
-rw-r--r--activesupport/test/xml_mini/nokogirisax_engine_test.rb3
-rw-r--r--activesupport/test/xml_mini/rexml_engine_test.rb3
-rw-r--r--activesupport/test/xml_mini_test.rb12
118 files changed, 1175 insertions, 933 deletions
diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md
index 1982811500..eee7a7a587 100644
--- a/activesupport/CHANGELOG.md
+++ b/activesupport/CHANGELOG.md
@@ -1,3 +1,198 @@
+* Disable the ability to iterate over Range of AS::TimeWithZone
+ due to significant performance issues.
+
+ *Bogdan Gusiev*
+
+* Allow attaching event subscribers to ActiveSupport::Notifications namespaces
+ before they're defined. Essentially, this means instead of this:
+
+ class JokeSubscriber < ActiveSupport::Subscriber
+ def sql(event)
+ puts "A rabbi and a priest walk into a bar..."
+ end
+
+ # This call needs to happen *after* defining the methods.
+ attach_to "active_record"
+ end
+
+ You can do this:
+
+ class JokeSubscriber < ActiveSupport::Subscriber
+ # This is much easier to read!
+ attach_to "active_record"
+
+ def sql(event)
+ puts "A rabbi and a priest walk into a bar..."
+ end
+ end
+
+ This should make it easier to read and understand these subscribers.
+
+ *Daniel Schierbeck*
+
+* Add `Date#middle_of_day`, `DateTime#middle_of_day` and `Time#middle_of_day` methods.
+
+ Also added `midday`, `noon`, `at_midday`, `at_noon` and `at_middle_of_day` as aliases.
+
+ *Anatoli Makarevich*
+
+* Fix ActiveSupport::Cache::FileStore#cleanup to no longer rely on missing each_key method.
+
+ *Murray Steele*
+
+* Ensure that autoloaded constants in all-caps nestings are marked as
+ autoloaded.
+
+ *Simon Coffey*
+
+* Add String#remove(pattern) as a short-hand for the common pattern of String#gsub(pattern, '')
+
+ *DHH*
+
+* Adds a new deprecation behaviour that raises an exception. Throwing this
+ line into +config/environments/development.rb+
+
+ ActiveSupport::Deprecation.behavior = :raise
+
+ will cause the application to raise an +ActiveSupport::DeprecationException+
+ on deprecations.
+
+ Use this for aggressive deprecation cleanups.
+
+ *Xavier Noria*
+
+* Remove 'cow' => 'kine' irregular inflection from default inflections.
+
+ *Andrew White*
+
+* Add `DateTime#to_s(:iso8601)` and `Date#to_s(:iso8601)` for consistency.
+
+ *Andrew White*
+
+* Add `Time#to_s(:iso8601)` for easy conversion of times to the iso8601 format for easy Javascript date parsing.
+
+ *DHH*
+
+* Improve `ActiveSupport::Cache::MemoryStore` cache size calculation.
+ The memory used by a key/entry pair is calculated via `#cached_size`:
+
+ def cached_size(key, entry)
+ key.to_s.bytesize + entry.size + PER_ENTRY_OVERHEAD
+ end
+
+ The value of `PER_ENTRY_OVERHEAD` is 240 bytes based on an [empirical
+ estimation](https://gist.github.com/ssimeonov/6047200) for 64-bit MRI on
+ 1.9.3 and 2.0. GH#11512
+
+ *Simeon Simeonov*
+
+* Only raise `Module::DelegationError` if it's the source of the exception.
+
+ Fixes #10559
+
+ *Andrew White*
+
+* Make `Time.at_with_coercion` retain the second fraction and return local time.
+
+ Fixes #11350
+
+ *Neer Friedman*, *Andrew White*
+
+* Make `HashWithIndifferentAccess#select` always return the hash, even when
+ `Hash#select!` returns `nil`, to allow further chaining.
+
+ *Marc Schütz*
+
+* Remove deprecated `String#encoding_aware?` core extensions (`core_ext/string/encoding`).
+
+ *Arun Agrawal*
+
+* Remove deprecated `Module#local_constant_names` in favor of `Module#local_constants`.
+
+ *Arun Agrawal*
+
+* Remove deprecated `DateTime.local_offset` in favor of `DateTime.civil_from_fromat`.
+
+ *Arun Agrawal*
+
+* Remove deprecated `Logger` core extensions (`core_ext/logger.rb`).
+
+ *Carlos Antonio da Silva*
+
+* Remove deprecated `Time#time_with_datetime_fallback`, `Time#utc_time`
+ and `Time#local_time` in favor of `Time#utc` and `Time#local`.
+
+ *Vipul A M*
+
+* Remove deprecated `Hash#diff` with no replacement.
+
+ If you're using it to compare hashes for the purpose of testing, please use
+ MiniTest's `assert_equal` instead.
+
+ *Carlos Antonio da Silva*
+
+* Remove deprecated `Date#to_time_in_current_zone` in favor of `Date#in_time_zone`.
+
+ *Vipul A M*
+
+* Remove deprecated `Proc#bind` with no replacement.
+
+ *Carlos Antonio da Silva*
+
+* Remove deprecated `Array#uniq_by` and `Array#uniq_by!`, use native
+ `Array#uniq` and `Array#uniq!` instead.
+
+ *Carlos Antonio da Silva*
+
+* Remove deprecated `ActiveSupport::BasicObject`, use `ActiveSupport::ProxyObject` instead.
+
+ *Carlos Antonio da Silva*
+
+* Remove deprecated `BufferedLogger`.
+
+ *Yves Senn*
+
+* Remove deprecated `assert_present` and `assert_blank` methods.
+
+ *Yves Senn*
+
+* Fix return value from `BacktraceCleaner#noise` when the cleaner is configured
+ with multiple silencers.
+
+ Fixes #11030
+
+ *Mark J. Titorenko*
+
+* `HashWithIndifferentAccess#select` now returns a `HashWithIndifferentAccess`
+ instance instead of a `Hash` instance.
+
+ Fixes #10723
+
+ *Albert Llop*
+
+* Add `DateTime#usec` and `DateTime#nsec` so that `ActiveSupport::TimeWithZone` keeps
+ sub-second resolution when wrapping a `DateTime` value.
+
+ Fixes #10855
+
+ *Andrew White*
+
+* Fix `ActiveSupport::Dependencies::Loadable#load_dependency` calling
+ `#blame_file!` on Exceptions that do not have the Blamable mixin
+
+ *Andrew Kreiling*
+
+* Override `Time.at` to support the passing of Time-like values when called with a single argument.
+
+ *Andrew White*
+
+* Prevent side effects to hashes inside arrays when
+ `Hash#with_indifferent_access` is called.
+
+ Fixes #10526
+
+ *Yves Senn*
+
* Raise an error when multiple `included` blocks are defined for a Concern.
The old behavior would silently discard previously defined blocks, running
only the last one.
diff --git a/activesupport/Rakefile b/activesupport/Rakefile
index e3788ed54f..5ba153662a 100644
--- a/activesupport/Rakefile
+++ b/activesupport/Rakefile
@@ -9,20 +9,22 @@ Rake::TestTask.new do |t|
t.verbose = true
end
+
namespace :test do
- Rake::TestTask.new(:isolated) do |t|
- t.pattern = 'test/ts_isolated.rb'
+ task :isolated do
+ Dir.glob("test/**/*_test.rb").all? do |file|
+ sh(Gem.ruby, '-w', '-Ilib:test', file)
+ end or raise "Failures"
end
end
-
spec = eval(File.read('activesupport.gemspec'))
Gem::PackageTask.new(spec) do |p|
p.gem_spec = spec
end
-desc "Release to gemcutter"
+desc "Release to rubygems"
task :release => :package do
require 'rake/gemcutter'
Rake::Gemcutter::Tasks.new(spec).define
diff --git a/activesupport/bin/generate_tables b/activesupport/bin/generate_tables
index 5fefa429df..f39e89b7d0 100755
--- a/activesupport/bin/generate_tables
+++ b/activesupport/bin/generate_tables
@@ -28,12 +28,6 @@ module ActiveSupport
def initialize
@ucd = Unicode::UnicodeDatabase.new
-
- default = Codepoint.new
- default.combining_class = 0
- default.uppercase_mapping = 0
- default.lowercase_mapping = 0
- @ucd.codepoints = Hash.new(default)
end
def parse_codepoints(line)
diff --git a/activesupport/lib/active_support.rb b/activesupport/lib/active_support.rb
index ffa6ffda4f..5e1fe9e556 100644
--- a/activesupport/lib/active_support.rb
+++ b/activesupport/lib/active_support.rb
@@ -39,7 +39,6 @@ module ActiveSupport
eager_autoload do
autoload :BacktraceCleaner
- autoload :BasicObject
autoload :ProxyObject
autoload :Benchmarkable
autoload :Cache
diff --git a/activesupport/lib/active_support/all.rb b/activesupport/lib/active_support/all.rb
index f537818300..151008bbaa 100644
--- a/activesupport/lib/active_support/all.rb
+++ b/activesupport/lib/active_support/all.rb
@@ -1,3 +1,4 @@
require 'active_support'
+require 'active_support/deprecation'
require 'active_support/time'
require 'active_support/core_ext'
diff --git a/activesupport/lib/active_support/backtrace_cleaner.rb b/activesupport/lib/active_support/backtrace_cleaner.rb
index 4b41e6247d..c88ae3e661 100644
--- a/activesupport/lib/active_support/backtrace_cleaner.rb
+++ b/activesupport/lib/active_support/backtrace_cleaner.rb
@@ -13,17 +13,17 @@ module ActiveSupport
# can focus on the rest.
#
# bc = BacktraceCleaner.new
- # bc.add_filter { |line| line.gsub(Rails.root, '') }
- # bc.add_silencer { |line| line =~ /mongrel|rubygems/ }
- # bc.clean(exception.backtrace) # will strip the Rails.root prefix and skip any lines from mongrel or rubygems
+ # bc.add_filter { |line| line.gsub(Rails.root, '') } # strip the Rails.root prefix
+ # bc.add_silencer { |line| line =~ /mongrel|rubygems/ } # skip any lines from mongrel or rubygems
+ # bc.clean(exception.backtrace) # perform the cleanup
#
# To reconfigure an existing BacktraceCleaner (like the default one in Rails)
# and show as much data as possible, you can always call
# <tt>BacktraceCleaner#remove_silencers!</tt>, which will restore the
# backtrace to a pristine state. If you need to reconfigure an existing
# BacktraceCleaner so that it does not filter or modify the paths of any lines
- # of the backtrace, you can call BacktraceCleaner#remove_filters! These two
- # methods will give you a completely untouched backtrace.
+ # of the backtrace, you can call <tt>BacktraceCleaner#remove_filters!<tt>
+ # These two methods will give you a completely untouched backtrace.
#
# Inspired by the Quiet Backtrace gem by Thoughtbot.
class BacktraceCleaner
@@ -97,11 +97,7 @@ module ActiveSupport
end
def noise(backtrace)
- @silencers.each do |s|
- backtrace = backtrace.select { |line| s.call(line) }
- end
-
- backtrace
+ backtrace - silence(backtrace)
end
end
end
diff --git a/activesupport/lib/active_support/basic_object.rb b/activesupport/lib/active_support/basic_object.rb
deleted file mode 100644
index 91aac6db64..0000000000
--- a/activesupport/lib/active_support/basic_object.rb
+++ /dev/null
@@ -1,11 +0,0 @@
-require 'active_support/deprecation'
-require 'active_support/proxy_object'
-
-module ActiveSupport
- class BasicObject < ProxyObject # :nodoc:
- def self.inherited(*)
- ::ActiveSupport::Deprecation.warn 'ActiveSupport::BasicObject is deprecated! Use ActiveSupport::ProxyObject instead.'
- super
- end
- end
-end
diff --git a/activesupport/lib/active_support/benchmarkable.rb b/activesupport/lib/active_support/benchmarkable.rb
index 6413502b53..805b7a714f 100644
--- a/activesupport/lib/active_support/benchmarkable.rb
+++ b/activesupport/lib/active_support/benchmarkable.rb
@@ -45,15 +45,5 @@ module ActiveSupport
yield
end
end
-
- # Silence the logger during the execution of the block.
- def silence
- message = "ActiveSupport::Benchmarkable#silence is deprecated. It will be removed from Rails 4.1."
- ActiveSupport::Deprecation.warn message
- old_logger_level, logger.level = logger.level, ::Logger::ERROR if logger
- yield
- ensure
- logger.level = old_logger_level if logger
- end
end
end
diff --git a/activesupport/lib/active_support/buffered_logger.rb b/activesupport/lib/active_support/buffered_logger.rb
deleted file mode 100644
index 1cd0c2f790..0000000000
--- a/activesupport/lib/active_support/buffered_logger.rb
+++ /dev/null
@@ -1,21 +0,0 @@
-require 'active_support/deprecation'
-require 'active_support/logger'
-
-module ActiveSupport
- class BufferedLogger < Logger
-
- def initialize(*args)
- self.class._deprecation_warning
- super
- end
-
- def self.inherited(*)
- _deprecation_warning
- super
- end
-
- def self._deprecation_warning
- ::ActiveSupport::Deprecation.warn 'ActiveSupport::BufferedLogger is deprecated! Use ActiveSupport::Logger instead.'
- end
- end
-end
diff --git a/activesupport/lib/active_support/cache.rb b/activesupport/lib/active_support/cache.rb
index b1ab5570a8..c5633d902f 100644
--- a/activesupport/lib/active_support/cache.rb
+++ b/activesupport/lib/active_support/cache.rb
@@ -228,13 +228,13 @@ module ActiveSupport
#
# Setting <tt>:race_condition_ttl</tt> is very useful in situations where
# a cache entry is used very frequently and is under heavy load. If a
- # cache expires and due to heavy load seven different processes will try
+ # cache expires and due to heavy load several different processes will try
# to read data natively and then they all will try to write to cache. To
# avoid that case the first process to find an expired cache entry will
# bump the cache expiration time by the value set in <tt>:race_condition_ttl</tt>.
# Yes, this process is extending the time for a stale value by another few
# seconds. Because of extended life of the previous cache, other processes
- # will continue to use slightly stale data for a just a big longer. In the
+ # will continue to use slightly stale data for a just a bit longer. In the
# meantime that first process will go ahead and will write into cache the
# new value. After that all the processes will start getting new value.
# The key is to keep <tt>:race_condition_ttl</tt> small.
@@ -408,7 +408,7 @@ module ActiveSupport
options = merged_options(options)
instrument(:exist?, name) do
entry = read_entry(namespaced_key(name, options), options)
- entry && !entry.expired?
+ (entry && !entry.expired?) || false
end
end
diff --git a/activesupport/lib/active_support/cache/file_store.rb b/activesupport/lib/active_support/cache/file_store.rb
index 0c55aa8a32..10d39463ec 100644
--- a/activesupport/lib/active_support/cache/file_store.rb
+++ b/activesupport/lib/active_support/cache/file_store.rb
@@ -22,19 +22,26 @@ module ActiveSupport
extend Strategy::LocalCache
end
+ # Deletes all items from the cache. In this case it deletes all the entries in the specified
+ # file store directory except for .gitkeep. Be careful which directory is specified in your
+ # config file when using +FileStore+ because everything in that directory will be deleted.
def clear(options = nil)
root_dirs = Dir.entries(cache_path).reject {|f| (EXCLUDED_DIRS + [".gitkeep"]).include?(f)}
FileUtils.rm_r(root_dirs.collect{|f| File.join(cache_path, f)})
end
+ # Premptively iterates through all stored keys and removes the ones which have expired.
def cleanup(options = nil)
options = merged_options(options)
- each_key(options) do |key|
+ search_dir(cache_path) do |fname|
+ key = file_path_key(fname)
entry = read_entry(key, options)
delete_entry(key, options) if entry && entry.expired?
end
end
+ # Increments an already existing integer value that is stored in the cache.
+ # If the key is not found nothing is done.
def increment(name, amount = 1, options = nil)
file_name = key_file_path(namespaced_key(name, options))
lock_file(file_name) do
@@ -49,6 +56,8 @@ module ActiveSupport
end
end
+ # Decrements an already existing integer value that is stored in the cache.
+ # If the key is not found nothing is done.
def decrement(name, amount = 1, options = nil)
file_name = key_file_path(namespaced_key(name, options))
lock_file(file_name) do
diff --git a/activesupport/lib/active_support/cache/memory_store.rb b/activesupport/lib/active_support/cache/memory_store.rb
index 4d26fb7e42..34ac91334a 100644
--- a/activesupport/lib/active_support/cache/memory_store.rb
+++ b/activesupport/lib/active_support/cache/memory_store.rb
@@ -36,6 +36,7 @@ module ActiveSupport
end
end
+ # Premptively iterates through all stored keys and removes the ones which have expired.
def cleanup(options = nil)
options = merged_options(options)
instrument(:cleanup, :size => @data.size) do
@@ -122,6 +123,13 @@ module ActiveSupport
end
protected
+
+ PER_ENTRY_OVERHEAD = 240
+
+ def cached_size(key, entry)
+ key.to_s.bytesize + entry.size + PER_ENTRY_OVERHEAD
+ end
+
def read_entry(key, options) # :nodoc:
entry = @data[key]
synchronize do
@@ -139,8 +147,11 @@ module ActiveSupport
synchronize do
old_entry = @data[key]
return false if @data.key?(key) && options[:unless_exist]
- @cache_size -= old_entry.size if old_entry
- @cache_size += entry.size
+ if old_entry
+ @cache_size -= (old_entry.size - entry.size)
+ else
+ @cache_size += cached_size(key, entry)
+ end
@key_access[key] = Time.now.to_f
@data[key] = entry
prune(@max_size * 0.75, @max_prune_time) if @cache_size > @max_size
@@ -152,7 +163,7 @@ module ActiveSupport
synchronize do
@key_access.delete(key)
entry = @data.delete(key)
- @cache_size -= entry.size if entry
+ @cache_size -= cached_size(key, entry) if entry
!!entry
end
end
diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb
index 85b7669353..c3aac31323 100644
--- a/activesupport/lib/active_support/callbacks.rb
+++ b/activesupport/lib/active_support/callbacks.rb
@@ -1,5 +1,6 @@
require 'active_support/concern'
require 'active_support/descendants_tracker'
+require 'active_support/core_ext/array/extract_options'
require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/kernel/reporting'
require 'active_support/core_ext/kernel/singleton_class'
@@ -94,6 +95,15 @@ module ActiveSupport
def halted_callback_hook(filter)
end
+ module Conditionals # :nodoc:
+ class Value
+ def initialize(&block)
+ @block = block
+ end
+ def call(target, value); @block.call(value); end
+ end
+ end
+
module Filters
Environment = Struct.new(:target, :halted, :value, :run_block)
@@ -403,8 +413,8 @@ module ActiveSupport
# the same after this point:
#
# Symbols:: Already methods.
- # Strings:: class_eval'ed into methods.
- # Procs:: define_method'ed into methods.
+ # Strings:: class_eval'd into methods.
+ # Procs:: using define_method compiled into methods.
# Objects::
# a method is created that calls the before_foo method
# on the object.
@@ -415,6 +425,7 @@ module ActiveSupport
when String
l = eval "lambda { |value| #{filter} }"
lambda { |target, value| target.instance_exec(value, &l) }
+ when Conditionals::Value then filter
when ::Proc
if filter.arity > 1
return lambda { |target, _, &block|
@@ -532,14 +543,12 @@ module ActiveSupport
@callbacks = nil
@chain.delete_if { |c| callback.duplicates?(c) }
end
-
end
module ClassMethods
-
def normalize_callback_params(filters, block) # :nodoc:
type = CALLBACK_FILTER_TYPES.include?(filters.first) ? filters.shift : :before
- options = filters.last.is_a?(Hash) ? filters.pop : {}
+ options = filters.extract_options!
filters.unshift(block) if block
[type, filters, options.dup]
end
@@ -565,7 +574,7 @@ module ActiveSupport
#
# set_callback :save, :before_meth
#
- # The callback can specified as a symbol naming an instance method; as a
+ # The callback can be specified as a symbol naming an instance method; as a
# proc, lambda, or block; as a string to be instance evaluated; or as an
# object that responds to a certain method determined by the <tt>:scope</tt>
# argument to +define_callback+.
@@ -627,16 +636,16 @@ module ActiveSupport
end
# Remove all set callbacks for the given event.
- def reset_callbacks(symbol)
- callbacks = get_callbacks symbol
+ def reset_callbacks(name)
+ callbacks = get_callbacks name
ActiveSupport::DescendantsTracker.descendants(self).each do |target|
- chain = target.get_callbacks(symbol).dup
+ chain = target.get_callbacks(name).dup
callbacks.each { |c| chain.delete(c) }
- target.set_callbacks symbol, chain
+ target.set_callbacks name, chain
end
- self.set_callbacks symbol, callbacks.dup.clear
+ self.set_callbacks name, callbacks.dup.clear
end
# Define sets of events in the object lifecycle that support callbacks.
@@ -648,10 +657,11 @@ module ActiveSupport
#
# * <tt>:terminator</tt> - Determines when a before filter will halt the
# callback chain, preventing following callbacks from being called and
- # the event from being triggered. This is a string to be eval'ed. The
- # result of the callback is available in the +result+ variable.
+ # the event from being triggered. This should be a lambda to be executed.
+ # The current object and the return result of the callback will be called
+ # with the lambda.
#
- # define_callbacks :validate, terminator: 'result == false'
+ # define_callbacks :validate, terminator: ->(target, result) { result == false }
#
# In this example, if any before validate callbacks returns +false+,
# other callbacks are not executed. Defaults to +false+, meaning no value
@@ -706,18 +716,18 @@ module ActiveSupport
# define_callbacks :save, scope: [:name]
#
# would call <tt>Audit#save</tt>.
- def define_callbacks(*callbacks)
- config = callbacks.last.is_a?(Hash) ? callbacks.pop : {}
- if config.key?(:terminator) && String === config[:terminator]
+ def define_callbacks(*names)
+ options = names.extract_options!
+ if options.key?(:terminator) && String === options[:terminator]
ActiveSupport::Deprecation.warn "String based terminators are deprecated, please use a lambda"
- value = config[:terminator]
- l = class_eval "lambda { |result| #{value} }", __FILE__, __LINE__
- config[:terminator] = lambda { |target, result| target.instance_exec(result, &l) }
+ value = options[:terminator]
+ line = class_eval "lambda { |result| #{value} }", __FILE__, __LINE__
+ options[:terminator] = lambda { |target, result| target.instance_exec(result, &line) }
end
- callbacks.each do |callback|
- class_attribute "_#{callback}_callbacks"
- set_callbacks callback, CallbackChain.new(callback, config)
+ names.each do |name|
+ class_attribute "_#{name}_callbacks"
+ set_callbacks name, CallbackChain.new(name, options)
end
end
diff --git a/activesupport/lib/active_support/concern.rb b/activesupport/lib/active_support/concern.rb
index b6ae86b583..b796d01dfd 100644
--- a/activesupport/lib/active_support/concern.rb
+++ b/activesupport/lib/active_support/concern.rb
@@ -105,25 +105,25 @@ module ActiveSupport
end
def self.extended(base) #:nodoc:
- base.instance_variable_set("@_dependencies", [])
+ base.instance_variable_set(:@_dependencies, [])
end
def append_features(base)
- if base.instance_variable_defined?("@_dependencies")
- base.instance_variable_get("@_dependencies") << self
+ if base.instance_variable_defined?(:@_dependencies)
+ base.instance_variable_get(:@_dependencies) << self
return false
else
return false if base < self
@_dependencies.each { |dep| base.send(:include, dep) }
super
- base.extend const_get("ClassMethods") if const_defined?("ClassMethods")
- base.class_eval(&@_included_block) if instance_variable_defined?("@_included_block")
+ base.extend const_get(:ClassMethods) if const_defined?(:ClassMethods)
+ base.class_eval(&@_included_block) if instance_variable_defined?(:@_included_block)
end
end
def included(base = nil, &block)
if base.nil?
- raise MultipleIncludedBlocks if instance_variable_defined?("@_included_block")
+ raise MultipleIncludedBlocks if instance_variable_defined?(:@_included_block)
@_included_block = block
else
diff --git a/activesupport/lib/active_support/core_ext.rb b/activesupport/lib/active_support/core_ext.rb
index 998a59c618..199aa91020 100644
--- a/activesupport/lib/active_support/core_ext.rb
+++ b/activesupport/lib/active_support/core_ext.rb
@@ -1,4 +1,3 @@
Dir["#{File.dirname(__FILE__)}/core_ext/*.rb"].each do |path|
- next if File.basename(path, '.rb') == 'logger'
require path
end
diff --git a/activesupport/lib/active_support/core_ext/array.rb b/activesupport/lib/active_support/core_ext/array.rb
index 79ba79192a..7d0c1e4c8d 100644
--- a/activesupport/lib/active_support/core_ext/array.rb
+++ b/activesupport/lib/active_support/core_ext/array.rb
@@ -1,6 +1,5 @@
require 'active_support/core_ext/array/wrap'
require 'active_support/core_ext/array/access'
-require 'active_support/core_ext/array/uniq_by'
require 'active_support/core_ext/array/conversions'
require 'active_support/core_ext/array/extract_options'
require 'active_support/core_ext/array/grouping'
diff --git a/activesupport/lib/active_support/core_ext/array/conversions.rb b/activesupport/lib/active_support/core_ext/array/conversions.rb
index 3807ee63b1..76ffd23ed1 100644
--- a/activesupport/lib/active_support/core_ext/array/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/array/conversions.rb
@@ -82,23 +82,8 @@ class Array
end
end
- # Converts a collection of elements into a formatted string by calling
- # <tt>to_s</tt> on all elements and joining them. Having this model:
- #
- # class Blog < ActiveRecord::Base
- # def to_s
- # title
- # end
- # end
- #
- # Blog.all.map(&:title) #=> ["First Post", "Second Post", "Third post"]
- #
- # <tt>to_formatted_s</tt> shows us:
- #
- # Blog.all.to_formatted_s # => "First PostSecond PostThird Post"
- #
- # Adding in the <tt>:db</tt> argument as the format yields a comma separated
- # id list:
+ # Extends <tt>Array#to_s</tt> to convert a collection of elements into a
+ # comma separated id list if <tt>:db</tt> argument is given as the format.
#
# Blog.all.to_formatted_s(:db) # => "1,2,3"
def to_formatted_s(format = :default)
diff --git a/activesupport/lib/active_support/core_ext/array/grouping.rb b/activesupport/lib/active_support/core_ext/array/grouping.rb
index dbddc7a7b4..37f007c751 100644
--- a/activesupport/lib/active_support/core_ext/array/grouping.rb
+++ b/activesupport/lib/active_support/core_ext/array/grouping.rb
@@ -31,9 +31,7 @@ class Array
if block_given?
collection.each_slice(number) { |slice| yield(slice) }
else
- groups = []
- collection.each_slice(number) { |group| groups << group }
- groups
+ collection.each_slice(number).to_a
end
end
@@ -86,13 +84,27 @@ class Array
# [1, 2, 3, 4, 5].split(3) # => [[1, 2], [4, 5]]
# (1..10).to_a.split { |i| i % 3 == 0 } # => [[1, 2], [4, 5], [7, 8], [10]]
def split(value = nil, &block)
- inject([[]]) do |results, element|
- if block && block.call(element) || value == element
- results << []
- else
- results.last << element
- end
+ if block
+ inject([[]]) do |results, element|
+ if block.call(element)
+ results << []
+ else
+ results.last << element
+ end
+ results
+ end
+ else
+ results, arr = [[]], self
+ until arr.empty?
+ if (idx = index(value))
+ results.last.concat(arr.shift(idx))
+ arr.shift
+ results << []
+ else
+ results.last.concat(arr.shift(arr.size))
+ end
+ end
results
end
end
diff --git a/activesupport/lib/active_support/core_ext/array/uniq_by.rb b/activesupport/lib/active_support/core_ext/array/uniq_by.rb
deleted file mode 100644
index 23573c97de..0000000000
--- a/activesupport/lib/active_support/core_ext/array/uniq_by.rb
+++ /dev/null
@@ -1,19 +0,0 @@
-class Array
- # *DEPRECATED*: Use <tt>Array#uniq</tt> instead.
- #
- # Returns a unique array based on the criteria in the block.
- #
- # [1, 2, 3, 4].uniq_by { |i| i.odd? } # => [1, 2]
- def uniq_by(&block)
- ActiveSupport::Deprecation.warn 'uniq_by is deprecated. Use Array#uniq instead'
- uniq(&block)
- end
-
- # *DEPRECATED*: Use <tt>Array#uniq!</tt> instead.
- #
- # Same as +uniq_by+, but modifies +self+.
- def uniq_by!(&block)
- ActiveSupport::Deprecation.warn 'uniq_by! is deprecated. Use Array#uniq! instead'
- uniq!(&block)
- end
-end
diff --git a/activesupport/lib/active_support/core_ext/class/attribute.rb b/activesupport/lib/active_support/core_ext/class/attribute.rb
index 6fa9967a28..83038f9da5 100644
--- a/activesupport/lib/active_support/core_ext/class/attribute.rb
+++ b/activesupport/lib/active_support/core_ext/class/attribute.rb
@@ -70,7 +70,6 @@ class Class
# To opt out of both instance methods, pass <tt>instance_accessor: false</tt>.
def class_attribute(*attrs)
options = attrs.extract_options!
- # double assignment is used to avoid "assigned but unused variable" warning
instance_reader = options.fetch(:instance_accessor, true) && options.fetch(:instance_reader, true)
instance_writer = options.fetch(:instance_accessor, true) && options.fetch(:instance_writer, true)
instance_predicate = options.fetch(:instance_predicate, true)
diff --git a/activesupport/lib/active_support/core_ext/date/calculations.rb b/activesupport/lib/active_support/core_ext/date/calculations.rb
index 106a65610c..c60e833441 100644
--- a/activesupport/lib/active_support/core_ext/date/calculations.rb
+++ b/activesupport/lib/active_support/core_ext/date/calculations.rb
@@ -69,6 +69,16 @@ class Date
alias :at_midnight :beginning_of_day
alias :at_beginning_of_day :beginning_of_day
+ # Converts Date to a Time (or DateTime if necessary) with the time portion set to the middle of the day (12:00)
+ def middle_of_day
+ in_time_zone.middle_of_day
+ end
+ alias :midday :middle_of_day
+ alias :noon :middle_of_day
+ alias :at_midday :middle_of_day
+ alias :at_noon :middle_of_day
+ alias :at_middle_of_day :middle_of_day
+
# Converts Date to a Time (or DateTime if necessary) with the time portion set to the end of the day (23:59:59)
def end_of_day
in_time_zone.end_of_day
@@ -119,4 +129,15 @@ class Date
options.fetch(:day, day)
)
end
+
+ # Allow Date to be compared with Time by converting to DateTime and relying on the <=> from there.
+ def compare_with_coercion(other)
+ if other.is_a?(Time)
+ self.to_datetime <=> other
+ else
+ compare_without_coercion(other)
+ end
+ end
+ alias_method :compare_without_coercion, :<=>
+ alias_method :<=>, :compare_with_coercion
end
diff --git a/activesupport/lib/active_support/core_ext/date/conversions.rb b/activesupport/lib/active_support/core_ext/date/conversions.rb
index 0637fe4929..6bc8f12176 100644
--- a/activesupport/lib/active_support/core_ext/date/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/date/conversions.rb
@@ -12,7 +12,8 @@ class Date
day_format = ActiveSupport::Inflector.ordinalize(date.day)
date.strftime("%B #{day_format}, %Y") # => "April 25th, 2007"
},
- :rfc822 => '%e %b %Y'
+ :rfc822 => '%e %b %Y',
+ :iso8601 => lambda { |date| date.iso8601 }
}
# Ruby 1.9 has Date#to_time which converts to localtime only.
@@ -34,6 +35,7 @@ class Date
# date.to_formatted_s(:long) # => "November 10, 2007"
# date.to_formatted_s(:long_ordinal) # => "November 10th, 2007"
# date.to_formatted_s(:rfc822) # => "10 Nov 2007"
+ # date.to_formatted_s(:iso8601) # => "2007-11-10"
#
# == Adding your own time formats to to_formatted_s
# You can add your own formats to the Date::DATE_FORMATS hash.
diff --git a/activesupport/lib/active_support/core_ext/date/zones.rb b/activesupport/lib/active_support/core_ext/date/zones.rb
index b4548671bf..d109b430db 100644
--- a/activesupport/lib/active_support/core_ext/date/zones.rb
+++ b/activesupport/lib/active_support/core_ext/date/zones.rb
@@ -1,37 +1,6 @@
require 'date'
-require 'active_support/core_ext/time/zones'
+require 'active_support/core_ext/date_and_time/zones'
class Date
- # *DEPRECATED*: Use +Date#in_time_zone+ instead.
- #
- # Converts Date to a TimeWithZone in the current zone if <tt>Time.zone</tt> or
- # <tt>Time.zone_default</tt> is set, otherwise converts Date to a Time via
- # Date#to_time.
- def to_time_in_current_zone
- ActiveSupport::Deprecation.warn 'Date#to_time_in_current_zone is deprecated. Use Date#in_time_zone instead', caller
-
- if ::Time.zone
- ::Time.zone.local(year, month, day)
- else
- to_time
- end
- end
-
- # Converts Date to a TimeWithZone in the current zone if Time.zone or Time.zone_default
- # is set, otherwise converts Date to a Time via Date#to_time
- #
- # Time.zone = 'Hawaii' # => 'Hawaii'
- # Date.new(2000).in_time_zone # => Sat, 01 Jan 2000 00:00:00 HST -10:00
- #
- # You can also pass in a TimeZone instance or string that identifies a TimeZone as an argument,
- # and the conversion will be based on that zone instead of <tt>Time.zone</tt>.
- #
- # Date.new(2000).in_time_zone('Alaska') # => Sat, 01 Jan 2000 00:00:00 AKST -09:00
- def in_time_zone(zone = ::Time.zone)
- if zone
- ::Time.find_zone!(zone).local(year, month, day)
- else
- to_time
- end
- end
+ include DateAndTime::Zones
end
diff --git a/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb b/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb
index 0d14cba7cc..c869a0e210 100644
--- a/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb
+++ b/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb
@@ -78,7 +78,7 @@ module DateAndTime
# Returns a new date/time at the start of the month.
# DateTime objects will have a time set to 0:00.
def beginning_of_month
- first_hour{ change(:day => 1) }
+ first_hour(change(:day => 1))
end
alias :at_beginning_of_month :beginning_of_month
@@ -113,7 +113,7 @@ module DateAndTime
# which is determined by +Date.beginning_of_week+ or +config.beginning_of_week+
# when set. +DateTime+ objects have their time set to 0:00.
def next_week(given_day_in_next_week = Date.beginning_of_week)
- first_hour{ weeks_since(1).beginning_of_week.days_since(days_span(given_day_in_next_week)) }
+ first_hour(weeks_since(1).beginning_of_week.days_since(days_span(given_day_in_next_week)))
end
# Short-hand for months_since(1).
@@ -136,7 +136,7 @@ module DateAndTime
# +Date.beginning_of_week+ or +config.beginning_of_week+ when set.
# DateTime objects have their time set to 0:00.
def prev_week(start_day = Date.beginning_of_week)
- first_hour{ weeks_ago(1).beginning_of_week.days_since(days_span(start_day)) }
+ first_hour(weeks_ago(1).beginning_of_week.days_since(days_span(start_day)))
end
alias_method :last_week, :prev_week
@@ -188,7 +188,7 @@ module DateAndTime
# +Date.beginning_of_week+ or +config.beginning_of_week+ when set.
# DateTime objects have their time set to 23:59:59.
def end_of_week(start_day = Date.beginning_of_week)
- last_hour{ days_since(6 - days_to_week_start(start_day)) }
+ last_hour(days_since(6 - days_to_week_start(start_day)))
end
alias :at_end_of_week :end_of_week
@@ -202,7 +202,7 @@ module DateAndTime
# DateTime objects will have a time set to 23:59:59.
def end_of_month
last_day = ::Time.days_in_month(month, year)
- last_hour{ days_since(last_day - day) }
+ last_hour(days_since(last_day - day))
end
alias :at_end_of_month :end_of_month
@@ -215,14 +215,12 @@ module DateAndTime
private
- def first_hour
- result = yield
- acts_like?(:time) ? result.change(:hour => 0) : result
+ def first_hour(date_or_time)
+ date_or_time.acts_like?(:time) ? date_or_time.beginning_of_day : date_or_time
end
- def last_hour
- result = yield
- acts_like?(:time) ? result.end_of_day : result
+ def last_hour(date_or_time)
+ date_or_time.acts_like?(:time) ? date_or_time.end_of_day : date_or_time
end
def days_span(day)
diff --git a/activesupport/lib/active_support/core_ext/date_and_time/zones.rb b/activesupport/lib/active_support/core_ext/date_and_time/zones.rb
new file mode 100644
index 0000000000..96c6df9407
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/date_and_time/zones.rb
@@ -0,0 +1,41 @@
+module DateAndTime
+ module Zones
+ # Returns the simultaneous time in <tt>Time.zone</tt> if a zone is given or
+ # if Time.zone_default is set. Otherwise, it returns the current time.
+ #
+ # Time.zone = 'Hawaii' # => 'Hawaii'
+ # DateTime.utc(2000).in_time_zone # => Fri, 31 Dec 1999 14:00:00 HST -10:00
+ # Date.new(2000).in_time_zone # => Sat, 01 Jan 2000 00:00:00 HST -10:00
+ #
+ # This method is similar to Time#localtime, except that it uses <tt>Time.zone</tt> as the local zone
+ # instead of the operating system's time zone.
+ #
+ # You can also pass in a TimeZone instance or string that identifies a TimeZone as an argument,
+ # and the conversion will be based on that zone instead of <tt>Time.zone</tt>.
+ #
+ # Time.utc(2000).in_time_zone('Alaska') # => Fri, 31 Dec 1999 15:00:00 AKST -09:00
+ # DateTime.utc(2000).in_time_zone('Alaska') # => Fri, 31 Dec 1999 15:00:00 AKST -09:00
+ # Date.new(2000).in_time_zone('Alaska') # => Sat, 01 Jan 2000 00:00:00 AKST -09:00
+ def in_time_zone(zone = ::Time.zone)
+ time_zone = ::Time.find_zone! zone
+ time = acts_like?(:time) ? self : nil
+
+ if time_zone
+ time_with_zone(time, time_zone)
+ else
+ time || self.to_time
+ end
+ end
+
+ private
+
+ def time_with_zone(time, zone)
+ if time
+ ActiveSupport::TimeWithZone.new(time.utc? ? time : time.getutc, zone)
+ else
+ ActiveSupport::TimeWithZone.new(nil, zone, to_time(:utc))
+ end
+ end
+ end
+end
+
diff --git a/activesupport/lib/active_support/core_ext/date_time/acts_like.rb b/activesupport/lib/active_support/core_ext/date_time/acts_like.rb
index c79745c5aa..8fbbe0d3e9 100644
--- a/activesupport/lib/active_support/core_ext/date_time/acts_like.rb
+++ b/activesupport/lib/active_support/core_ext/date_time/acts_like.rb
@@ -1,3 +1,4 @@
+require 'date'
require 'active_support/core_ext/object/acts_like'
class DateTime
diff --git a/activesupport/lib/active_support/core_ext/date_time/calculations.rb b/activesupport/lib/active_support/core_ext/date_time/calculations.rb
index 937567440b..8e5d723074 100644
--- a/activesupport/lib/active_support/core_ext/date_time/calculations.rb
+++ b/activesupport/lib/active_support/core_ext/date_time/calculations.rb
@@ -1,15 +1,7 @@
require 'date'
-require 'active_support/deprecation'
class DateTime
class << self
- # *DEPRECATED*: Use +DateTime.civil_from_format+ directly.
- def local_offset
- ActiveSupport::Deprecation.warn 'DateTime.local_offset is deprecated. Use DateTime.civil_from_format directly.'
-
- ::Time.local(2012).utc_offset.to_r / 86400
- end
-
# Returns <tt>Time.zone.now.to_datetime</tt> when <tt>Time.zone</tt> or
# <tt>config.time_zone</tt> are set, otherwise returns
# <tt>Time.now.to_datetime</tt>.
@@ -18,16 +10,6 @@ class DateTime
end
end
- # Tells whether the DateTime object's datetime lies in the past.
- def past?
- self < ::DateTime.current
- end
-
- # Tells whether the DateTime object's datetime lies in the future.
- def future?
- self > ::DateTime.current
- end
-
# Seconds since midnight: DateTime.now.seconds_since_midnight.
def seconds_since_midnight
sec + (min * 60) + (hour * 3600)
@@ -107,6 +89,16 @@ class DateTime
alias :at_midnight :beginning_of_day
alias :at_beginning_of_day :beginning_of_day
+ # Returns a new DateTime representing the middle of the day (12:00)
+ def middle_of_day
+ change(:hour => 12)
+ end
+ alias :midday :middle_of_day
+ alias :noon :middle_of_day
+ alias :at_midday :middle_of_day
+ alias :at_noon :middle_of_day
+ alias :at_middle_of_day :middle_of_day
+
# Returns a new DateTime representing the end of the day (23:59:59).
def end_of_day
change(:hour => 23, :min => 59, :sec => 59)
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 df07917d19..6ddfb72a0d 100644
--- a/activesupport/lib/active_support/core_ext/date_time/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/date_time/conversions.rb
@@ -19,6 +19,7 @@ class DateTime
# datetime.to_formatted_s(:long) # => "December 04, 2007 00:00"
# datetime.to_formatted_s(:long_ordinal) # => "December 4th, 2007 00:00"
# datetime.to_formatted_s(:rfc822) # => "Tue, 04 Dec 2007 00:00:00 +0000"
+ # datetime.to_formatted_s(:iso8601) # => "2007-12-04T00:00:00+00:00"
#
# == Adding your own datetime formats to to_formatted_s
# DateTime formats are shared with Time. You can add your own to the
@@ -80,6 +81,16 @@ class DateTime
seconds_since_unix_epoch.to_i
end
+ # Returns the fraction of a second as microseconds
+ def usec
+ (sec_fraction * 1_000_000).to_i
+ end
+
+ # Returns the fraction of a second as nanoseconds
+ def nsec
+ (sec_fraction * 1_000_000_000).to_i
+ end
+
private
def offset_in_seconds
diff --git a/activesupport/lib/active_support/core_ext/date_time/zones.rb b/activesupport/lib/active_support/core_ext/date_time/zones.rb
index 01a627f8af..c39f358395 100644
--- a/activesupport/lib/active_support/core_ext/date_time/zones.rb
+++ b/activesupport/lib/active_support/core_ext/date_time/zones.rb
@@ -1,25 +1,6 @@
require 'date'
-require 'active_support/core_ext/time/zones'
+require 'active_support/core_ext/date_and_time/zones'
class DateTime
- # Returns the simultaneous time in <tt>Time.zone</tt>.
- #
- # Time.zone = 'Hawaii' # => 'Hawaii'
- # DateTime.new(2000).in_time_zone # => Fri, 31 Dec 1999 14:00:00 HST -10:00
- #
- # This method is similar to Time#localtime, except that it uses <tt>Time.zone</tt>
- # as the local zone instead of the operating system's time zone.
- #
- # You can also pass in a TimeZone instance or string that identifies a TimeZone
- # as an argument, and the conversion will be based on that zone instead of
- # <tt>Time.zone</tt>.
- #
- # DateTime.new(2000).in_time_zone('Alaska') # => Fri, 31 Dec 1999 15:00:00 AKST -09:00
- def in_time_zone(zone = ::Time.zone)
- if zone
- ActiveSupport::TimeWithZone.new(utc? ? self : getutc, ::Time.find_zone!(zone))
- else
- self
- end
- end
+ include DateAndTime::Zones
end
diff --git a/activesupport/lib/active_support/core_ext/hash.rb b/activesupport/lib/active_support/core_ext/hash.rb
index 501483498d..686f12c6da 100644
--- a/activesupport/lib/active_support/core_ext/hash.rb
+++ b/activesupport/lib/active_support/core_ext/hash.rb
@@ -1,6 +1,5 @@
require 'active_support/core_ext/hash/conversions'
require 'active_support/core_ext/hash/deep_merge'
-require 'active_support/core_ext/hash/diff'
require 'active_support/core_ext/hash/except'
require 'active_support/core_ext/hash/indifferent_access'
require 'active_support/core_ext/hash/keys'
diff --git a/activesupport/lib/active_support/core_ext/hash/diff.rb b/activesupport/lib/active_support/core_ext/hash/diff.rb
deleted file mode 100644
index 4359213380..0000000000
--- a/activesupport/lib/active_support/core_ext/hash/diff.rb
+++ /dev/null
@@ -1,16 +0,0 @@
-require 'active_support/deprecation'
-
-class Hash
- # Returns a hash that represents the difference between two hashes.
- #
- # {1 => 2}.diff(1 => 2) # => {}
- # {1 => 2}.diff(1 => 3) # => {1 => 2}
- # {}.diff(1 => 2) # => {1 => 2}
- # {1 => 2, 3 => 4}.diff(1 => 2) # => {3 => 4}
- def diff(other)
- ActiveSupport::Deprecation.warn "Hash#diff is no longer used inside of Rails, and is being deprecated with no replacement. If you're using it to compare hashes for the purpose of testing, please use MiniTest's assert_equal instead."
- dup.
- delete_if { |k, v| other[k] == v }.
- merge!(other.dup.delete_if { |k, v| has_key?(k) })
- end
-end
diff --git a/activesupport/lib/active_support/core_ext/kernel/reporting.rb b/activesupport/lib/active_support/core_ext/kernel/reporting.rb
index 79d3303b41..36ab836457 100644
--- a/activesupport/lib/active_support/core_ext/kernel/reporting.rb
+++ b/activesupport/lib/active_support/core_ext/kernel/reporting.rb
@@ -91,6 +91,7 @@ module Kernel
stream_io.rewind
return captured_stream.read
ensure
+ captured_stream.close
captured_stream.unlink
stream_io.reopen(origin_stream)
end
diff --git a/activesupport/lib/active_support/core_ext/logger.rb b/activesupport/lib/active_support/core_ext/logger.rb
deleted file mode 100644
index 34de766331..0000000000
--- a/activesupport/lib/active_support/core_ext/logger.rb
+++ /dev/null
@@ -1,67 +0,0 @@
-require 'active_support/core_ext/class/attribute_accessors'
-require 'active_support/deprecation'
-require 'active_support/logger_silence'
-
-ActiveSupport::Deprecation.warn 'this file is deprecated and will be removed'
-
-# Adds the 'around_level' method to Logger.
-class Logger #:nodoc:
- def self.define_around_helper(level)
- module_eval <<-end_eval, __FILE__, __LINE__ + 1
- def around_#{level}(before_message, after_message) # def around_debug(before_message, after_message, &block)
- self.#{level}(before_message) # self.debug(before_message)
- return_value = yield(self) # return_value = yield(self)
- self.#{level}(after_message) # self.debug(after_message)
- return_value # return_value
- end # end
- end_eval
- end
- [:debug, :info, :error, :fatal].each {|level| define_around_helper(level) }
-end
-
-require 'logger'
-
-# Extensions to the built-in Ruby logger.
-#
-# If you want to use the default log formatter as defined in the Ruby core, then you
-# will need to set the formatter for the logger as in:
-#
-# logger.formatter = Formatter.new
-#
-# You can then specify the datetime format, for example:
-#
-# logger.datetime_format = "%Y-%m-%d"
-#
-# Note: This logger is deprecated in favor of ActiveSupport::Logger
-class Logger
- include LoggerSilence
-
- alias :old_datetime_format= :datetime_format=
- # Logging date-time format (string passed to +strftime+). Ignored if the formatter
- # does not respond to datetime_format=.
- def datetime_format=(format)
- formatter.datetime_format = format if formatter.respond_to?(:datetime_format=)
- end
-
- alias :old_datetime_format :datetime_format
- # Get the logging datetime format. Returns nil if the formatter does not support
- # datetime formatting.
- def datetime_format
- formatter.datetime_format if formatter.respond_to?(:datetime_format)
- end
-
- alias :old_initialize :initialize
- # Overwrite initialize to set a default formatter.
- def initialize(*args)
- old_initialize(*args)
- self.formatter = SimpleFormatter.new
- end
-
- # Simple formatter which only displays the message.
- class SimpleFormatter < Logger::Formatter
- # This method is invoked when a log event occurs
- def call(severity, timestamp, progname, msg)
- "#{String === msg ? msg : msg.inspect}\n"
- end
- end
-end
diff --git a/activesupport/lib/active_support/core_ext/module/delegation.rb b/activesupport/lib/active_support/core_ext/module/delegation.rb
index 6d42667e97..182e74d9e1 100644
--- a/activesupport/lib/active_support/core_ext/module/delegation.rb
+++ b/activesupport/lib/active_support/core_ext/module/delegation.rb
@@ -1,7 +1,16 @@
class Module
+ # Error generated by +delegate+ when a method is called on +nil+ and +allow_nil+
+ # option is not used.
+ class DelegationError < NoMethodError; end
+
# Provides a +delegate+ class method to easily expose contained objects'
# public methods as your own.
#
+ # ==== Options
+ # * <tt>:to</tt> - Specifies the target object
+ # * <tt>:prefix</tt> - Prefixes the new method with the target name or a custom prefix
+ # * <tt>:allow_nil</tt> - if set to true, prevents a +NoMethodError+ to be raised
+ #
# The macro receives one or more method names (specified as symbols or
# strings) and the name of the target object via the <tt>:to</tt> option
# (also a symbol or string).
@@ -164,7 +173,7 @@ class Module
#
# Reason is twofold: On one hand doing less calls is in general better.
# On the other hand it could be that the target has side-effects,
- # whereas conceptualy, from the user point of view, the delegator should
+ # whereas conceptually, from the user point of view, the delegator should
# be doing one call.
if allow_nil
module_eval(<<-EOS, file, line - 3)
@@ -176,19 +185,19 @@ class Module
end # end
EOS
else
- exception = %(raise "#{self}##{method_prefix}#{method} delegated to #{to}.#{method}, but #{to} is nil: \#{self.inspect}")
+ exception = %(raise DelegationError, "#{self}##{method_prefix}#{method} delegated to #{to}.#{method}, but #{to} is nil: \#{self.inspect}")
module_eval(<<-EOS, file, line - 2)
- def #{method_prefix}#{method}(#{definition}) # def customer_name(*args, &block)
- _ = #{to} # _ = client
- _.#{method}(#{definition}) # _.name(*args, &block)
- rescue NoMethodError # rescue NoMethodError
- if _.nil? # if _.nil?
- #{exception} # # add helpful message to the exception
- else # else
- raise # raise
- end # end
- end # end
+ def #{method_prefix}#{method}(#{definition}) # def customer_name(*args, &block)
+ _ = #{to} # _ = client
+ _.#{method}(#{definition}) # _.name(*args, &block)
+ rescue NoMethodError => e # rescue NoMethodError => e
+ if _.nil? && e.name == :#{method} # if _.nil? && e.name == :name
+ #{exception} # # add helpful message to the exception
+ else # else
+ raise # raise
+ end # end
+ end # end
EOS
end
end
diff --git a/activesupport/lib/active_support/core_ext/module/introspection.rb b/activesupport/lib/active_support/core_ext/module/introspection.rb
index 08e5f8a5c3..f1d26ef28f 100644
--- a/activesupport/lib/active_support/core_ext/module/introspection.rb
+++ b/activesupport/lib/active_support/core_ext/module/introspection.rb
@@ -59,20 +59,4 @@ class Module
def local_constants #:nodoc:
constants(false)
end
-
- # *DEPRECATED*: Use +local_constants+ instead.
- #
- # Returns the names of the constants defined locally as strings.
- #
- # module M
- # X = 1
- # end
- # M.local_constant_names # => ["X"]
- #
- # This method is useful for forward compatibility, since Ruby 1.8 returns
- # constant names as strings, whereas 1.9 returns them as symbols.
- def local_constant_names
- ActiveSupport::Deprecation.warn 'Module#local_constant_names is deprecated, use Module#local_constants instead'
- local_constants.map { |c| c.to_s }
- end
end
diff --git a/activesupport/lib/active_support/core_ext/module/method_transplanting.rb b/activesupport/lib/active_support/core_ext/module/method_transplanting.rb
new file mode 100644
index 0000000000..b1097cc83b
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/module/method_transplanting.rb
@@ -0,0 +1,11 @@
+class Module
+ ###
+ # TODO: remove this after 1.9 support is dropped
+ def methods_transplantable? # :nodoc:
+ x = Module.new { def foo; end }
+ Module.new { define_method :bar, x.instance_method(:foo) }
+ true
+ rescue TypeError
+ false
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/object/try.rb b/activesupport/lib/active_support/core_ext/object/try.rb
index 534bbe3c42..48190e1e66 100644
--- a/activesupport/lib/active_support/core_ext/object/try.rb
+++ b/activesupport/lib/active_support/core_ext/object/try.rb
@@ -47,7 +47,7 @@ class Object
end
# Same as #try, but will raise a NoMethodError exception if the receiving is not nil and
- # does not implemented the tried method.
+ # does not implement the tried method.
def try!(*a, &b)
if a.empty? && block_given?
yield self
diff --git a/activesupport/lib/active_support/core_ext/proc.rb b/activesupport/lib/active_support/core_ext/proc.rb
deleted file mode 100644
index 166c3855a0..0000000000
--- a/activesupport/lib/active_support/core_ext/proc.rb
+++ /dev/null
@@ -1,17 +0,0 @@
-require "active_support/core_ext/kernel/singleton_class"
-require "active_support/deprecation"
-
-class Proc #:nodoc:
- def bind(object)
- ActiveSupport::Deprecation.warn 'Proc#bind is deprecated and will be removed in future versions'
-
- block, time = self, Time.now
- object.class_eval do
- method_name = "__bind_#{time.to_i}_#{time.usec}"
- define_method(method_name, &block)
- method = instance_method(method_name)
- remove_method(method_name)
- method
- end.bind(object)
- end
-end
diff --git a/activesupport/lib/active_support/core_ext/range.rb b/activesupport/lib/active_support/core_ext/range.rb
index 1d8b1ede5a..9368e81235 100644
--- a/activesupport/lib/active_support/core_ext/range.rb
+++ b/activesupport/lib/active_support/core_ext/range.rb
@@ -1,3 +1,4 @@
require 'active_support/core_ext/range/conversions'
require 'active_support/core_ext/range/include_range'
require 'active_support/core_ext/range/overlaps'
+require 'active_support/core_ext/range/each'
diff --git a/activesupport/lib/active_support/core_ext/range/each.rb b/activesupport/lib/active_support/core_ext/range/each.rb
new file mode 100644
index 0000000000..d51ea2e944
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/range/each.rb
@@ -0,0 +1,24 @@
+require 'active_support/core_ext/module/aliasing'
+require 'active_support/core_ext/object/acts_like'
+
+class Range #:nodoc:
+
+ def each_with_time_with_zone(&block)
+ ensure_iteration_allowed
+ each_without_time_with_zone(&block)
+ end
+ alias_method_chain :each, :time_with_zone
+
+ def step_with_time_with_zone(n = 1, &block)
+ ensure_iteration_allowed
+ step_without_time_with_zone(n, &block)
+ end
+ alias_method_chain :step, :time_with_zone
+
+ private
+ def ensure_iteration_allowed
+ if first.acts_like?(:time)
+ raise TypeError, "can't iterate from #{first.class}"
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/string/access.rb b/activesupport/lib/active_support/core_ext/string/access.rb
index 8fa8157d65..ee3b6d2b3f 100644
--- a/activesupport/lib/active_support/core_ext/string/access.rb
+++ b/activesupport/lib/active_support/core_ext/string/access.rb
@@ -59,7 +59,7 @@ class String
# str.from(0).to(-1) #=> "hello"
# str.from(1).to(-2) #=> "ell"
def to(position)
- self[0..position]
+ self[0, position + 1]
end
# Returns the first character. If a limit is supplied, returns a substring
diff --git a/activesupport/lib/active_support/core_ext/string/encoding.rb b/activesupport/lib/active_support/core_ext/string/encoding.rb
deleted file mode 100644
index a583b914db..0000000000
--- a/activesupport/lib/active_support/core_ext/string/encoding.rb
+++ /dev/null
@@ -1,8 +0,0 @@
-require 'active_support/deprecation'
-
-class String
- def encoding_aware?
- ActiveSupport::Deprecation.warn 'String#encoding_aware? is deprecated'
- true
- 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 c62bb41416..49c0df6026 100644
--- a/activesupport/lib/active_support/core_ext/string/filters.rb
+++ b/activesupport/lib/active_support/core_ext/string/filters.rb
@@ -20,6 +20,16 @@ class String
self
end
+ # Returns a new string with all occurrences of the pattern removed. Short-hand for String#gsub(pattern, '').
+ def remove(pattern)
+ gsub pattern, ''
+ end
+
+ # Alters the string by removing all occurrences of the pattern. Short-hand for String#gsub!(pattern, '').
+ def remove!(pattern)
+ gsub! pattern, ''
+ end
+
# Truncates a given +text+ after a given <tt>length</tt> if +text+ is longer than <tt>length</tt>:
#
# 'Once upon a time in a world far far away'.truncate(27)
@@ -41,8 +51,8 @@ class String
def truncate(truncate_at, options = {})
return dup unless length > truncate_at
- options[:omission] ||= '...'
- length_with_room_for_omission = truncate_at - options[:omission].length
+ omission = options[:omission] || '...'
+ length_with_room_for_omission = truncate_at - omission.length
stop = \
if options[:separator]
rindex(options[:separator], length_with_room_for_omission) || length_with_room_for_omission
@@ -50,6 +60,6 @@ class String
length_with_room_for_omission
end
- "#{self[0...stop]}#{options[:omission]}"
+ "#{self[0, stop]}#{omission}"
end
end
diff --git a/activesupport/lib/active_support/core_ext/string/zones.rb b/activesupport/lib/active_support/core_ext/string/zones.rb
index e3f20eee29..510c884c18 100644
--- a/activesupport/lib/active_support/core_ext/string/zones.rb
+++ b/activesupport/lib/active_support/core_ext/string/zones.rb
@@ -1,3 +1,4 @@
+require 'active_support/core_ext/string/conversions'
require 'active_support/core_ext/time/zones'
class String
diff --git a/activesupport/lib/active_support/core_ext/thread.rb b/activesupport/lib/active_support/core_ext/thread.rb
index 5481766f10..e80f442973 100644
--- a/activesupport/lib/active_support/core_ext/thread.rb
+++ b/activesupport/lib/active_support/core_ext/thread.rb
@@ -23,14 +23,14 @@ class Thread
# for the fiber local. The fiber is executed in the same thread, so the
# thread local values are available.
def thread_variable_get(key)
- locals[key.to_sym]
+ _locals[key.to_sym]
end
# Sets a thread local with +key+ to +value+. Note that these are local to
# threads, and not to fibers. Please see Thread#thread_variable_get for
# more information.
def thread_variable_set(key, value)
- locals[key.to_sym] = value
+ _locals[key.to_sym] = value
end
# Returns an an array of the names of the thread-local variables (as Symbols).
@@ -45,7 +45,7 @@ class Thread
# Note that these are not fiber local variables. Please see Thread#thread_variable_get
# for more details.
def thread_variables
- locals.keys
+ _locals.keys
end
# Returns <tt>true</tt> if the given string (or symbol) exists as a
@@ -59,16 +59,21 @@ class Thread
# Note that these are not fiber local variables. Please see Thread#thread_variable_get
# for more details.
def thread_variable?(key)
- locals.has_key?(key.to_sym)
+ _locals.has_key?(key.to_sym)
+ end
+
+ def freeze
+ _locals.freeze
+ super
end
private
- def locals
- if defined?(@locals)
- @locals
+ def _locals
+ if defined?(@_locals)
+ @_locals
else
- LOCK.synchronize { @locals ||= {} }
+ LOCK.synchronize { @_locals ||= {} }
end
end
end unless Thread.instance_methods.include?(:thread_variable_set)
diff --git a/activesupport/lib/active_support/core_ext/time/calculations.rb b/activesupport/lib/active_support/core_ext/time/calculations.rb
index a3ce7dbe3f..6e0af0db4d 100644
--- a/activesupport/lib/active_support/core_ext/time/calculations.rb
+++ b/activesupport/lib/active_support/core_ext/time/calculations.rb
@@ -3,7 +3,6 @@ require 'active_support/core_ext/time/conversions'
require 'active_support/time_with_zone'
require 'active_support/core_ext/time/zones'
require 'active_support/core_ext/date_and_time/calculations'
-require 'active_support/deprecation'
class Time
include DateAndTime::Calculations
@@ -26,45 +25,27 @@ class Time
end
end
- # *DEPRECATED*: Use +Time#utc+ or +Time#local+ instead.
- #
- # Returns a new Time if requested year can be accommodated by Ruby's Time class
- # (i.e., if year is within either 1970..2038 or 1902..2038, depending on system architecture);
- # otherwise returns a DateTime.
- def time_with_datetime_fallback(utc_or_local, year, month=1, day=1, hour=0, min=0, sec=0, usec=0)
- ActiveSupport::Deprecation.warn 'time_with_datetime_fallback is deprecated. Use Time#utc or Time#local instead', caller
- time = ::Time.send(utc_or_local, year, month, day, hour, min, sec, usec)
-
- # This check is needed because Time.utc(y) returns a time object in the 2000s for 0 <= y <= 138.
- if time.year == year
- time
- else
- ::DateTime.civil_from_format(utc_or_local, year, month, day, hour, min, sec)
- end
- rescue
- ::DateTime.civil_from_format(utc_or_local, year, month, day, hour, min, sec)
+ # Returns <tt>Time.zone.now</tt> when <tt>Time.zone</tt> or <tt>config.time_zone</tt> are set, otherwise just returns <tt>Time.now</tt>.
+ def current
+ ::Time.zone ? ::Time.zone.now : ::Time.now
end
- # *DEPRECATED*: Use +Time#utc+ instead.
- #
- # Wraps class method +time_with_datetime_fallback+ with +utc_or_local+ set to <tt>:utc</tt>.
- def utc_time(*args)
- ActiveSupport::Deprecation.warn 'utc_time is deprecated. Use Time#utc instead', caller
- time_with_datetime_fallback(:utc, *args)
- end
+ # Layers additional behavior on Time.at so that ActiveSupport::TimeWithZone and DateTime
+ # instances can be used when called with a single argument
+ def at_with_coercion(*args)
+ return at_without_coercion(*args) if args.size != 1
- # *DEPRECATED*: Use +Time#local+ instead.
- #
- # Wraps class method +time_with_datetime_fallback+ with +utc_or_local+ set to <tt>:local</tt>.
- def local_time(*args)
- ActiveSupport::Deprecation.warn 'local_time is deprecated. Use Time#local instead', caller
- time_with_datetime_fallback(:local, *args)
- end
+ # Time.at can be called with a time or numerical value
+ time_or_number = args.first
- # Returns <tt>Time.zone.now</tt> when <tt>Time.zone</tt> or <tt>config.time_zone</tt> are set, otherwise just returns <tt>Time.now</tt>.
- def current
- ::Time.zone ? ::Time.zone.now : ::Time.now
+ if time_or_number.is_a?(ActiveSupport::TimeWithZone) || time_or_number.is_a?(DateTime)
+ at_without_coercion(time_or_number.to_f).getlocal
+ else
+ at_without_coercion(time_or_number)
+ end
end
+ alias_method :at_without_coercion, :at
+ alias_method :at, :at_with_coercion
end
# Seconds since midnight: Time.now.seconds_since_midnight
@@ -161,6 +142,16 @@ class Time
alias :at_midnight :beginning_of_day
alias :at_beginning_of_day :beginning_of_day
+ # Returns a new Time representing the middle of the day (12:00)
+ def middle_of_day
+ change(:hour => 12)
+ end
+ alias :midday :middle_of_day
+ alias :noon :middle_of_day
+ alias :at_midday :middle_of_day
+ alias :at_noon :middle_of_day
+ alias :at_middle_of_day :middle_of_day
+
# Returns a new Time representing the end of the day, 23:59:59.999999 (.999999999 in ruby1.9)
def end_of_day
change(
diff --git a/activesupport/lib/active_support/core_ext/time/conversions.rb b/activesupport/lib/active_support/core_ext/time/conversions.rb
index 48654eb1cc..9fd26156c7 100644
--- a/activesupport/lib/active_support/core_ext/time/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/time/conversions.rb
@@ -16,7 +16,8 @@ class Time
:rfc822 => lambda { |time|
offset_format = time.formatted_offset(false)
time.strftime("%a, %d %b %Y %H:%M:%S #{offset_format}")
- }
+ },
+ :iso8601 => lambda { |time| time.iso8601 }
}
# Converts to a formatted string. See DATE_FORMATS for builtin formats.
@@ -34,6 +35,7 @@ class Time
# time.to_formatted_s(:long) # => "January 18, 2007 06:10"
# time.to_formatted_s(:long_ordinal) # => "January 18th, 2007 06:10"
# time.to_formatted_s(:rfc822) # => "Thu, 18 Jan 2007 06:10:17 -0600"
+ # time.to_formatted_s(:iso8601) # => "2007-01-18T06:10:17-06:00"
#
# == Adding your own time formats to +to_formatted_s+
# You can add your own formats to the Time::DATE_FORMATS hash.
diff --git a/activesupport/lib/active_support/core_ext/time/zones.rb b/activesupport/lib/active_support/core_ext/time/zones.rb
index 139d48f59c..bbda04d60c 100644
--- a/activesupport/lib/active_support/core_ext/time/zones.rb
+++ b/activesupport/lib/active_support/core_ext/time/zones.rb
@@ -1,6 +1,8 @@
require 'active_support/time_with_zone'
+require 'active_support/core_ext/date_and_time/zones'
class Time
+ include DateAndTime::Zones
class << self
attr_accessor :zone_default
@@ -73,24 +75,4 @@ class Time
find_zone!(time_zone) rescue nil
end
end
-
- # Returns the simultaneous time in <tt>Time.zone</tt>.
- #
- # Time.zone = 'Hawaii' # => 'Hawaii'
- # Time.utc(2000).in_time_zone # => Fri, 31 Dec 1999 14:00:00 HST -10:00
- #
- # This method is similar to Time#localtime, except that it uses <tt>Time.zone</tt> as the local zone
- # instead of the operating system's time zone.
- #
- # You can also pass in a TimeZone instance or string that identifies a TimeZone as an argument,
- # and the conversion will be based on that zone instead of <tt>Time.zone</tt>.
- #
- # Time.utc(2000).in_time_zone('Alaska') # => Fri, 31 Dec 1999 15:00:00 AKST -09:00
- def in_time_zone(zone = ::Time.zone)
- if zone
- ActiveSupport::TimeWithZone.new(utc? ? self : getutc, ::Time.find_zone!(zone))
- else
- self
- end
- end
end
diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb
index 565d933cb3..6ca5d76fbb 100644
--- a/activesupport/lib/active_support/dependencies.rb
+++ b/activesupport/lib/active_support/dependencies.rb
@@ -215,7 +215,7 @@ module ActiveSupport #:nodoc:
yield
end
rescue Exception => exception # errors from loading file
- exception.blame_file! file
+ exception.blame_file! file if exception.respond_to? :blame_file!
raise
end
@@ -418,7 +418,7 @@ module ActiveSupport #:nodoc:
def load_file(path, const_paths = loadable_constants_for_path(path))
log_call path, const_paths
const_paths = [const_paths].compact unless const_paths.is_a? Array
- parent_paths = const_paths.collect { |const_path| const_path[/.*(?=::)/] || :Object }
+ parent_paths = const_paths.collect { |const_path| const_path[/.*(?=::)/] || ::Object }
result = nil
newly_defined_paths = new_constants_in(*parent_paths) do
@@ -461,7 +461,7 @@ module ActiveSupport #:nodoc:
if loaded.include?(expanded)
raise "Circular dependency detected while autoloading constant #{qualified_name}"
else
- require_or_load(expanded)
+ require_or_load(expanded, qualified_name)
raise LoadError, "Unable to autoload constant #{qualified_name}, expected #{file_path} to define it" unless from_mod.const_defined?(const_name, false)
return from_mod.const_get(const_name)
end
@@ -636,7 +636,7 @@ module ActiveSupport #:nodoc:
when String then desc.sub(/^::/, '')
when Symbol then desc.to_s
when Module
- desc.name.presence ||
+ desc.name ||
raise(ArgumentError, "Anonymous modules have no name to be referenced by")
else raise TypeError, "Not a valid constant descriptor: #{desc.inspect}"
end
diff --git a/activesupport/lib/active_support/deprecation.rb b/activesupport/lib/active_support/deprecation.rb
index 6c15fffc0f..ab16977bda 100644
--- a/activesupport/lib/active_support/deprecation.rb
+++ b/activesupport/lib/active_support/deprecation.rb
@@ -25,14 +25,14 @@ module ActiveSupport
include Reporting
include MethodWrapper
- # The version the deprecated behavior will be removed, by default.
+ # The version number in which the deprecated behavior will be removed, by default.
attr_accessor :deprecation_horizon
- # It accepts two parameters on initialization. The first is an version of library
- # and the second is an library name
+ # It accepts two parameters on initialization. The first is a version of library
+ # and the second is a library name
#
# ActiveSupport::Deprecation.new('2.0', 'MyLibrary')
- def initialize(deprecation_horizon = '4.1', gem_name = 'Rails')
+ def initialize(deprecation_horizon = '4.2', gem_name = 'Rails')
self.gem_name = gem_name
self.deprecation_horizon = deprecation_horizon
# By default, warnings are not silenced and debugging is off.
diff --git a/activesupport/lib/active_support/deprecation/behaviors.rb b/activesupport/lib/active_support/deprecation/behaviors.rb
index 90db180124..328b8c320a 100644
--- a/activesupport/lib/active_support/deprecation/behaviors.rb
+++ b/activesupport/lib/active_support/deprecation/behaviors.rb
@@ -1,14 +1,24 @@
require "active_support/notifications"
module ActiveSupport
+ class DeprecationException < StandardError
+ end
+
class Deprecation
# Default warning behaviors per Rails.env.
DEFAULT_BEHAVIORS = {
- :stderr => Proc.new { |message, callstack|
+ raise: ->(message, callstack) {
+ e = DeprecationException.new(message)
+ e.set_backtrace(callstack)
+ raise e
+ },
+
+ stderr: ->(message, callstack) {
$stderr.puts(message)
$stderr.puts callstack.join("\n ") if debug
},
- :log => Proc.new { |message, callstack|
+
+ log: ->(message, callstack) {
logger =
if defined?(Rails) && Rails.logger
Rails.logger
@@ -19,11 +29,13 @@ module ActiveSupport
logger.warn message
logger.debug callstack.join("\n ") if debug
},
- :notify => Proc.new { |message, callstack|
+
+ notify: ->(message, callstack) {
ActiveSupport::Notifications.instrument("deprecation.rails",
:message => message, :callstack => callstack)
},
- :silence => Proc.new { |message, callstack| }
+
+ silence: ->(message, callstack) {},
}
module Behavior
@@ -40,6 +52,7 @@ module ActiveSupport
#
# Available behaviors:
#
+ # [+raise+] Raise <tt>ActiveSupport::DeprecationException</tt>.
# [+stderr+] Log all deprecation warnings to +$stderr+.
# [+log+] Log all deprecation warnings to +Rails.logger+.
# [+notify+] Use +ActiveSupport::Notifications+ to notify +deprecation.rails+.
@@ -52,7 +65,7 @@ module ActiveSupport
# ActiveSupport::Deprecation.behavior = :stderr
# ActiveSupport::Deprecation.behavior = [:stderr, :log]
# ActiveSupport::Deprecation.behavior = MyCustomHandler
- # ActiveSupport::Deprecation.behavior = proc { |message, callstack|
+ # ActiveSupport::Deprecation.behavior = ->(message, callstack) {
# # custom stuff
# }
def behavior=(behavior)
diff --git a/activesupport/lib/active_support/duration.rb b/activesupport/lib/active_support/duration.rb
index 2cb1f408b6..87b6407038 100644
--- a/activesupport/lib/active_support/duration.rb
+++ b/activesupport/lib/active_support/duration.rb
@@ -70,13 +70,11 @@ module ActiveSupport
alias :until :ago
def inspect #:nodoc:
- consolidated = parts.inject(::Hash.new(0)) { |h,(l,r)| h[l] += r; h }
- parts = [:years, :months, :days, :minutes, :seconds].map do |length|
- n = consolidated[length]
- "#{n} #{n == 1 ? length.to_s.singularize : length.to_s}" if n.nonzero?
- end.compact
- parts = ["0 seconds"] if parts.empty?
- parts.to_sentence(:locale => :en)
+ parts.
+ reduce(::Hash.new(0)) { |h,(l,r)| h[l] += r; h }.
+ sort_by {|unit, _ | [:years, :months, :days, :minutes, :seconds].index(unit)}.
+ map {|unit, val| "#{val} #{val == 1 ? unit.to_s.chop : unit.to_s}"}.
+ to_sentence(:locale => :en)
end
def as_json(options = nil) #:nodoc:
diff --git a/activesupport/lib/active_support/file_update_checker.rb b/activesupport/lib/active_support/file_update_checker.rb
index 20136dd1b0..d6918bede2 100644
--- a/activesupport/lib/active_support/file_update_checker.rb
+++ b/activesupport/lib/active_support/file_update_checker.rb
@@ -115,7 +115,7 @@ module ActiveSupport
end
def compile_glob(hash)
- hash.freeze # Freeze so changes aren't accidently pushed
+ hash.freeze # Freeze so changes aren't accidentally pushed
return if hash.empty?
globs = hash.map do |key, value|
diff --git a/activesupport/lib/active_support/hash_with_indifferent_access.rb b/activesupport/lib/active_support/hash_with_indifferent_access.rb
index bdb8877f55..3da99872c0 100644
--- a/activesupport/lib/active_support/hash_with_indifferent_access.rb
+++ b/activesupport/lib/active_support/hash_with_indifferent_access.rb
@@ -91,7 +91,7 @@ module ActiveSupport
#
# This value can be later fetched using either +:key+ or +'key'+.
def []=(key, value)
- regular_writer(convert_key(key), convert_value(value))
+ regular_writer(convert_key(key), convert_value(value, for: :assignment))
end
alias_method :store, :[]=
@@ -224,14 +224,18 @@ module ActiveSupport
undef :symbolize_keys!
undef :deep_symbolize_keys!
def symbolize_keys; to_hash.symbolize_keys! end
- def deep_symbolize_keys; to_hash.deep_symbolize_keys end
+ def deep_symbolize_keys; to_hash.deep_symbolize_keys! end
def to_options!; self end
+ def select(*args, &block)
+ dup.tap {|hash| hash.select!(*args, &block)}
+ end
+
# Convert to a regular hash with string keys.
def to_hash
_new_hash= {}
each do |key, value|
- _new_hash[convert_key(key)] = convert_value(value, true)
+ _new_hash[convert_key(key)] = convert_value(value, for: :to_hash)
end
Hash.new(default).merge!(_new_hash)
end
@@ -241,12 +245,18 @@ module ActiveSupport
key.kind_of?(Symbol) ? key.to_s : key
end
- def convert_value(value, _convert_for_to_hash = false)
+ def convert_value(value, options = {})
if value.is_a? Hash
- _convert_for_to_hash ? value.to_hash : value.nested_under_indifferent_access
+ if options[:for] == :to_hash
+ value.to_hash
+ else
+ value.nested_under_indifferent_access
+ end
elsif value.is_a?(Array)
- value = value.dup if value.frozen?
- value.map! { |e| convert_value(e, _convert_for_to_hash) }
+ unless options[:for] == :assignment
+ value = value.dup
+ end
+ value.map! { |e| convert_value(e, options) }
else
value
end
diff --git a/activesupport/lib/active_support/inflections.rb b/activesupport/lib/active_support/inflections.rb
index ef882ebd09..4ea6abfa12 100644
--- a/activesupport/lib/active_support/inflections.rb
+++ b/activesupport/lib/active_support/inflections.rb
@@ -57,7 +57,6 @@ module ActiveSupport
inflect.irregular('child', 'children')
inflect.irregular('sex', 'sexes')
inflect.irregular('move', 'moves')
- inflect.irregular('cow', 'kine')
inflect.irregular('zombie', 'zombies')
inflect.uncountable(%w(equipment information rice money species series fish sheep jeans police))
diff --git a/activesupport/lib/active_support/inflector/methods.rb b/activesupport/lib/active_support/inflector/methods.rb
index 39648727fd..ffdb7b53c4 100644
--- a/activesupport/lib/active_support/inflector/methods.rb
+++ b/activesupport/lib/active_support/inflector/methods.rb
@@ -1,6 +1,5 @@
# encoding: utf-8
-require 'active_support/inflector/inflections'
require 'active_support/inflections'
module ActiveSupport
@@ -37,7 +36,7 @@ module ActiveSupport
# string.
#
# If passed an optional +locale+ parameter, the word will be
- # pluralized using rules defined for that language. By default,
+ # singularized using rules defined for that language. By default,
# this parameter is set to <tt>:en</tt>.
#
# 'posts'.singularize # => "post"
@@ -73,7 +72,9 @@ module ActiveSupport
else
string = string.sub(/^(?:#{inflections.acronym_regex}(?=\b|[A-Z_])|\w)/) { $&.downcase }
end
- string.gsub(/(?:_|(\/))([a-z\d]*)/i) { "#{$1}#{inflections.acronyms[$2] || $2.capitalize}" }.gsub('/', '::')
+ string.gsub!(/(?:_|(\/))([a-z\d]*)/i) { "#{$1}#{inflections.acronyms[$2] || $2.capitalize}" }
+ string.gsub!('/', '::')
+ string
end
# Makes an underscored, lowercase form from the expression in the string.
@@ -88,8 +89,7 @@ module ActiveSupport
#
# 'SSLError'.underscore.camelize # => "SslError"
def underscore(camel_cased_word)
- word = camel_cased_word.to_s.dup
- word.gsub!('::', '/')
+ word = camel_cased_word.to_s.gsub('::', '/')
word.gsub!(/(?:([A-Za-z\d])|^)(#{inflections.acronym_regex})(?=\b|[^a-z])/) { "#{$1}#{$1 && '_'}#{$2.downcase}" }
word.gsub!(/([A-Z\d]+)([A-Z][a-z])/,'\1_\2')
word.gsub!(/([a-z\d])([A-Z])/,'\1_\2')
@@ -185,7 +185,7 @@ module ActiveSupport
#
# See also +demodulize+.
def deconstantize(path)
- path.to_s[0...(path.rindex('::') || 0)] # implementation based on the one in facets' Module#spacename
+ path.to_s[0, path.rindex('::') || 0] # implementation based on the one in facets' Module#spacename
end
# Creates a foreign key name from a class name.
@@ -219,7 +219,12 @@ module ActiveSupport
# unknown.
def constantize(camel_cased_word)
names = camel_cased_word.split('::')
- names.shift if names.empty? || names.first.empty?
+
+ # Trigger a builtin NameError exception including the ill-formed constant in the message.
+ Object.const_get(camel_cased_word) if names.empty?
+
+ # Remove the first blank element in case of '::ClassName' notation.
+ names.shift if names.size > 1 && names.first.empty?
names.inject(Object) do |constant, name|
if constant == Object
@@ -314,9 +319,14 @@ module ActiveSupport
private
# Mount a regular expression that will match part by part of the constant.
- # For instance, Foo::Bar::Baz will generate Foo(::Bar(::Baz)?)?
+ #
+ # const_regexp("Foo::Bar::Baz") # => /Foo(::Bar(::Baz)?)?/
+ # const_regexp("::") # => /::/
def const_regexp(camel_cased_word) #:nodoc:
parts = camel_cased_word.split("::")
+
+ return Regexp.escape(camel_cased_word) if parts.blank?
+
last = parts.pop
parts.reverse.inject(last) do |acc, part|
diff --git a/activesupport/lib/active_support/json/decoding.rb b/activesupport/lib/active_support/json/decoding.rb
index 30833a4cb1..21de09c1cc 100644
--- a/activesupport/lib/active_support/json/decoding.rb
+++ b/activesupport/lib/active_support/json/decoding.rb
@@ -13,8 +13,8 @@ module ActiveSupport
#
# ActiveSupport::JSON.decode("{\"team\":\"rails\",\"players\":\"36\"}")
# => {"team" => "rails", "players" => "36"}
- def decode(json, proc = nil, options = {})
- data = ::JSON.load(json, proc, options)
+ def decode(json, options = {})
+ data = ::JSON.parse(json, options.merge(create_additions: false, quirks_mode: true))
if ActiveSupport.parse_json_times
convert_dates_from(data)
else
diff --git a/activesupport/lib/active_support/json/encoding.rb b/activesupport/lib/active_support/json/encoding.rb
index 7f8b41d218..77b5d8d227 100644
--- a/activesupport/lib/active_support/json/encoding.rb
+++ b/activesupport/lib/active_support/json/encoding.rb
@@ -2,7 +2,6 @@
require 'active_support/core_ext/object/to_json'
require 'active_support/core_ext/module/delegation'
-require 'active_support/json/variable'
require 'bigdecimal'
require 'active_support/core_ext/big_decimal/conversions' # for #to_s
diff --git a/activesupport/lib/active_support/json/variable.rb b/activesupport/lib/active_support/json/variable.rb
deleted file mode 100644
index d69dab6408..0000000000
--- a/activesupport/lib/active_support/json/variable.rb
+++ /dev/null
@@ -1,18 +0,0 @@
-require 'active_support/deprecation'
-
-module ActiveSupport
- module JSON
- # Deprecated: A string that returns itself as its JSON-encoded form.
- class Variable < String
- def initialize(*args)
- message = 'ActiveSupport::JSON::Variable is deprecated and will be removed in Rails 4.1. ' \
- 'For your own custom JSON literals, define #as_json and #encode_json yourself.'
- ActiveSupport::Deprecation.warn message
- super
- end
-
- def as_json(options = nil) self end #:nodoc:
- def encode_json(encoder) self end #:nodoc:
- end
- end
-end
diff --git a/activesupport/lib/active_support/log_subscriber/test_helper.rb b/activesupport/lib/active_support/log_subscriber/test_helper.rb
index f9a98686d3..75f353f62c 100644
--- a/activesupport/lib/active_support/log_subscriber/test_helper.rb
+++ b/activesupport/lib/active_support/log_subscriber/test_helper.rb
@@ -1,5 +1,5 @@
require 'active_support/log_subscriber'
-require 'active_support/buffered_logger'
+require 'active_support/logger'
require 'active_support/notifications'
module ActiveSupport
diff --git a/activesupport/lib/active_support/multibyte/chars.rb b/activesupport/lib/active_support/multibyte/chars.rb
index a42e7f6542..3c0cf9f137 100644
--- a/activesupport/lib/active_support/multibyte/chars.rb
+++ b/activesupport/lib/active_support/multibyte/chars.rb
@@ -56,11 +56,10 @@ module ActiveSupport #:nodoc:
# Forward all undefined methods to the wrapped string.
def method_missing(method, *args, &block)
+ result = @wrapped_string.__send__(method, *args, &block)
if method.to_s =~ /!$/
- 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
end
end
diff --git a/activesupport/lib/active_support/multibyte/unicode.rb b/activesupport/lib/active_support/multibyte/unicode.rb
index f1dfff738c..1845c6ae38 100644
--- a/activesupport/lib/active_support/multibyte/unicode.rb
+++ b/activesupport/lib/active_support/multibyte/unicode.rb
@@ -145,7 +145,7 @@ module ActiveSupport
ncp << (HANGUL_TBASE + tindex) unless tindex == 0
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)
+ elsif (ncp = database.codepoints[cp].decomp_mapping) and (!database.codepoints[cp].decomp_type || type == :compatibility)
decomposed.concat decompose(type, ncp.dup)
else
decomposed << cp
@@ -263,9 +263,9 @@ module ActiveSupport
when :c
compose(reorder_characters(decompose(:canonical, codepoints)))
when :kd
- reorder_characters(decompose(:compatability, codepoints))
+ reorder_characters(decompose(:compatibility, codepoints))
when :kc
- compose(reorder_characters(decompose(:compatability, codepoints)))
+ compose(reorder_characters(decompose(:compatibility, codepoints)))
else
raise ArgumentError, "#{form} is not a valid normalization variant", caller
end.pack('U*')
@@ -287,6 +287,13 @@ module ActiveSupport
class Codepoint
attr_accessor :code, :combining_class, :decomp_type, :decomp_mapping, :uppercase_mapping, :lowercase_mapping
+ # Initializing Codepoint object with default values
+ def initialize
+ @combining_class = 0
+ @uppercase_mapping = 0
+ @lowercase_mapping = 0
+ end
+
def swapcase_mapping
uppercase_mapping > 0 ? uppercase_mapping : lowercase_mapping
end
diff --git a/activesupport/lib/active_support/notifications.rb b/activesupport/lib/active_support/notifications.rb
index c45358bba9..b32aa75e59 100644
--- a/activesupport/lib/active_support/notifications.rb
+++ b/activesupport/lib/active_support/notifications.rb
@@ -143,8 +143,8 @@ module ActiveSupport
#
# == Default Queue
#
- # Notifications ships with a queue implementation that consumes and publish events
- # to log subscribers in a thread. You can use any queue implementation you want.
+ # Notifications ships with a queue implementation that consumes and publishes events
+ # to all log subscribers. You can use any queue implementation you want.
#
module Notifications
class << self
diff --git a/activesupport/lib/active_support/notifications/instrumenter.rb b/activesupport/lib/active_support/notifications/instrumenter.rb
index 0c9a729ce5..3a244b34b5 100644
--- a/activesupport/lib/active_support/notifications/instrumenter.rb
+++ b/activesupport/lib/active_support/notifications/instrumenter.rb
@@ -54,10 +54,11 @@ module ActiveSupport
@transaction_id = transaction_id
@end = ending
@children = []
+ @duration = nil
end
def duration
- 1000.0 * (self.end - time)
+ @duration ||= 1000.0 * (self.end - time)
end
def <<(event)
diff --git a/activesupport/lib/active_support/number_helper.rb b/activesupport/lib/active_support/number_helper.rb
index 414960d2b1..c9c0eff2bf 100644
--- a/activesupport/lib/active_support/number_helper.rb
+++ b/activesupport/lib/active_support/number_helper.rb
@@ -244,14 +244,14 @@ module ActiveSupport
#
# ==== Examples
#
- # number_to_percentage(100) # => 100.000%
- # number_to_percentage('98') # => 98.000%
- # number_to_percentage(100, precision: 0) # => 100%
- # number_to_percentage(1000, delimiter: '.', separator: ,') # => 1.000,000%
- # number_to_percentage(302.24398923423, precision: 5) # => 302.24399%
- # number_to_percentage(1000, locale: :fr) # => 1 000,000%
- # number_to_percentage('98a') # => 98a%
- # number_to_percentage(100, format: '%n %') # => 100 %
+ # number_to_percentage(100) # => 100.000%
+ # number_to_percentage('98') # => 98.000%
+ # number_to_percentage(100, precision: 0) # => 100%
+ # number_to_percentage(1000, delimiter: '.', separator: ',') # => 1.000,000%
+ # number_to_percentage(302.24398923423, precision: 5) # => 302.24399%
+ # number_to_percentage(1000, locale: :fr) # => 1 000,000%
+ # number_to_percentage('98a') # => 98a%
+ # number_to_percentage(100, format: '%n %') # => 100 %
def number_to_percentage(number, options = {})
return unless number
options = options.symbolize_keys
@@ -460,7 +460,7 @@ module ActiveSupport
# See <tt>number_to_human_size</tt> if you want to print a file
# size.
#
- # You can also define you own unit-quantifier names if you want
+ # You can also define your own unit-quantifier names if you want
# to use other decimal units (eg.: 1500 becomes "1.5
# kilometers", 0.150 becomes "150 milliliters", etc). You may
# define a wide range of unit quantifiers, even fractional ones
diff --git a/activesupport/lib/active_support/ordered_options.rb b/activesupport/lib/active_support/ordered_options.rb
index e03bb4ca0f..a33e2c58a9 100644
--- a/activesupport/lib/active_support/ordered_options.rb
+++ b/activesupport/lib/active_support/ordered_options.rb
@@ -41,7 +41,7 @@ module ActiveSupport
end
# +InheritableOptions+ provides a constructor to build an +OrderedOptions+
- # hash inherited from the another hash.
+ # hash inherited from another hash.
#
# Use this if you already have some hash and you want to create a new one based on it.
#
diff --git a/activesupport/lib/active_support/rescuable.rb b/activesupport/lib/active_support/rescuable.rb
index 9a038dfbca..a7eba91ac5 100644
--- a/activesupport/lib/active_support/rescuable.rb
+++ b/activesupport/lib/active_support/rescuable.rb
@@ -1,6 +1,5 @@
require 'active_support/concern'
require 'active_support/core_ext/class/attribute'
-require 'active_support/core_ext/proc'
require 'active_support/core_ext/string/inflections'
require 'active_support/core_ext/array/extract_options'
diff --git a/activesupport/lib/active_support/subscriber.rb b/activesupport/lib/active_support/subscriber.rb
index 34c6f900c1..f2966f23fc 100644
--- a/activesupport/lib/active_support/subscriber.rb
+++ b/activesupport/lib/active_support/subscriber.rb
@@ -31,18 +31,41 @@ module ActiveSupport
# Attach the subscriber to a namespace.
def attach_to(namespace, subscriber=new, notifier=ActiveSupport::Notifications)
+ @namespace = namespace
+ @subscriber = subscriber
+ @notifier = notifier
+
subscribers << subscriber
+ # Add event subscribers for all existing methods on the class.
subscriber.public_methods(false).each do |event|
- next if %w{ start finish }.include?(event.to_s)
+ add_event_subscriber(event)
+ end
+ end
- notifier.subscribe("#{event}.#{namespace}", subscriber)
+ # Adds event subscribers for all new methods added to the class.
+ def method_added(event)
+ # Only public methods are added as subscribers, and only if a notifier
+ # has been set up. This means that subscribers will only be set up for
+ # classes that call #attach_to.
+ if public_method_defined?(event) && notifier
+ add_event_subscriber(event)
end
end
def subscribers
@@subscribers ||= []
end
+
+ protected
+
+ attr_reader :subscriber, :notifier, :namespace
+
+ def add_event_subscriber(event)
+ return if %w{ start finish }.include?(event.to_s)
+
+ notifier.subscribe("#{event}.#{namespace}", subscriber)
+ end
end
def initialize
diff --git a/activesupport/lib/active_support/test_case.rb b/activesupport/lib/active_support/test_case.rb
index b124ae184d..2f27aff2bd 100644
--- a/activesupport/lib/active_support/test_case.rb
+++ b/activesupport/lib/active_support/test_case.rb
@@ -4,7 +4,6 @@ require 'active_support/testing/tagged_logging'
require 'active_support/testing/setup_and_teardown'
require 'active_support/testing/assertions'
require 'active_support/testing/deprecation'
-require 'active_support/testing/pending'
require 'active_support/testing/declarative'
require 'active_support/testing/isolation'
require 'active_support/testing/constant_lookup'
@@ -54,7 +53,6 @@ module ActiveSupport
include ActiveSupport::Testing::SetupAndTeardown
include ActiveSupport::Testing::Assertions
include ActiveSupport::Testing::Deprecation
- include ActiveSupport::Testing::Pending
extend ActiveSupport::Testing::Declarative
# test/unit backwards compatibility methods
diff --git a/activesupport/lib/active_support/testing/assertions.rb b/activesupport/lib/active_support/testing/assertions.rb
index 175f7ffe5a..76a591bc3b 100644
--- a/activesupport/lib/active_support/testing/assertions.rb
+++ b/activesupport/lib/active_support/testing/assertions.rb
@@ -92,36 +92,6 @@ module ActiveSupport
def assert_no_difference(expression, message = nil, &block)
assert_difference expression, 0, message, &block
end
-
- # Test if an expression is blank. Passes if <tt>object.blank?</tt>
- # is +true+.
- #
- # assert_blank [] # => true
- # assert_blank [[]] # => [[]] is not blank
- #
- # An error message can be specified.
- #
- # assert_blank [], 'this should be blank'
- def assert_blank(object, message=nil)
- ActiveSupport::Deprecation.warn('"assert_blank" is deprecated. Please use "assert object.blank?" instead')
- message ||= "#{object.inspect} is not blank"
- assert object.blank?, message
- end
-
- # Test if an expression is not blank. Passes if <tt>object.present?</tt>
- # is +true+.
- #
- # assert_present({ data: 'x' }) # => true
- # assert_present({}) # => {} is blank
- #
- # An error message can be specified.
- #
- # assert_present({ data: 'x' }, 'this should not be blank')
- def assert_present(object, message=nil)
- ActiveSupport::Deprecation.warn('"assert_present" is deprecated. Please use "assert object.present?" instead')
- message ||= "#{object.inspect} is blank"
- assert object.present?, message
- end
end
end
end
diff --git a/activesupport/lib/active_support/testing/declarative.rb b/activesupport/lib/active_support/testing/declarative.rb
index 508e37254a..1fa73caefa 100644
--- a/activesupport/lib/active_support/testing/declarative.rb
+++ b/activesupport/lib/active_support/testing/declarative.rb
@@ -19,9 +19,12 @@ module ActiveSupport
end
unless defined?(Spec)
- # test "verify something" do
- # ...
- # end
+ # Helper to define a test method using a String. Under the hood, it replaces
+ # spaces with underscores and defines the test method.
+ #
+ # test "verify something" do
+ # ...
+ # end
def test(name, &block)
test_name = "test_#{name.gsub(/\s+/,'_')}".to_sym
defined = instance_method(test_name) rescue false
diff --git a/activesupport/lib/active_support/testing/isolation.rb b/activesupport/lib/active_support/testing/isolation.rb
index 9c52ae7768..d5d31cecbe 100644
--- a/activesupport/lib/active_support/testing/isolation.rb
+++ b/activesupport/lib/active_support/testing/isolation.rb
@@ -3,49 +3,6 @@ require 'minitest/parallel_each'
module ActiveSupport
module Testing
- class RemoteError < StandardError
-
- attr_reader :message, :backtrace
-
- def initialize(exception)
- @message = "caught #{exception.class.name}: #{exception.message}"
- @backtrace = exception.backtrace
- end
- end
-
- class ProxyTestResult
- def initialize(calls = [])
- @calls = calls
- end
-
- def add_error(e)
- e = Test::Unit::Error.new(e.test_name, RemoteError.new(e.exception))
- @calls << [:add_error, e]
- end
-
- def __replay__(result)
- @calls.each do |name, args|
- result.send(name, *args)
- end
- end
-
- def marshal_dump
- @calls
- end
-
- def marshal_load(calls)
- initialize(calls)
- end
-
- def method_missing(name, *args)
- @calls << [name, args]
- end
-
- def info_signal
- Signal.list['INFO']
- end
- end
-
module Isolation
require 'thread'
@@ -107,19 +64,18 @@ module ActiveSupport
require "tempfile"
if ENV["ISOLATION_TEST"]
- proxy = ProxyTestResult.new
- retval = yield proxy
+ yield
File.open(ENV["ISOLATION_OUTPUT"], "w") do |file|
- file.puts [Marshal.dump([retval, proxy])].pack("m")
+ file.puts [Marshal.dump(self.dup)].pack("m")
end
exit!
else
Tempfile.open("isolation") do |tmpfile|
- ENV["ISOLATION_TEST"] = @method_name
+ ENV["ISOLATION_TEST"] = self.class.name
ENV["ISOLATION_OUTPUT"] = tmpfile.path
load_paths = $-I.map {|p| "-I\"#{File.expand_path(p)}\"" }.join(" ")
- `#{Gem.ruby} #{load_paths} #{$0} #{ORIG_ARGV.join(" ")} -t\"#{self.class}\"`
+ `#{Gem.ruby} #{load_paths} #{$0} #{ORIG_ARGV.join(" ")}`
ENV.delete("ISOLATION_TEST")
ENV.delete("ISOLATION_OUTPUT")
diff --git a/activesupport/lib/active_support/testing/pending.rb b/activesupport/lib/active_support/testing/pending.rb
deleted file mode 100644
index b04bbbbaea..0000000000
--- a/activesupport/lib/active_support/testing/pending.rb
+++ /dev/null
@@ -1,14 +0,0 @@
-require 'active_support/deprecation'
-
-module ActiveSupport
- module Testing
- module Pending # :nodoc:
- unless defined?(Spec)
- def pending(description = "", &block)
- ActiveSupport::Deprecation.warn("#pending is deprecated and will be removed in Rails 4.1, please use #skip instead.")
- skip(description.blank? ? nil : description)
- end
- end
- 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 a65148cf1f..33f2b8dc9b 100644
--- a/activesupport/lib/active_support/testing/setup_and_teardown.rb
+++ b/activesupport/lib/active_support/testing/setup_and_teardown.rb
@@ -3,6 +3,19 @@ require 'active_support/callbacks'
module ActiveSupport
module Testing
+ # Adds support for +setup+ and +teardown+ callbacks.
+ # These callbacks serve as a replacement to overwriting the
+ # <tt>#setup</tt> and <tt>#teardown</tt> methods of your TestCase.
+ #
+ # class ExampleTest < ActiveSupport::TestCase
+ # setup do
+ # # ...
+ # end
+ #
+ # teardown do
+ # # ...
+ # end
+ # end
module SetupAndTeardown
extend ActiveSupport::Concern
@@ -12,21 +25,23 @@ module ActiveSupport
end
module ClassMethods
+ # Add a callback, which runs before <tt>TestCase#setup</tt>.
def setup(*args, &block)
set_callback(:setup, :before, *args, &block)
end
+ # Add a callback, which runs after <tt>TestCase#teardown</tt>.
def teardown(*args, &block)
set_callback(:teardown, :after, *args, &block)
end
end
- def before_setup
+ def before_setup # :nodoc:
super
run_callbacks :setup
end
- def after_teardown
+ def after_teardown # :nodoc:
run_callbacks :teardown
super
end
diff --git a/activesupport/lib/active_support/time_with_zone.rb b/activesupport/lib/active_support/time_with_zone.rb
index 4a032b0ad0..95b9b8e5ae 100644
--- a/activesupport/lib/active_support/time_with_zone.rb
+++ b/activesupport/lib/active_support/time_with_zone.rb
@@ -292,7 +292,7 @@ module ActiveSupport
end
end
- %w(year mon month day mday wday yday hour min sec to_date).each do |method_name|
+ %w(year mon month day mday wday yday hour min sec usec nsec to_date).each do |method_name|
class_eval <<-EOV, __FILE__, __LINE__ + 1
def #{method_name} # def month
time.#{method_name} # time.month
@@ -300,10 +300,6 @@ module ActiveSupport
EOV
end
- def usec
- time.respond_to?(:usec) ? time.usec : 0
- end
-
def to_a
[time.sec, time.min, time.hour, time.day, time.mon, time.year, time.wday, time.yday, dst?, zone]
end
diff --git a/activesupport/test/abstract_unit.rb b/activesupport/test/abstract_unit.rb
index dd17cb64f4..65de48a7f6 100644
--- a/activesupport/test/abstract_unit.rb
+++ b/activesupport/test/abstract_unit.rb
@@ -8,7 +8,6 @@ ensure
end
require 'active_support/core_ext/kernel/reporting'
-require 'active_support/core_ext/string/encoding'
silence_warnings do
Encoding.default_internal = "UTF-8"
@@ -25,3 +24,13 @@ Thread.abort_on_exception = true
# Show backtraces for deprecated behavior for quicker cleanup.
ActiveSupport::Deprecation.debug = true
+
+# Skips the current run on Rubinius using Minitest::Assertions#skip
+def rubinius_skip(message = '')
+ skip message if RUBY_ENGINE == 'rbx'
+end
+
+# Skips the current run on JRuby using Minitest::Assertions#skip
+def jruby_skip(message = '')
+ skip message if RUBY_ENGINE == 'jruby'
+end
diff --git a/activesupport/test/autoloading_fixtures/html/some_class.rb b/activesupport/test/autoloading_fixtures/html/some_class.rb
new file mode 100644
index 0000000000..b43d15d891
--- /dev/null
+++ b/activesupport/test/autoloading_fixtures/html/some_class.rb
@@ -0,0 +1,4 @@
+module HTML
+ class SomeClass
+ end
+end
diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb
index ae6eaa4b60..16d087ab9d 100644
--- a/activesupport/test/caching_test.rb
+++ b/activesupport/test/caching_test.rb
@@ -327,8 +327,8 @@ module CacheStoreBehavior
def test_exist
@cache.write('foo', 'bar')
- assert @cache.exist?('foo')
- assert !@cache.exist?('bar')
+ assert_equal true, @cache.exist?('foo')
+ assert_equal false, @cache.exist?('bar')
end
def test_nil_exist
@@ -709,12 +709,24 @@ class FileStoreTest < ActiveSupport::TestCase
@cache.send(:read_entry, "winston", {})
assert @buffer.string.present?
end
+
+ def test_cleanup_removes_all_expired_entries
+ time = Time.now
+ @cache.write('foo', 'bar', expires_in: 10)
+ @cache.write('baz', 'qux')
+ @cache.write('quux', 'corge', expires_in: 20)
+ Time.stubs(:now).returns(time + 15)
+ @cache.cleanup
+ assert_not @cache.exist?('foo')
+ assert @cache.exist?('baz')
+ assert @cache.exist?('quux')
+ end
end
class MemoryStoreTest < ActiveSupport::TestCase
def setup
- @record_size = ActiveSupport::Cache::Entry.new("aaaaaaaaaa").size
- @cache = ActiveSupport::Cache.lookup_store(:memory_store, :expires_in => 60, :size => @record_size * 10)
+ @record_size = ActiveSupport::Cache.lookup_store(:memory_store).send(:cached_size, 1, ActiveSupport::Cache::Entry.new("aaaaaaaaaa"))
+ @cache = ActiveSupport::Cache.lookup_store(:memory_store, :expires_in => 60, :size => @record_size * 10 + 1)
end
include CacheStoreBehavior
@@ -764,6 +776,30 @@ class MemoryStoreTest < ActiveSupport::TestCase
assert !@cache.exist?(1), "no entry"
end
+ def test_prune_size_on_write_based_on_key_length
+ @cache.write(1, "aaaaaaaaaa") && sleep(0.001)
+ @cache.write(2, "bbbbbbbbbb") && sleep(0.001)
+ @cache.write(3, "cccccccccc") && sleep(0.001)
+ @cache.write(4, "dddddddddd") && sleep(0.001)
+ @cache.write(5, "eeeeeeeeee") && sleep(0.001)
+ @cache.write(6, "ffffffffff") && sleep(0.001)
+ @cache.write(7, "gggggggggg") && sleep(0.001)
+ @cache.write(8, "hhhhhhhhhh") && sleep(0.001)
+ @cache.write(9, "iiiiiiiiii") && sleep(0.001)
+ long_key = '*' * 2 * @record_size
+ @cache.write(long_key, "llllllllll")
+ assert @cache.exist?(long_key)
+ assert @cache.exist?(9)
+ assert @cache.exist?(8)
+ assert @cache.exist?(7)
+ assert @cache.exist?(6)
+ assert !@cache.exist?(5), "no entry"
+ assert !@cache.exist?(4), "no entry"
+ assert !@cache.exist?(3), "no entry"
+ assert !@cache.exist?(2), "no entry"
+ assert !@cache.exist?(1), "no entry"
+ end
+
def test_pruning_is_capped_at_a_max_time
def @cache.delete_entry (*args)
sleep(0.01)
diff --git a/activesupport/test/clean_backtrace_test.rb b/activesupport/test/clean_backtrace_test.rb
index b14950acb3..dd67a45cf6 100644
--- a/activesupport/test/clean_backtrace_test.rb
+++ b/activesupport/test/clean_backtrace_test.rb
@@ -36,6 +36,27 @@ class BacktraceCleanerSilencerTest < ActiveSupport::TestCase
end
end
+class BacktraceCleanerMultipleSilencersTest < ActiveSupport::TestCase
+ def setup
+ @bc = ActiveSupport::BacktraceCleaner.new
+ @bc.add_silencer { |line| line =~ /mongrel/ }
+ @bc.add_silencer { |line| line =~ /yolo/ }
+ end
+
+ test "backtrace should not contain lines that match the silencers" do
+ assert_equal \
+ [ "/other/class.rb" ],
+ @bc.clean([ "/mongrel/class.rb", "/other/class.rb", "/mongrel/stuff.rb", "/other/yolo.rb" ])
+ end
+
+ test "backtrace should only contain lines that match the silencers" do
+ assert_equal \
+ [ "/mongrel/class.rb", "/mongrel/stuff.rb", "/other/yolo.rb" ],
+ @bc.clean([ "/mongrel/class.rb", "/other/class.rb", "/mongrel/stuff.rb", "/other/yolo.rb" ],
+ :noise)
+ end
+end
+
class BacktraceCleanerFilterAndSilencerTest < ActiveSupport::TestCase
def setup
@bc = ActiveSupport::BacktraceCleaner.new
diff --git a/activesupport/test/concern_test.rb b/activesupport/test/concern_test.rb
index 8e2c298fc6..a74ee880b2 100644
--- a/activesupport/test/concern_test.rb
+++ b/activesupport/test/concern_test.rb
@@ -56,10 +56,6 @@ class ConcernTest < ActiveSupport::TestCase
@klass.send(:include, Baz)
assert_equal "baz", @klass.new.baz
assert @klass.included_modules.include?(ConcernTest::Baz)
-
- @klass.send(:include, Baz)
- assert_equal "baz", @klass.new.baz
- assert @klass.included_modules.include?(ConcernTest::Baz)
end
def test_class_methods_are_extended
@@ -68,12 +64,6 @@ class ConcernTest < ActiveSupport::TestCase
assert_equal ConcernTest::Baz::ClassMethods, (class << @klass; self.included_modules; end)[0]
end
- def test_instance_methods_are_included
- @klass.send(:include, Baz)
- assert_equal "baz", @klass.new.baz
- assert @klass.included_modules.include?(ConcernTest::Baz)
- end
-
def test_included_block_is_ran
@klass.send(:include, Baz)
assert_equal true, @klass.included_ran
diff --git a/activesupport/test/constantize_test_cases.rb b/activesupport/test/constantize_test_cases.rb
index 9b62295c96..bbeb710a0c 100644
--- a/activesupport/test/constantize_test_cases.rb
+++ b/activesupport/test/constantize_test_cases.rb
@@ -34,8 +34,6 @@ module ConstantizeTestCases
assert_equal Case::Dice, yield("Object::Case::Dice")
assert_equal ConstantizeTestCases, yield("ConstantizeTestCases")
assert_equal ConstantizeTestCases, yield("::ConstantizeTestCases")
- assert_equal Object, yield("")
- assert_equal Object, yield("::")
assert_raises(NameError) { yield("UnknownClass") }
assert_raises(NameError) { yield("UnknownClass::Ace") }
assert_raises(NameError) { yield("UnknownClass::Ace::Base") }
@@ -45,6 +43,8 @@ module ConstantizeTestCases
assert_raises(NameError) { yield("Ace::Base::ConstantizeTestCases") }
assert_raises(NameError) { yield("Ace::Gas::Base") }
assert_raises(NameError) { yield("Ace::Gas::ConstantizeTestCases") }
+ assert_raises(NameError) { yield("") }
+ assert_raises(NameError) { yield("::") }
end
def run_safe_constantize_tests_on
@@ -58,8 +58,8 @@ module ConstantizeTestCases
assert_equal Case::Dice, yield("Object::Case::Dice")
assert_equal ConstantizeTestCases, yield("ConstantizeTestCases")
assert_equal ConstantizeTestCases, yield("::ConstantizeTestCases")
- assert_equal Object, yield("")
- assert_equal Object, yield("::")
+ assert_nil yield("")
+ assert_nil yield("::")
assert_nil yield("UnknownClass")
assert_nil yield("UnknownClass::Ace")
assert_nil yield("UnknownClass::Ace::Base")
diff --git a/activesupport/test/core_ext/array_ext_test.rb b/activesupport/test/core_ext/array_ext_test.rb
index efa7582ab0..6cd0eb39b7 100644
--- a/activesupport/test/core_ext/array_ext_test.rb
+++ b/activesupport/test/core_ext/array_ext_test.rb
@@ -96,6 +96,10 @@ class ArrayExtToSentenceTests < ActiveSupport::TestCase
assert_equal "one two, and three", ['one', 'two', 'three'].to_sentence(options)
assert_equal({ words_connector: ' ' }, options)
end
+
+ def test_with_blank_elements
+ assert_equal ", one, , two, and three", [nil, 'one', '', 'two', 'three'].to_sentence
+ end
end
class ArrayExtToSTests < ActiveSupport::TestCase
@@ -355,36 +359,6 @@ class ArrayExtractOptionsTests < ActiveSupport::TestCase
end
end
-class ArrayUniqByTests < ActiveSupport::TestCase
- def test_uniq_by
- ActiveSupport::Deprecation.silence do
- assert_equal [1,2], [1,2,3,4].uniq_by { |i| i.odd? }
- assert_equal [1,2], [1,2,3,4].uniq_by(&:even?)
- assert_equal((-5..0).to_a, (-5..5).to_a.uniq_by{ |i| i**2 })
- end
- end
-
- def test_uniq_by!
- a = [1,2,3,4]
- ActiveSupport::Deprecation.silence do
- a.uniq_by! { |i| i.odd? }
- end
- assert_equal [1,2], a
-
- a = [1,2,3,4]
- ActiveSupport::Deprecation.silence do
- a.uniq_by! { |i| i.even? }
- end
- assert_equal [1,2], a
-
- a = (-5..5).to_a
- ActiveSupport::Deprecation.silence do
- a.uniq_by! { |i| i**2 }
- end
- assert_equal((-5..0).to_a, a)
- end
-end
-
class ArrayWrapperTests < ActiveSupport::TestCase
class FakeCollection
def to_ary
diff --git a/activesupport/test/core_ext/bigdecimal_test.rb b/activesupport/test/core_ext/bigdecimal_test.rb
index a5987044b9..b386e55d6c 100644
--- a/activesupport/test/core_ext/bigdecimal_test.rb
+++ b/activesupport/test/core_ext/bigdecimal_test.rb
@@ -1,5 +1,4 @@
require 'abstract_unit'
-require 'bigdecimal'
require 'active_support/core_ext/big_decimal'
class BigDecimalTest < ActiveSupport::TestCase
diff --git a/activesupport/test/core_ext/date_ext_test.rb b/activesupport/test/core_ext/date_ext_test.rb
index b1adf6d396..eab3aa7a6e 100644
--- a/activesupport/test/core_ext/date_ext_test.rb
+++ b/activesupport/test/core_ext/date_ext_test.rb
@@ -25,6 +25,7 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
assert_equal "February 21st, 2005", date.to_s(:long_ordinal)
assert_equal "2005-02-21", date.to_s(:db)
assert_equal "21 Feb 2005", date.to_s(:rfc822)
+ assert_equal "2005-02-21", date.to_s(:iso8601)
end
def test_readable_inspect
@@ -48,6 +49,10 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
end
end
+ def test_compare_to_time
+ assert Date.yesterday < Time.now
+ end
+
def test_to_datetime
assert_equal DateTime.civil(2005, 2, 21), Date.new(2005, 2, 21).to_datetime
assert_equal 0, Date.new(2005, 2, 21).to_datetime.offset # use UTC offset
@@ -243,6 +248,10 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
assert_equal Time.local(2005,2,21,0,0,0), Date.new(2005,2,21).beginning_of_day
end
+ def test_middle_of_day
+ assert_equal Time.local(2005,2,21,12,0,0), Date.new(2005,2,21).middle_of_day
+ end
+
def test_beginning_of_day_when_zone_is_set
zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
with_env_tz 'UTC' do
@@ -359,10 +368,3 @@ class DateExtBehaviorTest < ActiveSupport::TestCase
end
end
-class DateExtConversionsTest < ActiveSupport::TestCase
- def test_to_time_in_current_zone_is_deprecated
- assert_deprecated(/to_time_in_current_zone/) do
- Date.new(2012,6,7).to_time_in_current_zone
- end
- end
-end
diff --git a/activesupport/test/core_ext/date_time_ext_test.rb b/activesupport/test/core_ext/date_time_ext_test.rb
index 3e76b8a9b1..0a40aeb96c 100644
--- a/activesupport/test/core_ext/date_time_ext_test.rb
+++ b/activesupport/test/core_ext/date_time_ext_test.rb
@@ -18,6 +18,12 @@ class DateTimeExtCalculationsTest < ActiveSupport::TestCase
assert_equal "Mon, 21 Feb 2005 14:30:00 +0000", datetime.to_s(:rfc822)
assert_equal "February 21st, 2005 14:30", datetime.to_s(:long_ordinal)
assert_match(/^2005-02-21T14:30:00(Z|\+00:00)$/, datetime.to_s)
+
+ with_env_tz "US/Central" do
+ assert_equal "2009-02-05T14:30:05-06:00", DateTime.civil(2009, 2, 5, 14, 30, 5, Rational(-21600, 86400)).to_s(:iso8601)
+ assert_equal "2008-06-09T04:05:01-05:00", DateTime.civil(2008, 6, 9, 4, 5, 1, Rational(-18000, 86400)).to_s(:iso8601)
+ assert_equal "2009-02-05T14:30:05+00:00", DateTime.civil(2009, 2, 5, 14, 30, 5).to_s(:iso8601)
+ end
end
def test_readable_inspect
@@ -76,6 +82,10 @@ class DateTimeExtCalculationsTest < ActiveSupport::TestCase
assert_equal DateTime.civil(2005,2,4,0,0,0), DateTime.civil(2005,2,4,10,10,10).beginning_of_day
end
+ def test_middle_of_day
+ assert_equal DateTime.civil(2005,2,4,12,0,0), DateTime.civil(2005,2,4,10,10,10).middle_of_day
+ end
+
def test_end_of_day
assert_equal DateTime.civil(2005,2,4,23,59,59), DateTime.civil(2005,2,4,10,10,10).end_of_day
end
@@ -327,6 +337,16 @@ class DateTimeExtCalculationsTest < ActiveSupport::TestCase
assert_equal 946684800, DateTime.civil(1999,12,31,19,0,0,Rational(-5,24)).to_i
end
+ def test_usec
+ assert_equal 0, DateTime.civil(2000).usec
+ assert_equal 500000, DateTime.civil(2000, 1, 1, 0, 0, Rational(1,2)).usec
+ end
+
+ def test_nsec
+ assert_equal 0, DateTime.civil(2000).nsec
+ assert_equal 500000000, DateTime.civil(2000, 1, 1, 0, 0, Rational(1,2)).nsec
+ end
+
protected
def with_env_tz(new_tz = 'US/Eastern')
old_tz, ENV['TZ'] = ENV['TZ'], new_tz
diff --git a/activesupport/test/core_ext/duration_test.rb b/activesupport/test/core_ext/duration_test.rb
index 5e3987265b..ed267cf4b9 100644
--- a/activesupport/test/core_ext/duration_test.rb
+++ b/activesupport/test/core_ext/duration_test.rb
@@ -27,6 +27,7 @@ class DurationTest < ActiveSupport::TestCase
def test_equals
assert 1.day == 1.day
assert 1.day == 1.day.to_i
+ assert 1.day.to_i == 1.day
assert !(1.day == 'foo')
end
@@ -37,6 +38,8 @@ class DurationTest < ActiveSupport::TestCase
assert_equal '6 months and -2 days', (6.months - 2.days).inspect
assert_equal '10 seconds', 10.seconds.inspect
assert_equal '10 years, 2 months, and 1 day', (10.years + 2.months + 1.day).inspect
+ assert_equal '10 years, 2 months, and 1 day', (10.years + 1.month + 1.day + 1.month).inspect
+ assert_equal '10 years, 2 months, and 1 day', (1.day + 10.years + 2.months).inspect
assert_equal '7 days', 1.week.inspect
assert_equal '14 days', 1.fortnight.inspect
end
diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb
index dfcc6cd12a..2d0c56bef5 100644
--- a/activesupport/test/core_ext/hash_ext_test.rb
+++ b/activesupport/test/core_ext/hash_ext_test.rb
@@ -480,6 +480,42 @@ class HashExtTest < ActiveSupport::TestCase
assert_equal hash.delete('a'), nil
end
+ def test_indifferent_select
+ hash = ActiveSupport::HashWithIndifferentAccess.new(@strings).select {|k,v| v == 1}
+
+ assert_equal({ 'a' => 1 }, hash)
+ assert_instance_of ActiveSupport::HashWithIndifferentAccess, hash
+ end
+
+ def test_indifferent_select_returns_a_hash_when_unchanged
+ hash = ActiveSupport::HashWithIndifferentAccess.new(@strings).select {|k,v| true}
+
+ assert_instance_of ActiveSupport::HashWithIndifferentAccess, hash
+ end
+
+ def test_indifferent_select_bang
+ indifferent_strings = ActiveSupport::HashWithIndifferentAccess.new(@strings)
+ indifferent_strings.select! {|k,v| v == 1}
+
+ assert_equal({ 'a' => 1 }, indifferent_strings)
+ assert_instance_of ActiveSupport::HashWithIndifferentAccess, indifferent_strings
+ end
+
+ def test_indifferent_reject
+ hash = ActiveSupport::HashWithIndifferentAccess.new(@strings).reject {|k,v| v != 1}
+
+ assert_equal({ 'a' => 1 }, hash)
+ assert_instance_of ActiveSupport::HashWithIndifferentAccess, hash
+ end
+
+ def test_indifferent_reject_bang
+ indifferent_strings = ActiveSupport::HashWithIndifferentAccess.new(@strings)
+ indifferent_strings.reject! {|k,v| v != 1}
+
+ assert_equal({ 'a' => 1 }, indifferent_strings)
+ assert_instance_of ActiveSupport::HashWithIndifferentAccess, indifferent_strings
+ end
+
def test_indifferent_to_hash
# Should convert to a Hash with String keys.
assert_equal @strings, @mixed.with_indifferent_access.to_hash
@@ -503,6 +539,13 @@ class HashExtTest < ActiveSupport::TestCase
assert_equal [1], hash[:a]
end
+ def test_with_indifferent_access_has_no_side_effects_on_existing_hash
+ hash = {content: [{:foo => :bar, 'bar' => 'baz'}]}
+ hash.with_indifferent_access
+
+ assert_equal [:foo, "bar"], hash[:content].first.keys
+ end
+
def test_indifferent_hash_with_array_of_hashes
hash = { "urls" => { "url" => [ { "address" => "1" }, { "address" => "2" } ] }}.with_indifferent_access
assert_equal "1", hash[:urls][:url].first[:address]
@@ -664,12 +707,6 @@ class HashExtTest < ActiveSupport::TestCase
assert_equal expected, merged
end
- def test_diff
- assert_deprecated do
- assert_equal({ :a => 2 }, { :a => 2, :b => 5 }.diff({ :a => 1, :b => 5 }))
- end
- end
-
def test_slice
original = { :a => 'x', :b => 'y', :c => 10 }
expected = { :a => 'x', :b => 'y' }
diff --git a/activesupport/test/core_ext/module_test.rb b/activesupport/test/core_ext/module_test.rb
index 8872611fb1..283b13ff8b 100644
--- a/activesupport/test/core_ext/module_test.rb
+++ b/activesupport/test/core_ext/module_test.rb
@@ -66,6 +66,23 @@ Tester = Struct.new(:client) do
delegate :name, :to => :client, :prefix => false
end
+Product = Struct.new(:name) do
+ delegate :name, :to => :manufacturer, :prefix => true
+ delegate :name, :to => :type, :prefix => true
+
+ def manufacturer
+ @manufacturer ||= begin
+ nil.unknown_method
+ end
+ end
+
+ def type
+ @type ||= begin
+ nil.type_name
+ end
+ end
+end
+
class ParameterSet
delegate :[], :[]=, :to => :@params
@@ -207,7 +224,7 @@ class ModuleTest < ActiveSupport::TestCase
def test_delegation_without_allow_nil_and_nil_value
david = Someone.new("David")
- assert_raise(RuntimeError) { david.street }
+ assert_raise(Module::DelegationError) { david.street }
end
def test_delegation_to_method_that_exists_on_nil
@@ -264,6 +281,16 @@ class ModuleTest < ActiveSupport::TestCase
assert_equal [3], se.ints
end
+ def test_delegation_doesnt_mask_nested_no_method_error_on_nil_receiver
+ product = Product.new('Widget')
+
+ # Nested NoMethodError is a different name from the delegation
+ assert_raise(NoMethodError) { product.manufacturer_name }
+
+ # Nested NoMethodError is the same name as the delegation
+ assert_raise(NoMethodError) { product.type_name }
+ end
+
def test_parent
assert_equal Yz::Zy, Yz::Zy::Cd.parent
assert_equal Yz, Yz::Zy.parent
@@ -278,12 +305,6 @@ class ModuleTest < ActiveSupport::TestCase
def test_local_constants
assert_equal %w(Constant1 Constant3), Ab.local_constants.sort.map(&:to_s)
end
-
- def test_local_constant_names
- ActiveSupport::Deprecation.silence do
- assert_equal %w(Constant1 Constant3), Ab.local_constant_names.sort.map(&:to_s)
- end
- end
end
module BarMethodAliaser
diff --git a/activesupport/test/core_ext/numeric_ext_test.rb b/activesupport/test/core_ext/numeric_ext_test.rb
index f22ae3ccac..1da72eb17d 100644
--- a/activesupport/test/core_ext/numeric_ext_test.rb
+++ b/activesupport/test/core_ext/numeric_ext_test.rb
@@ -77,7 +77,7 @@ class NumericExtTimeAndDateTimeTest < ActiveSupport::TestCase
assert_equal @dtnow.advance(:days => 1).advance(:months => 2), @dtnow + 1.day + 2.months
end
- def test_duration_after_convertion_is_no_longer_accurate
+ def test_duration_after_conversion_is_no_longer_accurate
assert_equal 30.days.to_i.since(@now), 1.month.to_i.since(@now)
assert_equal 365.25.days.to_f.since(@now), 1.year.to_f.since(@now)
assert_equal 30.days.to_i.since(@dtnow), 1.month.to_i.since(@dtnow)
diff --git a/activesupport/test/core_ext/proc_test.rb b/activesupport/test/core_ext/proc_test.rb
deleted file mode 100644
index c4d5592196..0000000000
--- a/activesupport/test/core_ext/proc_test.rb
+++ /dev/null
@@ -1,14 +0,0 @@
-require 'abstract_unit'
-require 'active_support/core_ext/proc'
-
-class ProcTests < ActiveSupport::TestCase
- def test_bind_returns_method_with_changed_self
- assert_deprecated do
- block = Proc.new { self }
- assert_equal self, block.call
- bound_block = block.bind("hello")
- assert_not_equal block, bound_block
- assert_equal "hello", bound_block.call
- end
- end
-end
diff --git a/activesupport/test/core_ext/range_ext_test.rb b/activesupport/test/core_ext/range_ext_test.rb
index 3e2355ae23..854b0a38bd 100644
--- a/activesupport/test/core_ext/range_ext_test.rb
+++ b/activesupport/test/core_ext/range_ext_test.rb
@@ -54,7 +54,7 @@ class RangeTest < ActiveSupport::TestCase
assert((1...10) === (1...10))
end
- def test_should_compare_other_with_exlusive_end
+ def test_should_compare_other_with_exclusive_end
assert((1..10) === (1...10))
end
@@ -90,4 +90,26 @@ class RangeTest < ActiveSupport::TestCase
time_range_2 = Time.utc(2005, 12, 10, 17, 31)..Time.utc(2005, 12, 10, 18, 00)
assert !time_range_1.overlaps?(time_range_2)
end
+
+ def test_each_on_time_with_zone
+ twz = ActiveSupport::TimeWithZone.new(nil, ActiveSupport::TimeZone['Eastern Time (US & Canada)'] , Time.utc(2006,11,28,10,30))
+ assert_raises TypeError do
+ ((twz - 1.hour)..twz).each {}
+ end
+ end
+
+ def test_step_on_time_with_zone
+ twz = ActiveSupport::TimeWithZone.new(nil, ActiveSupport::TimeZone['Eastern Time (US & Canada)'] , Time.utc(2006,11,28,10,30))
+ assert_raises TypeError do
+ ((twz - 1.hour)..twz).step(1) {}
+ end
+ end
+
+ def test_include_on_time_with_zone
+ twz = ActiveSupport::TimeWithZone.new(nil, ActiveSupport::TimeZone['Eastern Time (US & Canada)'] , Time.utc(2006,11,28,10,30))
+ assert_raises TypeError do
+ ((twz - 1.hour)..twz).include?(twz)
+ end
+ end
+
end
diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb
index 8f0ebc13ea..3cb66d4eec 100644
--- a/activesupport/test/core_ext/string_ext_test.rb
+++ b/activesupport/test/core_ext/string_ext_test.rb
@@ -11,13 +11,6 @@ require 'active_support/core_ext/string/strip'
require 'active_support/core_ext/string/output_safety'
require 'active_support/core_ext/string/indent'
-module Ace
- module Base
- class Case
- end
- end
-end
-
class StringInflectionsTest < ActiveSupport::TestCase
include InflectorTestCases
include ConstantizeTestCases
@@ -277,6 +270,11 @@ class StringInflectionsTest < ActiveSupport::TestCase
def test_truncate_should_not_be_html_safe
assert !"Hello World!".truncate(12).html_safe?
end
+
+ def test_remove
+ assert_equal "Summer", "Fast Summer".remove(/Fast /)
+ assert_equal "Summer", "Fast Summer".remove!(/Fast /)
+ end
def test_constantize
run_constantize_tests_on do |string|
@@ -651,12 +649,6 @@ class OutputSafetyTest < ActiveSupport::TestCase
assert_equal 'foo'.to_yaml, 'foo'.html_safe.to_yaml(:foo => 1)
end
- test 'knows whether it is encoding aware' do
- assert_deprecated do
- assert 'ruby'.encoding_aware?
- end
- end
-
test "call to_param returns a normal string" do
string = @string.html_safe
assert string.html_safe?
diff --git a/activesupport/test/core_ext/thread_test.rb b/activesupport/test/core_ext/thread_test.rb
index 230c1203ad..54d2dcd8dd 100644
--- a/activesupport/test/core_ext/thread_test.rb
+++ b/activesupport/test/core_ext/thread_test.rb
@@ -63,7 +63,18 @@ class ThreadExt < ActiveSupport::TestCase
end
end
+ def test_thread_variable_frozen_after_set
+ t = Thread.new { }.join
+ t.thread_variable_set :foo, "bar"
+ t.freeze
+ assert_raises(RuntimeError) do
+ t.thread_variable_set(:baz, "qux")
+ end
+ end
+
def test_thread_variable_security
+ rubinius_skip "$SAFE is not supported on Rubinius."
+
t = Thread.new { sleep }
assert_raises(SecurityError) do
diff --git a/activesupport/test/core_ext/time_ext_test.rb b/activesupport/test/core_ext/time_ext_test.rb
index 4e53aff00b..41a1df084e 100644
--- a/activesupport/test/core_ext/time_ext_test.rb
+++ b/activesupport/test/core_ext/time_ext_test.rb
@@ -117,6 +117,18 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
end
end
+ def test_middle_of_day
+ assert_equal Time.local(2005,2,4,12,0,0), Time.local(2005,2,4,10,10,10).middle_of_day
+ with_env_tz 'US/Eastern' do
+ assert_equal Time.local(2006,4,2,12,0,0), Time.local(2006,4,2,10,10,10).middle_of_day, 'start DST'
+ assert_equal Time.local(2006,10,29,12,0,0), Time.local(2006,10,29,10,10,10).middle_of_day, 'ends DST'
+ end
+ with_env_tz 'NZ' do
+ assert_equal Time.local(2006,3,19,12,0,0), Time.local(2006,3,19,10,10,10).middle_of_day, 'ends DST'
+ assert_equal Time.local(2006,10,1,12,0,0), Time.local(2006,10,1,10,10,10).middle_of_day, 'start DST'
+ end
+ end
+
def test_beginning_of_hour
assert_equal Time.local(2005,2,4,19,0,0), Time.local(2005,2,4,19,30,10).beginning_of_hour
end
@@ -509,6 +521,9 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
with_env_tz "US/Central" do
assert_equal "Thu, 05 Feb 2009 14:30:05 -0600", Time.local(2009, 2, 5, 14, 30, 5).to_s(:rfc822)
assert_equal "Mon, 09 Jun 2008 04:05:01 -0500", Time.local(2008, 6, 9, 4, 5, 1).to_s(:rfc822)
+ assert_equal "2009-02-05T14:30:05-06:00", Time.local(2009, 2, 5, 14, 30, 5).to_s(:iso8601)
+ assert_equal "2008-06-09T04:05:01-05:00", Time.local(2008, 6, 9, 4, 5, 1).to_s(:iso8601)
+ assert_equal "2009-02-05T14:30:05Z", Time.utc(2009, 2, 5, 14, 30, 5).to_s(:iso8601)
end
end
@@ -578,58 +593,6 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
assert_equal 29, Time.days_in_month(2)
end
- def test_time_with_datetime_fallback
- ActiveSupport::Deprecation.silence do
- assert_equal Time.time_with_datetime_fallback(:utc, 2005, 2, 21, 17, 44, 30), Time.utc(2005, 2, 21, 17, 44, 30)
- assert_equal Time.time_with_datetime_fallback(:local, 2005, 2, 21, 17, 44, 30), Time.local(2005, 2, 21, 17, 44, 30)
- assert_equal Time.time_with_datetime_fallback(:utc, 2039, 2, 21, 17, 44, 30), DateTime.civil(2039, 2, 21, 17, 44, 30, 0)
- assert_equal Time.time_with_datetime_fallback(:local, 2039, 2, 21, 17, 44, 30), DateTime.civil_from_format(:local, 2039, 2, 21, 17, 44, 30)
- assert_equal Time.time_with_datetime_fallback(:utc, 1900, 2, 21, 17, 44, 30), DateTime.civil(1900, 2, 21, 17, 44, 30, 0)
- assert_equal Time.time_with_datetime_fallback(:utc, 2005), Time.utc(2005)
- assert_equal Time.time_with_datetime_fallback(:utc, 2039), DateTime.civil(2039, 1, 1, 0, 0, 0, 0)
- assert_equal Time.time_with_datetime_fallback(:utc, 2005, 2, 21, 17, 44, 30, 1), Time.utc(2005, 2, 21, 17, 44, 30, 1) #with usec
- # This won't overflow on 64bit linux
- unless time_is_64bits?
- assert_equal Time.time_with_datetime_fallback(:local, 1900, 2, 21, 17, 44, 30), DateTime.civil_from_format(:local, 1900, 2, 21, 17, 44, 30)
- assert_equal Time.time_with_datetime_fallback(:utc, 2039, 2, 21, 17, 44, 30, 1),
- DateTime.civil(2039, 2, 21, 17, 44, 30, 0, 0)
- assert_equal ::Date::ITALY, Time.time_with_datetime_fallback(:utc, 2039, 2, 21, 17, 44, 30, 1).start # use Ruby's default start value
- end
- silence_warnings do
- 0.upto(138) do |year|
- [:utc, :local].each do |format|
- assert_equal year, Time.time_with_datetime_fallback(format, year).year
- end
- end
- end
- end
- end
-
- def test_utc_time
- ActiveSupport::Deprecation.silence do
- assert_equal Time.utc_time(2005, 2, 21, 17, 44, 30), Time.utc(2005, 2, 21, 17, 44, 30)
- assert_equal Time.utc_time(2039, 2, 21, 17, 44, 30), DateTime.civil(2039, 2, 21, 17, 44, 30, 0)
- assert_equal Time.utc_time(1901, 2, 21, 17, 44, 30), DateTime.civil(1901, 2, 21, 17, 44, 30, 0)
- end
- end
-
- def test_local_time
- ActiveSupport::Deprecation.silence do
- assert_equal Time.local_time(2005, 2, 21, 17, 44, 30), Time.local(2005, 2, 21, 17, 44, 30)
- assert_equal Time.local_time(2039, 2, 21, 17, 44, 30), DateTime.civil_from_format(:local, 2039, 2, 21, 17, 44, 30)
-
- unless time_is_64bits?
- assert_equal Time.local_time(1901, 2, 21, 17, 44, 30), DateTime.civil_from_format(:local, 1901, 2, 21, 17, 44, 30)
- end
- end
- end
-
- def test_time_with_datetime_fallback_deprecations
- assert_deprecated(/time_with_datetime_fallback/) { Time.time_with_datetime_fallback(:utc, 2012, 6, 7) }
- assert_deprecated(/utc_time/) { Time.utc_time(2012, 6, 7) }
- assert_deprecated(/local_time/) { Time.local_time(2012, 6, 7) }
- end
-
def test_last_month_on_31st
assert_equal Time.local(2004, 2, 29), Time.local(2004, 3, 31).last_month
end
@@ -741,6 +704,82 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
assert_equal(-1, Time.utc(2000) <=> ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 0, 0, 1), ActiveSupport::TimeZone['UTC'] ))
end
+ def test_at_with_datetime
+ assert_equal Time.utc(2000, 1, 1, 0, 0, 0), Time.at(DateTime.civil(2000, 1, 1, 0, 0, 0))
+
+ # Only test this if the underlying Time.at raises a TypeError
+ begin
+ Time.at_without_coercion(Time.now, 0)
+ rescue TypeError
+ assert_raise(TypeError) { assert_equal(Time.utc(2000, 1, 1, 0, 0, 0), Time.at(DateTime.civil(2000, 1, 1, 0, 0, 0), 0)) }
+ end
+ end
+
+ def test_at_with_datetime_returns_local_time
+ with_env_tz 'US/Eastern' do
+ dt = DateTime.civil(2000, 1, 1, 0, 0, 0, '+0')
+ assert_equal Time.local(1999, 12, 31, 19, 0, 0), Time.at(dt)
+ assert_equal 'EST', Time.at(dt).zone
+ assert_equal(-18000, Time.at(dt).utc_offset)
+
+ # Daylight savings
+ dt = DateTime.civil(2000, 7, 1, 1, 0, 0, '+1')
+ assert_equal Time.local(2000, 6, 30, 20, 0, 0), Time.at(dt)
+ assert_equal 'EDT', Time.at(dt).zone
+ assert_equal(-14400, Time.at(dt).utc_offset)
+ end
+ end
+
+ def test_at_with_time_with_zone
+ assert_equal Time.utc(2000, 1, 1, 0, 0, 0), Time.at(ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone['UTC']))
+
+ # Only test this if the underlying Time.at raises a TypeError
+ begin
+ Time.at_without_coercion(Time.now, 0)
+ rescue TypeError
+ assert_raise(TypeError) { assert_equal(Time.utc(2000, 1, 1, 0, 0, 0), Time.at(ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone['UTC']), 0)) }
+ end
+ end
+
+ def test_at_with_time_with_zone_returns_local_time
+ with_env_tz 'US/Eastern' do
+ twz = ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone['London'])
+ assert_equal Time.local(1999, 12, 31, 19, 0, 0), Time.at(twz)
+ assert_equal 'EST', Time.at(twz).zone
+ assert_equal(-18000, Time.at(twz).utc_offset)
+
+ # Daylight savings
+ twz = ActiveSupport::TimeWithZone.new(Time.utc(2000, 7, 1, 0, 0, 0), ActiveSupport::TimeZone['London'])
+ assert_equal Time.local(2000, 6, 30, 20, 0, 0), Time.at(twz)
+ assert_equal 'EDT', Time.at(twz).zone
+ assert_equal(-14400, Time.at(twz).utc_offset)
+ end
+ end
+
+ def test_at_with_time_microsecond_precision
+ assert_equal Time.at(Time.utc(2000, 1, 1, 0, 0, 0, 111)).to_f, Time.utc(2000, 1, 1, 0, 0, 0, 111).to_f
+ end
+
+ def test_at_with_utc_time
+ with_env_tz 'US/Eastern' do
+ assert_equal Time.utc(2000), Time.at(Time.utc(2000))
+ assert_equal 'UTC', Time.at(Time.utc(2000)).zone
+ assert_equal(0, Time.at(Time.utc(2000)).utc_offset)
+ end
+ end
+
+ def test_at_with_local_time
+ with_env_tz 'US/Eastern' do
+ assert_equal Time.local(2000), Time.at(Time.local(2000))
+ assert_equal 'EST', Time.at(Time.local(2000)).zone
+ assert_equal(-18000, Time.at(Time.local(2000)).utc_offset)
+
+ assert_equal Time.local(2000, 7, 1), Time.at(Time.local(2000, 7, 1))
+ assert_equal 'EDT', Time.at(Time.local(2000, 7, 1)).zone
+ assert_equal(-14400, Time.at(Time.local(2000, 7, 1)).utc_offset)
+ end
+ end
+
def test_eql?
assert_equal true, Time.utc(2000).eql?( ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone['UTC']) )
assert_equal true, Time.utc(2000).eql?( ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["Hawaii"]) )
@@ -810,9 +849,6 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ')
end
- def time_is_64bits?
- Time.time_with_datetime_fallback(:utc, 2039, 2, 21, 17, 44, 30, 1).is_a?(Time)
- end
end
class TimeExtMarshalingTest < ActiveSupport::TestCase
diff --git a/activesupport/test/core_ext/time_with_zone_test.rb b/activesupport/test/core_ext/time_with_zone_test.rb
index 3ce3297874..5494824a40 100644
--- a/activesupport/test/core_ext/time_with_zone_test.rb
+++ b/activesupport/test/core_ext/time_with_zone_test.rb
@@ -80,6 +80,11 @@ class TimeWithZoneTest < ActiveSupport::TestCase
ActiveSupport.use_standard_json_time_format = old
end
+ def test_to_json_when_wrapping_a_date_time
+ twz = ActiveSupport::TimeWithZone.new(DateTime.civil(2000), @time_zone)
+ assert_equal '"1999-12-31T19:00:00.000-05:00"', ActiveSupport::JSON.encode(twz)
+ end
+
def test_nsec
local = Time.local(2011,6,7,23,59,59,Rational(999999999, 1000))
with_zone = ActiveSupport::TimeWithZone.new(nil, ActiveSupport::TimeZone["Hawaii"], local)
@@ -445,6 +450,16 @@ class TimeWithZoneTest < ActiveSupport::TestCase
assert_equal 0, twz.usec
end
+ def test_usec_returns_sec_fraction_when_datetime_is_wrapped
+ twz = ActiveSupport::TimeWithZone.new(DateTime.civil(2000, 1, 1, 0, 0, Rational(1,2)), @time_zone)
+ assert_equal 500000, twz.usec
+ end
+
+ def test_nsec_returns_sec_fraction_when_datetime_is_wrapped
+ twz = ActiveSupport::TimeWithZone.new(DateTime.civil(2000, 1, 1, 0, 0, Rational(1,2)), @time_zone)
+ assert_equal 500000000, twz.nsec
+ end
+
def test_utc_to_local_conversion_saves_period_in_instance_variable
assert_nil @twz.instance_variable_get('@period')
@twz.time
@@ -982,6 +997,15 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < ActiveSupport::TestCase
Time.zone = nil
end
+ def test_time_in_time_zone_doesnt_affect_receiver
+ with_env_tz 'Europe/London' do
+ time = Time.local(2000, 7, 1)
+ time_with_zone = time.in_time_zone('Eastern Time (US & Canada)')
+ assert_equal Time.utc(2000, 6, 30, 23, 0, 0), time_with_zone
+ assert_not time.utc?, 'time expected to be local, but is UTC'
+ end
+ end
+
protected
def with_env_tz(new_tz = 'US/Eastern')
old_tz, ENV['TZ'] = ENV['TZ'], new_tz
diff --git a/activesupport/test/dependencies/raises_exception_without_blame_file.rb b/activesupport/test/dependencies/raises_exception_without_blame_file.rb
new file mode 100644
index 0000000000..4b2da6ff30
--- /dev/null
+++ b/activesupport/test/dependencies/raises_exception_without_blame_file.rb
@@ -0,0 +1,5 @@
+exception = Exception.new('I am not blamable!')
+class << exception
+ undef_method(:blame_file!)
+end
+raise exception
diff --git a/activesupport/test/dependencies_test.rb b/activesupport/test/dependencies_test.rb
index b8cbbca601..2392b71960 100644
--- a/activesupport/test/dependencies_test.rb
+++ b/activesupport/test/dependencies_test.rb
@@ -87,6 +87,14 @@ class DependenciesTest < ActiveSupport::TestCase
end
end
+ def test_dependency_which_raises_doesnt_blindly_call_blame_file!
+ with_loading do
+ filename = 'dependencies/raises_exception_without_blame_file'
+
+ assert_raises(Exception) { require_dependency filename }
+ end
+ end
+
def test_warnings_should_be_enabled_on_first_load
with_loading 'dependencies' do
old_warnings, ActiveSupport::Dependencies.warnings_on_first_load = ActiveSupport::Dependencies.warnings_on_first_load, true
@@ -650,6 +658,14 @@ class DependenciesTest < ActiveSupport::TestCase
Object.class_eval { remove_const :E }
end
+ def test_constants_in_capitalized_nesting_marked_as_autoloaded
+ with_autoloading_fixtures do
+ ActiveSupport::Dependencies.load_missing_constant(HTML, "SomeClass")
+
+ assert ActiveSupport::Dependencies.autoloaded?("HTML::SomeClass")
+ end
+ end
+
def test_unloadable
with_autoloading_fixtures do
Object.const_set :M, Module.new
diff --git a/activesupport/test/deprecation/basic_object_test.rb b/activesupport/test/deprecation/basic_object_test.rb
deleted file mode 100644
index 4b5bed9eb1..0000000000
--- a/activesupport/test/deprecation/basic_object_test.rb
+++ /dev/null
@@ -1,12 +0,0 @@
-require 'abstract_unit'
-require 'active_support/deprecation'
-require 'active_support/basic_object'
-
-
-class BasicObjectTest < ActiveSupport::TestCase
- test 'BasicObject warns about deprecation when inherited from' do
- warn = 'ActiveSupport::BasicObject is deprecated! Use ActiveSupport::ProxyObject instead.'
- ActiveSupport::Deprecation.expects(:warn).with(warn).once
- Class.new(ActiveSupport::BasicObject)
- end
-end \ No newline at end of file
diff --git a/activesupport/test/deprecation/buffered_logger_test.rb b/activesupport/test/deprecation/buffered_logger_test.rb
deleted file mode 100644
index bf11a4732c..0000000000
--- a/activesupport/test/deprecation/buffered_logger_test.rb
+++ /dev/null
@@ -1,22 +0,0 @@
-require 'abstract_unit'
-require 'active_support/buffered_logger'
-
-class BufferedLoggerTest < ActiveSupport::TestCase
-
- def test_can_be_subclassed
- warn = 'ActiveSupport::BufferedLogger is deprecated! Use ActiveSupport::Logger instead.'
-
- ActiveSupport::Deprecation.expects(:warn).with(warn).once
-
- Class.new(ActiveSupport::BufferedLogger)
- end
-
- def test_issues_deprecation_when_instantiated
- warn = 'ActiveSupport::BufferedLogger is deprecated! Use ActiveSupport::Logger instead.'
-
- ActiveSupport::Deprecation.expects(:warn).with(warn).once
-
- ActiveSupport::BufferedLogger.new(STDOUT)
- end
-
-end
diff --git a/activesupport/test/deprecation_test.rb b/activesupport/test/deprecation_test.rb
index 9616e42f44..9674851b9d 100644
--- a/activesupport/test/deprecation_test.rb
+++ b/activesupport/test/deprecation_test.rb
@@ -98,6 +98,22 @@ class DeprecationTest < ActiveSupport::TestCase
assert_match(/foo=nil/, @b)
end
+ def test_raise_behaviour
+ ActiveSupport::Deprecation.behavior = :raise
+
+ message = 'Revise this deprecated stuff now!'
+ callstack = %w(foo bar baz)
+
+ begin
+ ActiveSupport::Deprecation.behavior.first.call(message, callstack)
+ rescue ActiveSupport::DeprecationException => e
+ assert_equal message, e.message
+ assert_equal callstack, e.backtrace
+ else
+ flunk 'the :raise deprecation behaviour should raise the expected exception'
+ end
+ end
+
def test_default_stderr_behavior
ActiveSupport::Deprecation.behavior = :stderr
behavior = ActiveSupport::Deprecation.behavior.first
diff --git a/activesupport/test/inflector_test.rb b/activesupport/test/inflector_test.rb
index 22cb61ffd6..32739d45a9 100644
--- a/activesupport/test/inflector_test.rb
+++ b/activesupport/test/inflector_test.rb
@@ -76,9 +76,10 @@ class InflectorTest < ActiveSupport::TestCase
ActiveSupport::Inflector.inflections.uncountable "series" # Return to normal
end
- MixtureToTitleCase.each do |before, titleized|
- define_method "test_titleize_#{before}" do
- assert_equal(titleized, ActiveSupport::Inflector.titleize(before))
+ MixtureToTitleCase.each_with_index do |(before, titleized), index|
+ define_method "test_titleize_mixture_to_title_case_#{index}" do
+ assert_equal(titleized, ActiveSupport::Inflector.titleize(before), "mixture \
+ to TitleCase failed for #{before}")
end
end
@@ -229,25 +230,35 @@ class InflectorTest < ActiveSupport::TestCase
end
end
+# FIXME: get following tests to pass on jruby, currently skipped
+#
+# Currently this fails because ActiveSupport::Multibyte::Unicode#tidy_bytes
+# required a specific Encoding::Converter(UTF-8 to UTF8-MAC) which unavailable on JRuby
+# causing our tests to error out.
+# related bug http://jira.codehaus.org/browse/JRUBY-7194
def test_parameterize
+ jruby_skip "UTF-8 to UTF8-MAC Converter is unavailable"
StringToParameterized.each do |some_string, parameterized_string|
assert_equal(parameterized_string, ActiveSupport::Inflector.parameterize(some_string))
end
end
def test_parameterize_and_normalize
+ jruby_skip "UTF-8 to UTF8-MAC Converter is unavailable"
StringToParameterizedAndNormalized.each do |some_string, parameterized_string|
assert_equal(parameterized_string, ActiveSupport::Inflector.parameterize(some_string))
end
end
def test_parameterize_with_custom_separator
+ jruby_skip "UTF-8 to UTF8-MAC Converter is unavailable"
StringToParameterizeWithUnderscore.each do |some_string, parameterized_string|
assert_equal(parameterized_string, ActiveSupport::Inflector.parameterize(some_string, '_'))
end
end
def test_parameterize_with_multi_character_separator
+ jruby_skip "UTF-8 to UTF8-MAC Converter is unavailable"
StringToParameterized.each do |some_string, parameterized_string|
assert_equal(parameterized_string.gsub('-', '__sep__'), ActiveSupport::Inflector.parameterize(some_string, '__sep__'))
end
@@ -419,33 +430,36 @@ class InflectorTest < ActiveSupport::TestCase
end
end
- Irregularities.each do |irregularity|
- singular, plural = *irregularity
- ActiveSupport::Inflector.inflections do |inflect|
- define_method("test_irregularity_between_#{singular}_and_#{plural}") do
- inflect.irregular(singular, plural)
- assert_equal singular, ActiveSupport::Inflector.singularize(plural)
- assert_equal plural, ActiveSupport::Inflector.pluralize(singular)
+ Irregularities.each do |singular, plural|
+ define_method("test_irregularity_between_#{singular}_and_#{plural}") do
+ with_dup do
+ ActiveSupport::Inflector.inflections do |inflect|
+ inflect.irregular(singular, plural)
+ assert_equal singular, ActiveSupport::Inflector.singularize(plural)
+ assert_equal plural, ActiveSupport::Inflector.pluralize(singular)
+ end
end
end
end
- Irregularities.each do |irregularity|
- singular, plural = *irregularity
- ActiveSupport::Inflector.inflections do |inflect|
- define_method("test_pluralize_of_irregularity_#{plural}_should_be_the_same") do
- inflect.irregular(singular, plural)
- assert_equal plural, ActiveSupport::Inflector.pluralize(plural)
+ Irregularities.each do |singular, plural|
+ define_method("test_pluralize_of_irregularity_#{plural}_should_be_the_same") do
+ with_dup do
+ ActiveSupport::Inflector.inflections do |inflect|
+ inflect.irregular(singular, plural)
+ assert_equal plural, ActiveSupport::Inflector.pluralize(plural)
+ end
end
end
end
- Irregularities.each do |irregularity|
- singular, plural = *irregularity
- ActiveSupport::Inflector.inflections do |inflect|
- define_method("test_singularize_of_irregularity_#{singular}_should_be_the_same") do
- inflect.irregular(singular, plural)
- assert_equal singular, ActiveSupport::Inflector.singularize(singular)
+ Irregularities.each do |singular, plural|
+ define_method("test_singularize_of_irregularity_#{singular}_should_be_the_same") do
+ with_dup do
+ ActiveSupport::Inflector.inflections do |inflect|
+ inflect.irregular(singular, plural)
+ assert_equal singular, ActiveSupport::Inflector.singularize(singular)
+ end
end
end
end
diff --git a/activesupport/test/inflector_test_cases.rb b/activesupport/test/inflector_test_cases.rb
index 7704300938..cc36d62138 100644
--- a/activesupport/test/inflector_test_cases.rb
+++ b/activesupport/test/inflector_test_cases.rb
@@ -105,7 +105,6 @@ module InflectorTestCases
"prize" => "prizes",
"edge" => "edges",
- "cow" => "kine",
"database" => "databases",
# regression tests against improper inflection regexes
diff --git a/activesupport/test/json/decoding_test.rb b/activesupport/test/json/decoding_test.rb
index 34ed866848..e9780b36e4 100644
--- a/activesupport/test/json/decoding_test.rb
+++ b/activesupport/test/json/decoding_test.rb
@@ -4,6 +4,12 @@ require 'active_support/json'
require 'active_support/time'
class TestJSONDecoding < ActiveSupport::TestCase
+ class Foo
+ def self.json_create(object)
+ "Foo"
+ end
+ end
+
TESTS = {
%q({"returnTo":{"\/categories":"\/"}}) => {"returnTo" => {"/categories" => "/"}},
%q({"return\\"To\\":":{"\/categories":"\/"}}) => {"return\"To\":" => {"/categories" => "/"}},
@@ -52,15 +58,26 @@ class TestJSONDecoding < ActiveSupport::TestCase
# tests escaping of "\n" char with Yaml backend
%q({"a":"\n"}) => {"a"=>"\n"},
%q({"a":"\u000a"}) => {"a"=>"\n"},
- %q({"a":"Line1\u000aLine2"}) => {"a"=>"Line1\nLine2"}
+ %q({"a":"Line1\u000aLine2"}) => {"a"=>"Line1\nLine2"},
+ # prevent json unmarshalling
+ %q({"json_class":"TestJSONDecoding::Foo"}) => {"json_class"=>"TestJSONDecoding::Foo"},
+ # json "fragments" - these are invalid JSON, but ActionPack relies on this
+ %q("a string") => "a string",
+ %q(1.1) => 1.1,
+ %q(1) => 1,
+ %q(-1) => -1,
+ %q(true) => true,
+ %q(false) => false,
+ %q(null) => nil
}
- TESTS.each do |json, expected|
- test "json decodes #{json}" do
+ TESTS.each_with_index do |(json, expected), index|
+ test "json decodes #{index}" do
prev = ActiveSupport.parse_json_times
ActiveSupport.parse_json_times = true
silence_warnings do
- assert_equal expected, ActiveSupport::JSON.decode(json)
+ assert_equal expected, ActiveSupport::JSON.decode(json), "JSON decoding \
+ failed for #{json}"
end
ActiveSupport.parse_json_times = prev
end
@@ -75,7 +92,16 @@ class TestJSONDecoding < ActiveSupport::TestCase
end
def test_failed_json_decoding
+ assert_raise(ActiveSupport::JSON.parse_error) { ActiveSupport::JSON.decode(%(undefined)) }
+ assert_raise(ActiveSupport::JSON.parse_error) { ActiveSupport::JSON.decode(%({a: 1})) }
assert_raise(ActiveSupport::JSON.parse_error) { ActiveSupport::JSON.decode(%({: 1})) }
+ assert_raise(ActiveSupport::JSON.parse_error) { ActiveSupport::JSON.decode(%()) }
+ end
+
+ def test_cannot_force_json_unmarshalling
+ encodeded = %q({"json_class":"TestJSONDecoding::Foo"})
+ decodeded = {"json_class"=>"TestJSONDecoding::Foo"}
+ assert_equal decodeded, ActiveSupport::JSON.decode(encodeded, create_additions: true)
end
end
diff --git a/activesupport/test/json/encoding_test.rb b/activesupport/test/json/encoding_test.rb
index 106a7fb522..ed1326705c 100644
--- a/activesupport/test/json/encoding_test.rb
+++ b/activesupport/test/json/encoding_test.rb
@@ -96,13 +96,6 @@ class TestJSONEncoding < ActiveSupport::TestCase
end
end
- def test_json_variable
- assert_deprecated do
- assert_equal ActiveSupport::JSON::Variable.new('foo'), 'foo'
- assert_equal ActiveSupport::JSON::Variable.new('alert("foo")'), 'alert("foo")'
- end
- end
-
def test_hash_encoding
assert_equal %({\"a\":\"b\"}), ActiveSupport::JSON.encode(:a => :b)
assert_equal %({\"a\":1}), ActiveSupport::JSON.encode('a' => 1)
@@ -195,7 +188,7 @@ class TestJSONEncoding < ActiveSupport::TestCase
assert_nothing_raised do
hash = {
"CHI" => {
- :dislay_name => "chicago",
+ :display_name => "chicago",
:latitude => 123.234
}
}
diff --git a/activesupport/test/load_paths_test.rb b/activesupport/test/load_paths_test.rb
index 979e25bdf3..ac617a9fd8 100644
--- a/activesupport/test/load_paths_test.rb
+++ b/activesupport/test/load_paths_test.rb
@@ -10,7 +10,7 @@ class LoadPathsTest < ActiveSupport::TestCase
}
load_paths_count[File.expand_path('../../lib', __FILE__)] -= 1
- filtered = load_paths_count.select { |k, v| v > 1 }
- assert filtered.empty?, filtered.inspect
+ load_paths_count.select! { |k, v| v > 1 }
+ assert load_paths_count.empty?, load_paths_count.inspect
end
end
diff --git a/activesupport/test/rescuable_test.rb b/activesupport/test/rescuable_test.rb
index e099e47e0e..ec9d231125 100644
--- a/activesupport/test/rescuable_test.rb
+++ b/activesupport/test/rescuable_test.rb
@@ -97,7 +97,7 @@ class RescuableTest < ActiveSupport::TestCase
assert_equal expected, result
end
- def test_children_should_inherit_rescue_defintions_from_parents_and_child_rescue_should_be_appended
+ def test_children_should_inherit_rescue_definitions_from_parents_and_child_rescue_should_be_appended
expected = ["WraithAttack", "WraithAttack", "NuclearExplosion", "MadRonon", "CoolError"]
result = @cool_stargate.send(:rescue_handlers).collect {|e| e.first}
assert_equal expected, result
diff --git a/activesupport/test/subscriber_test.rb b/activesupport/test/subscriber_test.rb
new file mode 100644
index 0000000000..253411aa3d
--- /dev/null
+++ b/activesupport/test/subscriber_test.rb
@@ -0,0 +1,40 @@
+require 'abstract_unit'
+require 'active_support/subscriber'
+
+class TestSubscriber < ActiveSupport::Subscriber
+ attach_to :doodle
+
+ cattr_reader :event
+
+ def self.clear
+ @@event = nil
+ end
+
+ def open_party(event)
+ @@event = event
+ end
+
+ private
+
+ def private_party(event)
+ @@event = event
+ end
+end
+
+class SubscriberTest < ActiveSupport::TestCase
+ def setup
+ TestSubscriber.clear
+ end
+
+ def test_attaches_subscribers
+ ActiveSupport::Notifications.instrument("open_party.doodle")
+
+ assert_equal "open_party.doodle", TestSubscriber.event.name
+ end
+
+ def test_does_not_attach_private_methods
+ ActiveSupport::Notifications.instrument("private_party.doodle")
+
+ assert_nil TestSubscriber.event
+ end
+end
diff --git a/activesupport/test/test_case_test.rb b/activesupport/test/test_case_test.rb
deleted file mode 100644
index 08df67827e..0000000000
--- a/activesupport/test/test_case_test.rb
+++ /dev/null
@@ -1,11 +0,0 @@
-require 'abstract_unit'
-
-module ActiveSupport
- class TestCaseTest < ActiveSupport::TestCase
- def test_pending_deprecation
- assert_deprecated do
- pending "should use #skip instead"
- end
- end
- end
-end
diff --git a/activesupport/test/test_test.rb b/activesupport/test/test_test.rb
index 68f9ec6c00..0c8cc1f883 100644
--- a/activesupport/test/test_test.rb
+++ b/activesupport/test/test_test.rb
@@ -87,54 +87,6 @@ class AssertDifferenceTest < ActiveSupport::TestCase
end
end
-class AssertBlankTest < ActiveSupport::TestCase
- BLANK = [ EmptyTrue.new, nil, false, '', ' ', " \n\t \r ", [], {} ]
- NOT_BLANK = [ EmptyFalse.new, Object.new, true, 0, 1, 'x', [nil], { nil => 0 } ]
-
- def test_assert_blank_true
- BLANK.each { |value|
- assert_deprecated { assert_blank value }
- }
- end
-
- def test_assert_blank_false
- NOT_BLANK.each { |v|
- assert_deprecated {
- begin
- assert_blank v
- fail 'should not get to here'
- rescue Exception => e
- assert_match(/is not blank/, e.message)
- end
- }
- }
- end
-end
-
-class AssertPresentTest < ActiveSupport::TestCase
- BLANK = [ EmptyTrue.new, nil, false, '', ' ', " \n\t \r ", [], {} ]
- NOT_BLANK = [ EmptyFalse.new, Object.new, true, 0, 1, 'x', [nil], { nil => 0 } ]
-
- def test_assert_present_true
- NOT_BLANK.each { |v|
- assert_deprecated { assert_present v }
- }
- end
-
- def test_assert_present_false
- BLANK.each { |v|
- assert_deprecated {
- begin
- assert_present v
- fail 'should not get to here'
- rescue Exception => e
- assert_match(/is blank/, e.message)
- end
- }
- }
- end
-end
-
class AlsoDoingNothingTest < ActiveSupport::TestCase
end
diff --git a/activesupport/test/transliterate_test.rb b/activesupport/test/transliterate_test.rb
index ce91c443e1..e0f85f4e7c 100644
--- a/activesupport/test/transliterate_test.rb
+++ b/activesupport/test/transliterate_test.rb
@@ -3,7 +3,6 @@ require 'abstract_unit'
require 'active_support/inflector/transliterate'
class TransliterateTest < ActiveSupport::TestCase
-
def test_transliterate_should_not_change_ascii_chars
(0..127).each do |byte|
char = [byte].pack("U")
@@ -24,12 +23,13 @@ class TransliterateTest < ActiveSupport::TestCase
def test_transliterate_should_work_with_custom_i18n_rules_and_uncomposed_utf8
char = [117, 776].pack("U*") # "ü" as ASCII "u" plus COMBINING DIAERESIS
I18n.backend.store_translations(:de, :i18n => {:transliterate => {:rule => {"ü" => "ue"}}})
- I18n.locale = :de
+ default_locale, I18n.locale = I18n.locale, :de
assert_equal "ue", ActiveSupport::Inflector.transliterate(char)
+ ensure
+ I18n.locale = default_locale
end
def test_transliterate_should_allow_a_custom_replacement_char
assert_equal "a*b", ActiveSupport::Inflector.transliterate("a索b", "*")
end
-
end
diff --git a/activesupport/test/ts_isolated.rb b/activesupport/test/ts_isolated.rb
deleted file mode 100644
index 294d6595f7..0000000000
--- a/activesupport/test/ts_isolated.rb
+++ /dev/null
@@ -1,16 +0,0 @@
-require 'active_support/testing/autorun'
-require 'active_support/test_case'
-require 'rbconfig'
-require 'active_support/core_ext/kernel/reporting'
-
-class TestIsolated < ActiveSupport::TestCase
- ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME'))
-
- Dir["#{File.dirname(__FILE__)}/**/*_test.rb"].each do |file|
- define_method("test #{file}") do
- command = "#{ruby} -Ilib:test #{file}"
- result = silence_stderr { `#{command}` }
- assert $?.to_i.zero?, "#{command}\n#{result}"
- end
- end
-end
diff --git a/activesupport/test/xml_mini/jdom_engine_test.rb b/activesupport/test/xml_mini/jdom_engine_test.rb
index 904ef7b208..ed4de8aba2 100644
--- a/activesupport/test/xml_mini/jdom_engine_test.rb
+++ b/activesupport/test/xml_mini/jdom_engine_test.rb
@@ -178,7 +178,7 @@ if RUBY_PLATFORM =~ /java/
private
def assert_equal_rexml(xml)
parsed_xml = XmlMini.parse(xml)
- hash = XmlMini.with_backend('REXML') { parsed_xml }
+ hash = XmlMini.with_backend('REXML') { XmlMini.parse(xml) }
assert_equal(hash, parsed_xml)
end
end
diff --git a/activesupport/test/xml_mini/libxml_engine_test.rb b/activesupport/test/xml_mini/libxml_engine_test.rb
index e7cb350663..a8df2e1f7b 100644
--- a/activesupport/test/xml_mini/libxml_engine_test.rb
+++ b/activesupport/test/xml_mini/libxml_engine_test.rb
@@ -195,7 +195,8 @@ class LibxmlEngineTest < ActiveSupport::TestCase
private
def assert_equal_rexml(xml)
parsed_xml = XmlMini.parse(xml)
- hash = XmlMini.with_backend('REXML') { parsed_xml }
+ xml.rewind if xml.respond_to?(:rewind)
+ hash = XmlMini.with_backend('REXML') { XmlMini.parse(xml) }
assert_equal(hash, parsed_xml)
end
end
diff --git a/activesupport/test/xml_mini/libxmlsax_engine_test.rb b/activesupport/test/xml_mini/libxmlsax_engine_test.rb
index 07485911c9..d6d90639e2 100644
--- a/activesupport/test/xml_mini/libxmlsax_engine_test.rb
+++ b/activesupport/test/xml_mini/libxmlsax_engine_test.rb
@@ -186,7 +186,8 @@ class LibXMLSAXEngineTest < ActiveSupport::TestCase
private
def assert_equal_rexml(xml)
parsed_xml = XmlMini.parse(xml)
- hash = XmlMini.with_backend('REXML') { parsed_xml }
+ xml.rewind if xml.respond_to?(:rewind)
+ hash = XmlMini.with_backend('REXML') { XmlMini.parse(xml) }
assert_equal(hash, parsed_xml)
end
end
diff --git a/activesupport/test/xml_mini/nokogiri_engine_test.rb b/activesupport/test/xml_mini/nokogiri_engine_test.rb
index 937517786e..2e962576b5 100644
--- a/activesupport/test/xml_mini/nokogiri_engine_test.rb
+++ b/activesupport/test/xml_mini/nokogiri_engine_test.rb
@@ -208,7 +208,8 @@ class NokogiriEngineTest < ActiveSupport::TestCase
private
def assert_equal_rexml(xml)
parsed_xml = XmlMini.parse(xml)
- hash = XmlMini.with_backend('REXML') { parsed_xml }
+ xml.rewind if xml.respond_to?(:rewind)
+ hash = XmlMini.with_backend('REXML') { XmlMini.parse(xml) }
assert_equal(hash, parsed_xml)
end
end
diff --git a/activesupport/test/xml_mini/nokogirisax_engine_test.rb b/activesupport/test/xml_mini/nokogirisax_engine_test.rb
index 84a5c44a87..4f078f31e0 100644
--- a/activesupport/test/xml_mini/nokogirisax_engine_test.rb
+++ b/activesupport/test/xml_mini/nokogirisax_engine_test.rb
@@ -209,7 +209,8 @@ class NokogiriSAXEngineTest < ActiveSupport::TestCase
private
def assert_equal_rexml(xml)
parsed_xml = XmlMini.parse(xml)
- hash = XmlMini.with_backend('REXML') { parsed_xml }
+ xml.rewind if xml.respond_to?(:rewind)
+ hash = XmlMini.with_backend('REXML') { XmlMini.parse(xml) }
assert_equal(hash, parsed_xml)
end
end
diff --git a/activesupport/test/xml_mini/rexml_engine_test.rb b/activesupport/test/xml_mini/rexml_engine_test.rb
index 70a3b918fd..0c1f11803c 100644
--- a/activesupport/test/xml_mini/rexml_engine_test.rb
+++ b/activesupport/test/xml_mini/rexml_engine_test.rb
@@ -30,7 +30,8 @@ class REXMLEngineTest < ActiveSupport::TestCase
private
def assert_equal_rexml(xml)
parsed_xml = XmlMini.parse(xml)
- hash = XmlMini.with_backend('REXML') { parsed_xml }
+ xml.rewind if xml.respond_to?(:rewind)
+ hash = XmlMini.with_backend('REXML') { XmlMini.parse(xml) }
assert_equal(hash, parsed_xml)
end
end
diff --git a/activesupport/test/xml_mini_test.rb b/activesupport/test/xml_mini_test.rb
index a025279e16..d992028323 100644
--- a/activesupport/test/xml_mini_test.rb
+++ b/activesupport/test/xml_mini_test.rb
@@ -106,7 +106,11 @@ module XmlMiniTest
module Nokogiri end
setup do
- @xml = ActiveSupport::XmlMini
+ @xml, @default_backend = ActiveSupport::XmlMini, ActiveSupport::XmlMini.backend
+ end
+
+ teardown do
+ ActiveSupport::XmlMini.backend = @default_backend
end
test "#with_backend should switch backend and then switch back" do
@@ -135,7 +139,11 @@ module XmlMiniTest
module LibXML end
setup do
- @xml = ActiveSupport::XmlMini
+ @xml, @default_backend = ActiveSupport::XmlMini, ActiveSupport::XmlMini.backend
+ end
+
+ teardown do
+ ActiveSupport::XmlMini.backend = @default_backend
end
test "#with_backend should be thread-safe" do